ngram
listlengths 0
67.8k
|
|---|
[
"magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not",
"assert firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed json\" if",
"[\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" ,",
"headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for",
"for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = []",
"logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\")",
"for x in vals]): return code raise ValueError(f\"not able to encode values {vals}\")",
"0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert",
"fmt = firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not a valid uncompressed",
"if firstChars[0] == 123: # { 123 compressed = False else: assert firstChars",
"sublist) chromLength = data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"],",
"True else: fmt = firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not a",
"from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [",
"opener = gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz):",
"if cdsum == 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum",
"= [ [ 0, 2** 8, 'B' ], # char 1 [ -2**",
"TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF )",
"= gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz,",
"def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed = None with open(inbj,",
"m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD)",
"logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert",
"== header_val opener = open if compress: logger.info(\" compressing\") opener = gzip.open with",
"*chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD",
"2**63, 'q' ], # long long 8 ] def getByteSize(vals): for (min_val, max_val,",
"as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz)",
"eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert len(fhd.read()) == 0 return header",
"digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\"",
"VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"",
"def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if",
"inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER",
"{header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading",
"m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\")",
"m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt",
"((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) =",
"-1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)}",
"data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data,",
"header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\")",
"struct.unpack(fmt, pack) if returnBytes: return res, pack else: return res return getValues def",
"compressed = None with open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8 +",
"logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ,",
"lst = data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum =",
"] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename +",
"4 [ -2**31, 2**31, 'l' ], # long 4 [ 0, 2**64, 'Q'",
"assert header_rev == header_val opener = open if compress: logger.info(\" compressing\") opener =",
"import GZIP_MAGIC from ._consts import ( COMPRESS, ) from ._consts import ( TABIX_EXTENSION,",
"fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ),",
"== len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\"",
"compressed = False else: raise ValueError(f\"not a valid uncompressed file. invalid magic header:",
"else: with open(inbj, \"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\" in data",
"long unsigned 4 [ -2**31, 2**31, 'l' ], # long 4 [ 0,",
"f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ",
", *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize",
"as {is_compressed}\") data = None if compressed: with gzip.open(inbj, \"rb\") as fhd: data",
"= data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data)",
"], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256()",
"], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ]",
"gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\",",
"VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2** 8, 'B' ],",
"list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] +",
"= getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof =",
"chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\")",
"'H' ], # short unsigned 2 [ -2**15, 2**15, 'h' ], # short",
"[v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt =",
"decompressing\") opener = gzip.open with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True)",
"open if compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb') as fhd:",
"in BIN_SIZES: if all([x >= min_val and x < max_val for x in",
"getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER",
"TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\"",
"{VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver ==",
"firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] ==",
"data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME)",
"{fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode()",
"logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts import ( COMPRESS, ) from",
") BIN_SIZES = [ [ 0, 2** 8, 'B' ], # char 1",
"8, 'B' ], # char 1 [ -2** 7, 2** 7, 'b' ],",
"data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving",
"{chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d}",
"compressing\") opener = gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in",
"{lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]}",
"short unsigned 2 [ -2**15, 2**15, 'h' ], # short 2 [ 0,",
"7, 'b' ], # char 1 [ 0, 2**16, 'H' ], # short",
"*chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD)",
"= ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk def",
"list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener = open if compress: logger.info(\" compressing\")",
"writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data",
"fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return res, pack else: return res",
"( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2** 8,",
"in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data",
"lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data =",
"{len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD",
"((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert",
"= list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener = open if compress: logger.info(\"",
"import json import struct import hashlib from ._logger import logger, getLogLevel from ._gzip",
"import logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts import ( COMPRESS, )",
"= fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME",
"{digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex",
"= hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\")",
"compressed: with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else: with open(inbj, \"rt\")",
"._consts import ( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION )",
"genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt,",
"} headerJ = json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode()",
"opener = gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\",",
"getFilenames(ingz) compressed = None with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if",
"] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open",
"None if firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt = firstChars[8:] try:",
"saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten =",
"with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) =",
"header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener = open if",
"{VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a valid",
"== GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed json\" if compressed else",
"open(inbj, \"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\"",
"res, pack else: return res return getValues def getFilenames(infile): if infile[-3:] == '.gz'",
"= json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\"",
"getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev",
"# long unsigned 4 [ -2**31, 2**31, 'l' ], # long 4 [",
"= filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed = None",
"fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} -",
"chrom_data[0] chrom_data = [st] + [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] #",
"except: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC}",
": data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [ [\"q\" ,",
"{chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)}",
"fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed",
"header = { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\":",
"{vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res",
"header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False",
"reading {lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,),",
"-2**15, 2**15, 'h' ], # short 2 [ 0, 2**32, 'L' ], #",
"long 4 [ 0, 2**64, 'Q' ], # long long unsigned 8 [",
"return res return getValues def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] ==",
"{inbj} as {is_compressed}\") data = None if compressed: with gzip.open(inbj, \"rb\") as fhd:",
"in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data",
"'h' ], # short 2 [ 0, 2**32, 'L' ], # long unsigned",
"for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if",
"- {chromLength:18,d}\") lst = data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\")",
"is None: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected",
"{lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d)",
"cdsum == 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\"",
": data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ =",
"OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\") opener = gzip.open with",
"json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed =",
"f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen",
"getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex",
"unsigned 8 [ -2**63, 2**63, 'q' ], # long long 8 ] def",
"digestHex = m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex",
"open if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data,",
"m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return",
"= None with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0] ==",
"inid, inbj, inbk) = getFilenames(ingz) compressed = None with open(inbj, \"rb\") as fhd:",
"= [st] + [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]}",
"char 1 [ -2** 7, 2** 7, 'b' ], # char 1 [",
"], # long 4 [ 0, 2**64, 'Q' ], # long long unsigned",
"._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME,",
"= header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK]",
"struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return res, pack",
"[ 0, 2**16, 'H' ], # short unsigned 2 [ -2**15, 2**15, 'h'",
"+ VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed = None with open(indexFile,",
"# sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex",
"valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt",
"from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER,",
"m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c]",
"+ TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener = gzip.open",
"lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for",
"GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed json\" if compressed else \"json\"",
"expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise",
"= TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if",
"header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) =",
"in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum",
"return getValues def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz",
"unsigned 2 [ -2**15, 2**15, 'h' ], # short 2 [ 0, 2**32,",
"fhd: data = json.load(fhd) else: with open(inbj, \"rt\") as fhd: data = json.load(fhd)",
"'B' ], # char 1 [ -2** 7, 2** 7, 'b' ], #",
"), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver",
"# logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1]",
"d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\")",
"cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d)",
"hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val",
"hashlib from ._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts import",
"= None with open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME)",
"as fhd: data = json.load(fhd) else: with open(inbj, \"rt\") as fhd: data =",
"for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in header_fmts]",
"d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d)",
"= json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\",",
"lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen",
"struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex)",
"0, 2**16, 'H' ], # short unsigned 2 [ -2**15, 2**15, 'h' ],",
"= gzip.open with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ),",
"d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam ==",
"from ._consts import ( COMPRESS, ) from ._consts import ( TABIX_EXTENSION, ) from",
"in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\"",
"header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener",
"= getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d)",
"= infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk = ingz +",
"{ \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] }",
"c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if",
"ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s =",
"compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst:",
"data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\")",
"struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt,",
"getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if all([x >= min_val and x",
"logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] #",
">= min_val and x < max_val for x in vals]): return code raise",
"], # long long 8 ] def getByteSize(vals): for (min_val, max_val, code) in",
"= None if compressed: with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else:",
"lst for item in sublist) chromLength = data[\"chromLength\"] header = { \"chroms\" :",
"4 [ 0, 2**64, 'Q' ], # long long unsigned 8 [ -2**63,",
"{fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d)",
"opener = open if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as",
"# logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data) == -1,",
"= infile else: ingz = infile[:-4] inid = infile + TABIX_EXTENSION inbj =",
"for item in sublist) chromLength = data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"],",
"getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d}",
"0, 2**32, 'L' ], # long unsigned 4 [ -2**31, 2**31, 'l' ],",
"opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\"",
"logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed = None with open(indexFile, \"rb\") as",
"fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ),",
"header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] =",
"# logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data = [st]",
"compressed = False else: assert firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed",
"data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [",
"logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data)",
"len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\",",
"logger.info(f\"loading {inbj} as {is_compressed}\") data = None if compressed: with gzip.open(inbj, \"rb\") as",
"struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION",
"8 ] def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if all([x >=",
"\"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None if compressed: with gzip.open(inbj, \"rb\")",
"to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack",
"# fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\",",
"raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR",
"== VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d)",
"{indexFile}\") m = hashlib.sha256() compressed = None with open(indexFile, \"rb\") as fhd: firstChars",
"h in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel()",
"getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes:",
"\"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d}",
"file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if",
"\"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in",
"2 [ -2**15, 2**15, 'h' ], # short 2 [ 0, 2**32, 'L'",
"= getFilenames(ingz) compressed = None with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2)",
"enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt",
"chromLength = data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\"",
"= chrom_data[0] chrom_data = [st] + [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])]",
"header_fmt = \"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val =",
"logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header",
"logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) #",
"# char 1 [ -2** 7, 2** 7, 'b' ], # char 1",
"headerJ = json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ],",
"digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert",
"res = struct.unpack(fmt, pack) if returnBytes: return res, pack else: return res return",
"getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data",
"{GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not",
"compressed = True else: fmt = firstChars[8:] try: fmt = fmt.decode() except: raise",
"ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ]",
"data assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] ==",
"{digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert",
"\"__format_name__\" in data assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\"",
"in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() ==",
"unsigned 4 [ -2**31, 2**31, 'l' ], # long 4 [ 0, 2**64,",
"{fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\") opener",
"opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\")",
"{fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\")",
"fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d}",
"VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m =",
"data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"],",
"{fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a valid",
"d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt",
"inbk) = getFilenames(ingz) compressed = None with open(inbj, \"rb\") as fhd: firstChars =",
"# lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD =",
"m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d)",
"# m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize)",
"GZIP_MAGIC: compressed = True else: fmt = firstChars[8:] try: fmt = fmt.decode() except:",
"*flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize =",
"header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a",
"logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data in lst: #",
"\"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data",
"# { 123 compressed = False else: assert firstChars == GZIP_MAGIC, firstChars compressed",
"getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)):",
"logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK",
"sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex =",
"def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res =",
"ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz,",
"else: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC}",
"((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) =",
"= struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest)",
"compressed = None with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0]",
"= struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" ,",
"= getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ",
"d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len}",
"data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def",
"== VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ,",
"lambda lst: (item for sublist in lst for item in sublist) chromLength =",
"loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed",
"compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb') as fhd: getter =",
"pack) if returnBytes: return res, pack else: return res return getValues def getFilenames(infile):",
"for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms =",
"= [] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\")",
"+ \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h",
"2**32, 'L' ], # long unsigned 4 [ -2**31, 2**31, 'l' ], #",
"else: fmt = firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not a valid",
"= len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest =",
"= struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename +",
"h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in header_fmts] header_dat",
"'{header_fmt}'\") header_val = [h[1] for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val )",
"0, 2**64, 'Q' ], # long long unsigned 8 [ -2**63, 2**63, 'q'",
"firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt = firstChars[8:] try: fmt =",
"{chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) #",
"chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data) ==",
"+ TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid,",
"getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam",
"._gzip import GZIP_MAGIC from ._consts import ( COMPRESS, ) from ._consts import (",
"lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\"",
"'b' ], # char 1 [ 0, 2**16, 'H' ], # short unsigned",
"fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) #",
"BIN_SIZES = [ [ 0, 2** 8, 'B' ], # char 1 [",
"else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None if compressed: with gzip.open(inbj,",
"{VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a valid uncompressed file. invalid magic",
"with open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed",
"== VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert",
"+ VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst: (item for sublist in",
"2 [ 0, 2**32, 'L' ], # long unsigned 4 [ -2**31, 2**31,",
"= TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\")",
"((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex ==",
"firstChars = fhd.read(2) if firstChars[0] == 123: # { 123 compressed = False",
"[ 0, 2**32, 'L' ], # long unsigned 4 [ -2**31, 2**31, 'l'",
"opener = gzip.open with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len,",
"] ] m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h in",
"VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode()",
"] m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h in header_fmts])",
"json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" ,",
"returnBytes: return res, pack else: return res return getValues def getFilenames(infile): if infile[-3:]",
"data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st",
"m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data =",
"logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\")",
"logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min",
", len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ)",
"= getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\")",
"+ VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz, data,",
"struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) #",
"], # short 2 [ 0, 2**32, 'L' ], # long unsigned 4",
"indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed =",
"returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack)",
"\"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val",
"), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest()",
"m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\"",
"fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]}",
"fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" ,",
"== cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\")",
"getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ =",
"d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c",
"with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0] == 123: #",
"-2**31, 2**31, 'l' ], # long 4 [ 0, 2**64, 'Q' ], #",
"= hashlib.sha256() compressed = None with open(indexFile, \"rb\") as fhd: firstChars = fhd.read(",
"._consts import ( COMPRESS, ) from ._consts import ( TABIX_EXTENSION, ) from ._consts",
"VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2** 8, 'B'",
"], # long unsigned 4 [ -2**31, 2**31, 'l' ], # long 4",
"TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES =",
"= fhd.read(2) if firstChars[0] == 123: # { 123 compressed = False else:",
"{is_compressed}\") data = None if compressed: with gzip.open(inbj, \"rb\") as fhd: data =",
"import hashlib from ._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts",
"= fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return res, pack else: return",
"data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\",",
"gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else: with open(inbj, \"rt\") as fhd:",
"= open if compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb') as",
"digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode())",
"= fmt.decode() except: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}.",
"max_val, code) in BIN_SIZES: if all([x >= min_val and x < max_val for",
"json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\",",
"values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum",
") from ._consts import ( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER,",
"ingz = infile[:-4] inid = infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION",
"values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s)",
"fmt = fmt.decode() except: raise ValueError(f\"not a valid uncompressed file. invalid magic header:",
"{GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a valid uncompressed file.",
"expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\") opener =",
"[ -2**31, 2**31, 'l' ], # long 4 [ 0, 2**64, 'Q' ],",
"VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed = None with open(indexFile, \"rb\")",
"compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for",
"magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed =",
"= getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in",
"else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ),",
"getLogLevel from ._gzip import GZIP_MAGIC from ._consts import ( COMPRESS, ) from ._consts",
"def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz = infile",
"fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\"",
"._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts import ( COMPRESS,",
"is_compressed = \"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data",
"+ chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data)",
"'l' ], # long 4 [ 0, 2**64, 'Q' ], # long long",
"d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver}",
"header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\":",
"return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m =",
"logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev)",
"(item for sublist in lst for item in sublist) chromLength = data[\"chromLength\"] header",
"OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a",
"m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\"",
"inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] =",
"TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES",
"2**64, 'Q' ], # long long unsigned 8 [ -2**63, 2**63, 'q' ],",
"], # char 1 [ 0, 2**16, 'H' ], # short unsigned 2",
"loading {indexFile}\") m = hashlib.sha256() compressed = None with open(indexFile, \"rb\") as fhd:",
"else: return res return getValues def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:]",
"struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener = open",
"if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert",
"{chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]}",
"getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz = infile else:",
"TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not",
"2**15, 'h' ], # short 2 [ 0, 2**32, 'L' ], # long",
"firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not a valid uncompressed file. invalid",
"0, 2** 8, 'B' ], # char 1 [ -2** 7, 2** 7,",
"if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd,",
"len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256() header_fmt = \"<\"",
"fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] == GZIP_MAGIC: compressed",
"in sublist) chromLength = data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\" :",
"if returnBytes: return res, pack else: return res return getValues def getFilenames(infile): if",
"# long long unsigned 8 [ -2**63, 2**63, 'q' ], # long long",
"= ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return",
"fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\")",
"[f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" ,",
"< max_val for x in vals]): return code raise ValueError(f\"not able to encode",
"= firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not a valid uncompressed file.",
"\"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data in",
"\"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in",
"return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving",
", len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256() header_fmt =",
"m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev)",
"if compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb') as fhd: getter",
"compressed = None if firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt =",
"saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz",
"<gh_stars>1-10 import gzip import json import struct import hashlib from ._logger import logger,",
"compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None if compressed: with",
"*header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat)",
"], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\"",
"fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m",
"open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0] == 123: # {",
"for sublist in lst for item in sublist) chromLength = data[\"chromLength\"] header =",
"in vals]): return code raise ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd,",
"header_val opener = open if compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile,",
"{sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\")",
"res return getValues def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] == '.bgz':",
"= json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in data assert data[\"__format_name__\"] ==",
"TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener",
"from ._consts import ( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION",
"[ [ 0, 2** 8, 'B' ], # char 1 [ -2** 7,",
"def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if all([x >= min_val and",
"= [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ],",
"[h[1] for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat)",
", VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m",
"= False else: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}.",
"{chromLength:18,d}\") lst = data[lstK] for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum",
"as fhd: data = json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in data",
"len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) #",
"indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed = None with",
"2** 7, 'b' ], # char 1 [ 0, 2**16, 'H' ], #",
"if infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz = infile else: ingz",
"= False else: assert firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed =",
"outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst: (item",
"for chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st =",
"\"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]:",
"chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d)",
"valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed",
"== m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert len(fhd.read()) == 0",
"data = json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in data assert data[\"__format_name__\"]",
"logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data = [st] +",
"\"rb\") as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None",
"in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK]",
"fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len",
"with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else: with open(inbj, \"rt\") as",
"fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD",
"_) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof",
"== VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d)",
"TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener = gzip.open with",
"header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener = open if compress:",
"a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener",
"def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ =",
"= \"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data =",
"[ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\"",
"= filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst: (item for",
"== \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev ==",
"len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] == GZIP_MAGIC: compressed = True else:",
"cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0)",
"\"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ",
"max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(),",
"valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener =",
"logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver,",
"TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj,",
"len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ],",
"= ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener",
"cdsum = sum(chrom_data) st = chrom_data[0] chrom_data = [st] + [v - chrom_data[c]",
"{cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _)",
"from ._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC from ._consts import (",
"fmt_s = struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return",
"infile[-4:] == '.bgz': ingz = infile else: ingz = infile[:-4] inid = infile",
", *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) #",
"== VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a valid uncompressed file. invalid",
"VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS):",
"firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed json\" if compressed",
"\"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0] == 123: # { 123",
"{GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\") opener = gzip.open",
"{chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max",
"{chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data",
"#pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data)",
"], # char 1 [ -2** 7, 2** 7, 'b' ], # char",
"'.gz' or infile[-4:] == '.bgz': ingz = infile else: ingz = infile[:-4] inid",
"logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]:",
"fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ),",
"8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] == GZIP_MAGIC: compressed =",
"header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\")",
"TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress:",
"assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) =",
"infile[:-4] inid = infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk =",
"compressed = True is_compressed = \"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj}",
"= m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex =",
"._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0,",
"# long 4 [ 0, 2**64, 'Q' ], # long long unsigned 8",
"= headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK",
"= open if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as fhd:",
"ingz = infile else: ingz = infile[:-4] inid = infile + TABIX_EXTENSION inbj",
"== TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION",
"((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME),",
"firstChars[0] == 123: # { 123 compressed = False else: assert firstChars ==",
"[f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0]",
"((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER,",
"[\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256() header_fmt",
"struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex)",
") from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [",
"= True is_compressed = \"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj} as",
"assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) =",
"infile else: ingz = infile[:-4] inid = infile + TABIX_EXTENSION inbj = ingz",
"as fhd: firstChars = fhd.read(2) if firstChars[0] == 123: # { 123 compressed",
"compressed is None: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}.",
"( COMPRESS, ) from ._consts import ( TABIX_EXTENSION, ) from ._consts import (",
"123: # { 123 compressed = False else: assert firstChars == GZIP_MAGIC, firstChars",
"[st] + [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\")",
"logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam,",
"= m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile",
"len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam",
"[ 0, 2** 8, 'B' ], # char 1 [ -2** 7, 2**",
"def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten",
"fmt.decode() except: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected",
"data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz +",
"flatten = lambda lst: (item for sublist in lst for item in sublist)",
"False else: assert firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed",
"data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header)",
"f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver",
"from ._gzip import GZIP_MAGIC from ._consts import ( COMPRESS, ) from ._consts import",
"{len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\")",
"data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile = filename",
"if firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt = firstChars[8:] try: fmt",
"{fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\")",
"m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode()",
"VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ),",
"], # long long unsigned 8 [ -2**63, 2**63, 'q' ], # long",
"TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import",
", headerJ.encode() ] ] m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for",
"= open if compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb') as",
"if all([x >= min_val and x < max_val for x in vals]): return",
"sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum,",
"header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\",",
"sublist in lst for item in sublist) chromLength = data[\"chromLength\"] header = {",
"ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\")",
"else: ingz = infile[:-4] inid = infile + TABIX_EXTENSION inbj = ingz +",
"# short 2 [ 0, 2**32, 'L' ], # long unsigned 4 [",
"json import struct import hashlib from ._logger import logger, getLogLevel from ._gzip import",
"), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam",
"((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\"",
"header {header}\") chromLength = header[\"chromLength\"] for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\"",
"{fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed = False else:",
"{cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data",
"f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} ==",
"True is_compressed = \"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\")",
"inid = infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk = ingz",
"= fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] == GZIP_MAGIC:",
"{chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data = [st] + [v",
"fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading",
"-2** 7, 2** 7, 'b' ], # char 1 [ 0, 2**16, 'H'",
"), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header",
"import gzip import json import struct import hashlib from ._logger import logger, getLogLevel",
"], # short unsigned 2 [ -2**15, 2**15, 'h' ], # short 2",
"-2**63, 2**63, 'q' ], # long long 8 ] def getByteSize(vals): for (min_val,",
"all([x >= min_val and x < max_val for x in vals]): return code",
"loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed = None with open(inbj, \"rb\")",
"{cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\"",
"logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d)",
"if compressed is None: raise ValueError(f\"not a valid uncompressed file. invalid magic header:",
"inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ",
"logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\")",
"assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile =",
"= getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex = digestHex.decode()",
"[\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for",
"assert \"__format_name__\" in data assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert",
"vals]): return code raise ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False):",
"== TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS):",
"compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION",
"1 [ -2** 7, 2** 7, 'b' ], # char 1 [ 0,",
"assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) ==",
"fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\")",
"json\" if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None if",
"{chrom_data[-10:]}\") if cdsum == 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} ==",
"# logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data)",
"(ingz, inid, inbj, inbk) = getFilenames(ingz) compressed = None with open(inbj, \"rb\") as",
"'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing",
"digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest",
"fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2]",
"{min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum,",
"= getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength",
"= infile[:-4] inid = infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk",
"open if compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb') as fhd:",
"\"compressed json\" if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None",
"m = hashlib.sha256() compressed = None with open(indexFile, \"rb\") as fhd: firstChars =",
"gzip.open with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d)",
"fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a valid uncompressed file.",
"inbj = ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\")",
") from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import (",
"char 1 [ 0, 2**16, 'H' ], # short unsigned 2 [ -2**15,",
"assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER",
"+ [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt",
"returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len ==",
"fhd.read(2) if firstChars[0] == 123: # { 123 compressed = False else: assert",
"import ( COMPRESS, ) from ._consts import ( TABIX_EXTENSION, ) from ._consts import",
"(chrom_data, d) = getter(f\"<{chromSize}{fmt.decode()}\") m.update(d) chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for",
"assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d)",
"digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF)",
"assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert len(fhd.read())",
"logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def",
"- chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data)",
"'q' ], # long long 8 ] def getByteSize(vals): for (min_val, max_val, code)",
"in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in header_fmts] header_dat =",
"short 2 [ 0, 2**32, 'L' ], # long unsigned 4 [ -2**31,",
"invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise",
"{sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum",
"], [f\"{len(headerJ)}s\" , headerJ.encode() ] ] m = hashlib.sha256() header_fmt = \"<\" +",
"pack else: return res return getValues def getFilenames(infile): if infile[-3:] == '.gz' or",
"in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize",
"# lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest()",
"== '.bgz': ingz = infile else: ingz = infile[:-4] inid = infile +",
"== cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\"",
"COMPRESS, ) from ._consts import ( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME,",
"[ -2**63, 2**63, 'q' ], # long long 8 ] def getByteSize(vals): for",
"2**31, 'l' ], # long 4 [ 0, 2**64, 'Q' ], # long",
"== 123: # { 123 compressed = False else: assert firstChars == GZIP_MAGIC,",
"{outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\")",
"able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt)",
"{fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\")",
"header_rev == header_val opener = open if compress: logger.info(\" compressing\") opener = gzip.open",
"cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data)",
"data = None if compressed: with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd)",
"f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam =",
"((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum}",
"'rb') as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d)",
"getter(f\"<q\") m.update(d) ((fmt,), d) = getter(f\"<c\") m.update(d) # logger.info(f\"cdsum {cdsum} fmt {fmt}\") (chrom_data,",
"None if compressed: with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else: with",
"= json.load(fhd) else: with open(inbj, \"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\"",
"= { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"]",
"magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\"",
"= getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} ==",
"uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt ==",
"m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"]",
"import struct import hashlib from ._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC",
"ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz,",
"headerJ.encode() ] ] m = hashlib.sha256() header_fmt = \"<\" + \"\".join([h[0] for h",
"getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\")",
"try: fmt = fmt.decode() except: raise ValueError(f\"not a valid uncompressed file. invalid magic",
"chrom_data = list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] =",
"max_val for x in vals]): return code raise ValueError(f\"not able to encode values",
"= chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy",
"min_val and x < max_val for x in vals]): return code raise ValueError(f\"not",
"with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj,",
"[\"q\" , VCFBGZ_FORMAT_VER ], [\"q\" , len(headerJ) ], [f\"{len(headerJ)}s\" , headerJ.encode() ] ]",
"= f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d}",
"data, compress=COMPRESS): outfile = filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda",
"{outfile}\") flatten = lambda lst: (item for sublist in lst for item in",
"uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open",
"\"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [ [\"q\"",
"== cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex,",
"ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME",
"(min_val, max_val, code) in BIN_SIZES: if all([x >= min_val and x < max_val",
"# long long 8 ] def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES:",
"if fmt == VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a valid uncompressed",
"{VCFBGZ_FORMAT_NAME}\") opener = open if compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile,",
"header_val = [h[1] for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat)",
"ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener =",
"with open(inbj, \"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\" in data assert",
"), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex",
"opener = open if compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb')",
"as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed = None if",
"else: assert firstChars == GZIP_MAGIC, firstChars compressed = True is_compressed = \"compressed json\"",
"fhd.write(digestSize) digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def",
"VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2** 8, 'B' ], #",
"== GZIP_MAGIC: compressed = True else: fmt = firstChars[8:] try: fmt = fmt.decode()",
"headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength = header[\"chromLength\"] for lstK in",
") compressed = None if firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt",
"GZIP_MAGIC from ._consts import ( COMPRESS, ) from ._consts import ( TABIX_EXTENSION, )",
"data = json.load(fhd) else: with open(inbj, \"rt\") as fhd: data = json.load(fhd) assert",
"for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\")",
"7, 2** 7, 'b' ], # char 1 [ 0, 2**16, 'H' ],",
"sum(chrom_data) st = chrom_data[0] chrom_data = [st] + [v - chrom_data[c] for c,v",
"= getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len",
"header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev",
"return res, pack else: return res return getValues def getFilenames(infile): if infile[-3:] ==",
"chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0:",
"as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s}",
"file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME:",
"genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len",
"== len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d)",
"len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d) = getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam",
"= getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} ==",
"d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\") digestHex =",
"\"numCols\" : data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts",
"= struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD)",
"1 [ 0, 2**16, 'H' ], # short unsigned 2 [ -2**15, 2**15,",
"item in sublist) chromLength = data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\"",
"expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a valid uncompressed",
"assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) =",
"digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof ==",
"code) in BIN_SIZES: if all([x >= min_val and x < max_val for x",
"getter(f\"<{digestLen}s\") digestHex = digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF))",
"st = chrom_data[0] chrom_data = [st] + [v - chrom_data[c] for c,v in",
"lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD)",
"long unsigned 8 [ -2**63, 2**63, 'q' ], # long long 8 ]",
"logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ,",
"= struct.unpack(header_fmt, header_dat) header_rev = list(header_rev) logger.debug(header_rev) assert header_rev == header_val opener =",
"lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst =",
"min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms,",
"code raise ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt):",
"== -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data)",
"{fmt_ver}\") assert fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d)",
"header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) =",
"[] for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d)",
"json.load(fhd) else: with open(inbj, \"rt\") as fhd: data = json.load(fhd) assert \"__format_name__\" in",
"= data[\"chromLength\"] header = { \"chroms\" : data[\"chroms\"], \"numCols\" : data[\"numCols\"], \"chromSizes\" :",
"for chromSize in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,),",
"logger.debug(header_rev) assert header_rev == header_val opener = open if compress: logger.info(\" compressing\") opener",
"VCFBGZ_FORMAT_NAME: compressed = False else: raise ValueError(f\"not a valid uncompressed file. invalid magic",
"invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if fmt == VCFBGZ_FORMAT_NAME: compressed",
"TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename, data, compress=COMPRESS): outfile",
"= gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\",",
"fhd: data = json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in data assert",
"[ 0, 2**64, 'Q' ], # long long unsigned 8 [ -2**63, 2**63,",
"'.bgz': ingz = infile else: ingz = infile[:-4] inid = infile + TABIX_EXTENSION",
"fmt_ver == VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\")",
"lst: (item for sublist in lst for item in sublist) chromLength = data[\"chromLength\"]",
"'L' ], # long unsigned 4 [ -2**31, 2**31, 'l' ], # long",
"range(1,len(chrom_data)): chrom_data[c] = chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum ==",
"{fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME) {len(VCFBGZ_FORMAT_NAME)}\" ((fmt_nam, ), d)",
"\"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize in header[\"chromSizes\"]: logger.info(f\"",
"\"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) =",
"in lst for item in sublist) chromLength = data[\"chromLength\"] header = { \"chroms\"",
"+ len(VCFBGZ_FORMAT_NAME) ) compressed = None if firstChars[:2] == GZIP_MAGIC: compressed = True",
"fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} ==",
"# short unsigned 2 [ -2**15, 2**15, 'h' ], # short 2 [",
"{lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ)",
"inbj, inbk) = getFilenames(ingz) compressed = None with open(inbj, \"rb\") as fhd: firstChars",
"long long unsigned 8 [ -2**63, 2**63, 'q' ], # long long 8",
"not ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] =",
"\"rb\") as fhd: data = json.load(fhd) else: with open(inbj, \"rt\") as fhd: data",
"# logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt}",
"opener = open if compressed: logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb')",
"for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst",
"logger.info(\" decompressing\") opener = gzip.open with opener(indexFile, 'rb') as fhd: getter = genStructValueGetter(fhd,",
"== 0: #pypy assert sum(chrom_data) == -1, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" else:",
"d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\")",
"in header[\"chromSizes\"]: logger.info(f\" {chromSize:12,d} values\") ((cdsum,), d) = getter(f\"<q\") m.update(d) ((fmt,), d) =",
"gzip import json import struct import hashlib from ._logger import logger, getLogLevel from",
"] def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if all([x >= min_val",
"[ -2**15, 2**15, 'h' ], # short 2 [ 0, 2**32, 'L' ],",
"None with open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) )",
"chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms",
"for (min_val, max_val, code) in BIN_SIZES: if all([x >= min_val and x <",
"and x < max_val for x in vals]): return code raise ValueError(f\"not able",
") logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev",
"with opener(outfile, 'wb') as fhd: fhd.write(header_dat) for lstK in [\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]:",
"header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in header_fmts] header_dat = struct.pack(header_fmt,",
"\"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ],",
"= sum(chrom_data) st = chrom_data[0] chrom_data = [st] + [v - chrom_data[c] for",
"= struct.pack(f\"<{chromLength}q\" , *flatten(lst)) # fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen =",
"fhd.write(lstD) # m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen)",
"2** 8, 'B' ], # char 1 [ -2** 7, 2** 7, 'b'",
"2**16, 'H' ], # short unsigned 2 [ -2**15, 2**15, 'h' ], #",
"pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return res, pack else:",
"= None if firstChars[:2] == GZIP_MAGIC: compressed = True else: fmt = firstChars[8:]",
"cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ),",
"False else: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected",
"[ -2** 7, 2** 7, 'b' ], # char 1 [ 0, 2**16,",
"firstChars compressed = True is_compressed = \"compressed json\" if compressed else \"json\" logger.info(f\"loading",
"logger.info(f\" saving {outfile}\") flatten = lambda lst: (item for sublist in lst for",
"\"numberRows\"]: logger.info(f\" writing {lstK:16s} - {chromLength:18,d}\") lst = data[lstK] for chrom_data in lst:",
"8 [ -2**63, 2**63, 'q' ], # long long 8 ] def getByteSize(vals):",
"return code raise ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def",
"f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts",
"chrom_data = [st] + [v - chrom_data[c] for c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data",
"fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) #",
"struct import hashlib from ._logger import logger, getLogLevel from ._gzip import GZIP_MAGIC from",
"= struct.unpack(fmt, pack) if returnBytes: return res, pack else: return res return getValues",
"= lambda lst: (item for sublist in lst for item in sublist) chromLength",
"hashlib.sha256() compressed = None with open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8",
"assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return data def saveVcfGzPy(filename,",
"OR {VCFBGZ_FORMAT_NAME}\") if compressed is None: raise ValueError(f\"not a valid uncompressed file. invalid",
"logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val",
"import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2**",
"m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile =",
"assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"]",
"{cdsum}\" else: assert sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen,",
"{fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD =",
"import ( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from",
"fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk) = getFilenames(ingz) compressed = None",
"), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len",
"m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize) digestHex = m.hexdigest()",
"if compressed else \"json\" logger.info(f\"loading {inbj} as {is_compressed}\") data = None if compressed:",
"struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data) fhd.write(lstD) m.update(lstD) # sys.exit(0) # lstD = struct.pack(f\"<{chromLength}q\" , *flatten(lst))",
"def loadVcfGzPy(filename): indexFile = filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256()",
"{max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data)",
"sum(chrom_data) == cdsum, f\"sum(chrom_data) {sum(chrom_data)} == cdsum {cdsum}\" header[lstK].append(chrom_data) ((digestLen, ), d) =",
"getValues def getFilenames(infile): if infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz =",
"logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev = struct.unpack(header_fmt, header_dat) header_rev =",
"chrom_data in lst: # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0]",
"= getter(f\"<{fmt_len}s\") m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME,",
"return ingz, inid, inbj, inbk def saveTabixPy(ingz, data, compress=COMPRESS): data[\"__format_name__\"] = TABIXPY_FORMAT_NAME data[\"__format_ver__\"",
"data[\"__format_ver__\" ] = TABIXPY_FORMAT_VER outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener =",
"long long 8 ] def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if",
"x < max_val for x in vals]): return code raise ValueError(f\"not able to",
"infile + TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION",
"file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is None:",
"= struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val) m.update(header_dat) if getLogLevel() == \"DEBUG\": header_rev =",
"= genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert",
"= list(chrom_data) # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") for c in range(1,len(chrom_data)): chrom_data[c] = chrom_data[c]",
"( TABIX_EXTENSION, ) from ._consts import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts",
"filename + VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst: (item for sublist",
"\"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1] for",
"# char 1 [ 0, 2**16, 'H' ], # short unsigned 2 [",
"if compressed: with gzip.open(inbj, \"rb\") as fhd: data = json.load(fhd) else: with open(inbj,",
"json.load(fhd) assert \"__format_name__\" in data assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME",
"x in vals]): return code raise ValueError(f\"not able to encode values {vals}\") def",
"uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if compressed is",
"gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid,",
"'Q' ], # long long unsigned 8 [ -2**63, 2**63, 'q' ], #",
"getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header = json.loads(headerJ) logger.debug(f\" header {header}\") chromLength =",
"{chrom_data[-10:]}\") cdsum = sum(chrom_data) st = chrom_data[0] chrom_data = [st] + [v -",
"digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename): indexFile = filename",
"raise ValueError(f\"not able to encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s",
"\"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ] == TABIXPY_FORMAT_VER return",
": data[\"numCols\"], \"chromSizes\" : data[\"chromSizes\"], \"chromLength\": data[\"chromLength\"] } headerJ = json.dumps(header) header_fmts =",
"or infile[-4:] == '.bgz': ingz = infile else: ingz = infile[:-4] inid =",
"m.update(lstD) digestHex = m.hexdigest() digestLen = len(digestHex) digestSize = struct.pack(f\"<q\", digestLen) m.update(digestSize) fhd.write(digestSize)",
"m.update(d) fmt_nam = fmt_nam.decode() logger.debug(f\" fmt_nam {fmt_nam}\") assert fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam}",
"compress: logger.debug(\"compressing\") opener = gzip.open with opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1)",
"== '.gz' or infile[-4:] == '.bgz': ingz = infile else: ingz = infile[:-4]",
"infile[-3:] == '.gz' or infile[-4:] == '.bgz': ingz = infile else: ingz =",
"if compress: logger.info(\" compressing\") opener = gzip.open with opener(outfile, 'wb') as fhd: fhd.write(header_dat)",
"= [h[1] for h in header_fmts] header_dat = struct.pack(header_fmt, *header_val ) logger.debug(header_dat) logger.debug(header_val)",
"in data assert \"__format_ver__\" in data assert data[\"__format_name__\"] == TABIXPY_FORMAT_NAME assert data[\"__format_ver__\" ]",
"getter(\"<q\") m.update(d) logger.debug(f\" fmt_len {fmt_len}\") assert fmt_len == len(VCFBGZ_FORMAT_NAME), f\"fmt_len {fmt_len} == len(VCFBGZ_FORMAT_NAME)",
"VCFBGZ_EXTENSION logger.info(f\" saving {outfile}\") flatten = lambda lst: (item for sublist in lst",
"chrom_data[c] + chrom_data[c-1] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") if cdsum == 0: #pypy assert",
"VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" fmt_ver {fmt_ver}\") assert fmt_ver",
"m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert len(fhd.read()) == 0 return",
"( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION, VCFBGZ_EOF",
"{ 123 compressed = False else: assert firstChars == GZIP_MAGIC, firstChars compressed =",
"123 compressed = False else: assert firstChars == GZIP_MAGIC, firstChars compressed = True",
"VCFBGZ_EOF ) BIN_SIZES = [ [ 0, 2** 8, 'B' ], # char",
"None: raise ValueError(f\"not a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC}",
"digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF assert len(fhd.read()) ==",
"logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof == VCFBGZ_EOF",
"[\"realPositions\", \"firstPositions\", \"lastPositions\", \"numberRows\"]: logger.info(f\" reading {lstK}\") header[lstK] = [] for chromSize in",
"fmt_nam == VCFBGZ_FORMAT_NAME, f\"fmt_nam {fmt_nam} == VCFBGZ_FORMAT_NAME {VCFBGZ_FORMAT_NAME}\" ((fmt_ver, ), d) = getter(\"<q\")",
"invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") opener = open if compressed:",
"{VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d)",
"digestHex = m.hexdigest() digest = struct.pack(f\"<{digestLen}s\", digestHex.encode()) fhd.write(digest) logger.info(digestHex) fhd.write(VCFBGZ_EOF) return def loadVcfGzPy(filename):",
"long 8 ] def getByteSize(vals): for (min_val, max_val, code) in BIN_SIZES: if all([x",
"outfileJ = ingz + TABIXPY_EXTENSION logger.info(f\"saving {outfileJ}\") opener = open if compress: logger.debug(\"compressing\")",
"{fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD = struct.pack(f\"<{len(chrom_data)}q\" , *chrom_data)",
"open(indexFile, \"rb\") as fhd: firstChars = fhd.read( 8 + len(VCFBGZ_FORMAT_NAME) ) compressed =",
"= struct.calcsize(fmt) pack = fhd.read(fmt_s) res = struct.unpack(fmt, pack) if returnBytes: return res,",
"filename + VCFBGZ_EXTENSION logger.info(f\" loading {indexFile}\") m = hashlib.sha256() compressed = None with",
"c,v in enumerate(chrom_data[1:])] # logger.info(f\"chrom_data {chrom_data[:10]} {chrom_data[-10:]}\") fmt = getByteSize(chrom_data) fms = f\"<qc{len(chrom_data)}{fmt}\"",
"cdsum {cdsum:21,d} fmts {fms}\") lstD = struct.pack(fms, cdsum, fmt.encode(), *chrom_data) # lstD =",
"import ( TABIXPY_FORMAT_NAME, TABIXPY_FORMAT_VER, TABIXPY_EXTENSION ) from ._consts import ( VCFBGZ_FORMAT_VER, VCFBGZ_FORMAT_NAME, VCFBGZ_EXTENSION,",
"+ TABIX_EXTENSION inbj = ingz + TABIXPY_EXTENSION inbk = ingz + VCFBGZ_EXTENSION assert",
"= \"<\" + \"\".join([h[0] for h in header_fmts]) logger.debug(f\"header_fmt '{header_fmt}'\") header_val = [h[1]",
"a valid uncompressed file. invalid magic header: {fmt}. expected {GZIP_MAGIC} OR {VCFBGZ_FORMAT_NAME}\") if",
"VCFBGZ_FORMAT_VER, f\"fmt_ver {fmt_ver} == VCFBGZ_FORMAT_VER {VCFBGZ_FORMAT_VER}\" ((lenHeaderJ, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"",
"lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\") m.update(d) headerJ = headerJ.decode() header =",
"inbk = ingz + VCFBGZ_EXTENSION assert not ingz.endswith(\".\") return ingz, inid, inbj, inbk",
"fms = f\"<qc{len(chrom_data)}{fmt}\" logger.info(f\" fmt {fmt} min {min(chrom_data):15,d} max {max(chrom_data):15,d} len {len(chrom_data):18,d} cdsum",
"= True else: fmt = firstChars[8:] try: fmt = fmt.decode() except: raise ValueError(f\"not",
"= digestHex.decode() logger.info(f\"digestHex {digestHex}\") assert digestHex == m.hexdigest() eof = fhd.read(len(VCFBGZ_EOF)) assert eof",
"saving {outfile}\") flatten = lambda lst: (item for sublist in lst for item",
"((digestLen, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"digestLen {digestLen}\") ((digestHex, ), _) = getter(f\"<{digestLen}s\")",
"encode values {vals}\") def genStructValueGetter(fhd, returnBytes=False): def getValues(fmt): fmt_s = struct.calcsize(fmt) pack =",
"BIN_SIZES: if all([x >= min_val and x < max_val for x in vals]):",
"None with open(inbj, \"rb\") as fhd: firstChars = fhd.read(2) if firstChars[0] == 123:",
"opener(outfileJ, \"wt\") as fhd: json.dump(data, fhd, indent=1) def loadTabixPy(ingz): (ingz, inid, inbj, inbk)",
"fhd: firstChars = fhd.read(2) if firstChars[0] == 123: # { 123 compressed =",
"), d) = getter(\"<q\") m.update(d) logger.debug(f\" lenHeaderJ {lenHeaderJ}\") ((headerJ, ), d) = getter(f\"<{lenHeaderJ}s\")",
"as fhd: getter = genStructValueGetter(fhd, returnBytes=True) ((fmt_len, ), d) = getter(\"<q\") m.update(d) logger.debug(f\"",
"header_fmts = [ [\"q\" , len(VCFBGZ_FORMAT_NAME) ], [f\"{len(VCFBGZ_FORMAT_NAME)}s\", VCFBGZ_FORMAT_NAME.encode() ], [\"q\" , VCFBGZ_FORMAT_VER"
] |
[
"omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient in accordance",
"# Чем больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def",
"return val and val & (val - 1) == 0 def gen_halfs(arrays, size):",
"test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0, 1, 3]",
"j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) ==",
"np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples)",
"2], [3, 4], [5, 6], [7]] def split_array(array, where): return array[:where], array[where:] def",
"is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two') self.nsamples = nsamples self.omega0 =",
"decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs",
"gen_halfs(arrays, size): halfsize = size // 2 for array in arrays: pair =",
"= logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable): one, two = tee(iterable)",
"== [[1], [3]] assert j.tolist() == [[2], [4]] def split_vertical(mat): mat = np.asarray(mat)",
"(val - 1) == 0 def gen_halfs(arrays, size): halfsize = size // 2",
"accordance with wavelet type return 11 * (self.omega0 / 70) / self.scales def",
"[[1], [3]] assert j.tolist() == [[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half",
"5, 6, 7, 8, 9], ] def iconcatenate_pairs(items): for pair in pairwise(items): yield",
"equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad])",
"сколько базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves =",
"j.tolist() == [[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] /",
"def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be",
"* PI2 / nsamples return angfreq # Чем больше, тем больше октав снизу",
"] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right for left,",
"/ samplerate # сколько базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count /",
"assert j.tolist() == [[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1]",
"тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution,",
"one, two = tee(iterable) next(two, None) return zip(one, two) def grouper(iterable, n): return",
"для базового вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0 ** 2)) /",
"= (omega0 + np.sqrt(2 + omega0 ** 2)) / PI2 # scale -",
"power of two') self.nsamples = nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate,",
"2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad",
"def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional power of two",
"self.original_size = len(array) self.pad_size = self.size - self.original_size if self.pad_size == 0: return",
"skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count",
"yield np.concatenate(pair) def is_power_of_two(val): return val and val & (val - 1) ==",
"== [[1, 2], [3, 4], [5, 6], [7]] def split_array(array, where): return array[:where],",
"поместится (диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count",
"- количество отсчетов для базового вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0",
"j = split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1], [3]] assert j.tolist()",
"last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def",
"of two') self.nsamples = nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution,",
"array elif self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant') assert False #",
"8, 9], ] def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val):",
"return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i,",
"return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]])",
"def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1,",
"pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and val & (val - 1)",
"split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1], [3]] assert j.tolist() == [[2],",
"i.tolist() == [[1], [3]] assert j.tolist() == [[2], [4]] def split_vertical(mat): mat =",
"for j in filter(len, pair): yield j def test_gen_halfs(): d = [ [1,2,3,4],",
"pairwise(iterable): one, two = tee(iterable) next(two, None) return zip(one, two) def grouper(iterable, n):",
"# Cut pad size from last last_image_size = padder.original_size // decimate overlapped_halfs[-1] =",
"as fractional power of two \"\"\" # morle_samples - количество отсчетов для базового",
"blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples)",
"70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks",
"= [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical,",
"def __call__(self, array): self.original_size = len(array) self.pad_size = self.size - self.original_size if self.pad_size",
"= np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks *",
"октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\"",
"np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes",
"mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0, 1, 3] class",
"# Set coefficient in accordance with wavelet type return 11 * (self.omega0 /",
"samplerate * PI2 / nsamples return angfreq # Чем больше, тем больше октав",
"1:] -= nsamples angfreq *= samplerate * PI2 / nsamples return angfreq #",
"[[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert [list(r) for r",
"sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as",
"* (self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks =",
"next(two, None) return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def",
"omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two') self.nsamples =",
"import partial from itertools import chain, tee import logging import numpy as np",
"angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient in accordance with wavelet type",
"8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)] == \\ [ [1, 2,",
"def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2",
"** 2)) / PI2 # scale - измеряется в секундах minimal_scale = morle_samples",
"split_array(array, halfsize) for j in filter(len, pair): yield j def test_gen_halfs(): d =",
"= map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0, 1, 3] class NumpyPadder(object):",
"samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval)",
"= padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples,",
"np.concatenate(pair) def is_power_of_two(val): return val and val & (val - 1) == 0",
"def gen_halfs(arrays, size): halfsize = size // 2 for array in arrays: pair",
"def __init__(self, size): self.size = size def __call__(self, array): self.original_size = len(array) self.pad_size",
"def frequencies(self): # Set coefficient in accordance with wavelet type return 11 *",
"windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece",
"here raise Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution,",
"in items: yield last last = elem yield fn(last) def test_map_only_last(): mapped =",
"return array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable) last = next(items) for",
"array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable) last = next(items) for elem",
"split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable) last =",
"6], [7]] def split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable): items =",
"= split_array(array, halfsize) for j in filter(len, pair): yield j def test_gen_halfs(): d",
"samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional power of two \"\"\" #",
"PI2 = 2 * np.pi def pairwise(iterable): one, two = tee(iterable) next(two, None)",
"samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:]",
":last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq",
"import numpy as np log = logging.getLogger(__name__) PI2 = 2 * np.pi def",
"morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval",
"pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and val & (val",
"= 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional power",
"logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable): one, two = tee(iterable) next(two,",
"for array in arrays: pair = split_array(array, halfsize) for j in filter(len, pair):",
"last = elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3))",
"**kwargs): half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples)",
"/ 2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2,",
"= [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4],",
":half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5, 6],",
"= size // 2 for array in arrays: pair = split_array(array, halfsize) for",
"= int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2",
"np.asarray(mat) half = mat.shape[1] / 2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs():",
"= mat.shape[1] / 2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs =",
"iter(iterable) last = next(items) for elem in items: yield last last = elem",
"= self.size - self.original_size if self.pad_size == 0: return array elif self.pad_size >",
"size def __call__(self, array): self.original_size = len(array) self.pad_size = self.size - self.original_size if",
"size < 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not",
"return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq =",
"yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped) ==",
"self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder,",
"/ self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks =",
"self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks =",
"partial from itertools import chain, tee import logging import numpy as np log",
"blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self,",
"def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with",
"minimal_scale = morle_samples / samplerate # сколько базовых вейвлетов поместится (диапазон частот) freq_interval",
"np.pi def pairwise(iterable): one, two = tee(iterable) next(two, None) return zip(one, two) def",
"self.original_size if self.pad_size == 0: return array elif self.pad_size > 0: return np.pad(array,",
"n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j = split_vertical([[1, 2], [3,",
"j in filter(len, pair): yield j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7],",
"chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece,",
"sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar,",
"= split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1], [3]] assert j.tolist() ==",
"nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples,",
"# scale - измеряется в секундах minimal_scale = morle_samples / samplerate # сколько",
"+ np.sqrt(2 + omega0 ** 2)) / PI2 # scale - измеряется в",
"= morle_samples / samplerate # сколько базовых вейвлетов поместится (диапазон частот) freq_interval =",
"// decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\"",
"with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate,",
"in arrays: pair = split_array(array, halfsize) for j in filter(len, pair): yield j",
"np.sqrt(2 + omega0 ** 2)) / PI2 # scale - измеряется в секундах",
"class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples",
"[[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] / 2 return",
"windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left +",
"np.pad(array, (0, self.pad_size), 'constant') assert False # Should never come here raise Exception('Pad",
"two \"\"\" # morle_samples - количество отсчетов для базового вейвлета morle_samples = (omega0",
"mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5, 6], [7,",
"elem in items: yield last last = elem yield fn(last) def test_map_only_last(): mapped",
"= map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) )",
"equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate,",
"/ morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves)",
"LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional",
"измеряется в секундах minimal_scale = morle_samples / samplerate # сколько базовых вейвлетов поместится",
"chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad =",
"[4, 5, 6], [7, 8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)] ==",
"self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate)",
"blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_,",
"= angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient in accordance with wavelet",
"= tee(iterable) next(two, None) return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] *",
"1, 3] class NumpyPadder(object): def __init__(self, size): self.size = size def __call__(self, array):",
"& (val - 1) == 0 def gen_halfs(arrays, size): halfsize = size //",
"def map_only_last(fn, iterable): items = iter(iterable) last = next(items) for elem in items:",
"in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and val & (val -",
"[4]] def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] / 2 return mat[:,",
"pairs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert [list(r)",
"angfreq *= samplerate * PI2 / nsamples return angfreq # Чем больше, тем",
"Чем больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count,",
"= LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval",
"half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5, 6], [7, 8,",
"from functools import partial from itertools import chain, tee import logging import numpy",
"iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and val",
"NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces,",
"2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale /",
"assert i.tolist() == [[1], [3]] assert j.tolist() == [[2], [4]] def split_vertical(mat): mat",
"chain, tee import logging import numpy as np log = logging.getLogger(__name__) PI2 =",
"в секундах minimal_scale = morle_samples / samplerate # сколько базовых вейвлетов поместится (диапазон",
"progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder",
"0: return array elif self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant') assert",
"== [0, 1, 3] class NumpyPadder(object): def __init__(self, size): self.size = size def",
"val and val & (val - 1) == 0 def gen_halfs(arrays, size): halfsize",
"3, 4, 5, 6], [4, 5, 6, 7, 8, 9], ] def iconcatenate_pairs(items):",
"visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution))",
"= omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property",
"\"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -=",
"[7]] def split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable)",
"in grouper(halfs, 2)] # Cut pad size from last last_image_size = padder.original_size //",
"import chain, tee import logging import numpy as np log = logging.getLogger(__name__) PI2",
"list(mapped) == [0, 1, 3] class NumpyPadder(object): def __init__(self, size): self.size = size",
"coefficient in accordance with wavelet type return 11 * (self.omega0 / 70) /",
"2)) / PI2 # scale - измеряется в секундах minimal_scale = morle_samples /",
"as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples",
"decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder =",
"where): return array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable) last = next(items)",
"numpy as np log = logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable):",
"two) def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j =",
"pad size from last last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size]",
"for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left",
"6], [7, 8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)] == \\ [",
"indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes * scale_resolution)",
"False # Should never come here raise Exception('Pad size < 0') class BaseWaveletBox(object):",
"range(3)) assert list(mapped) == [0, 1, 3] class NumpyPadder(object): def __init__(self, size): self.size",
"* np.pi def pairwise(iterable): one, two = tee(iterable) next(two, None) return zip(one, two)",
"itertools import chain, tee import logging import numpy as np log = logging.getLogger(__name__)",
"int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 **",
"'constant') assert False # Should never come here raise Exception('Pad size < 0')",
"in accordance with wavelet type return 11 * (self.omega0 / 70) / self.scales",
"[0, 1, 3] class NumpyPadder(object): def __init__(self, size): self.size = size def __call__(self,",
"autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional power of two \"\"\"",
"**kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return",
"1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes * scale_resolution) return minimal_scale * logarithmic_indexes",
"overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces",
"iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [",
"half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces",
"[ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images))",
"map_only_last(fn, iterable): items = iter(iterable) last = next(items) for elem in items: yield",
"tee import logging import numpy as np log = logging.getLogger(__name__) PI2 = 2",
"overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\"",
"map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces",
"количество отсчетов для базового вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0 **",
"return 11 * (self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs):",
"overlapped_halfs = [left + right for left, right in grouper(halfs, 2)] # Cut",
"omega0): \"\"\" Compute scales as fractional power of two \"\"\" # morle_samples -",
"def split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable): items = iter(iterable) last",
"= overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies",
"zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks",
"отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as",
"samplerate # сколько базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count / morle_samples",
"= next(items) for elem in items: yield last last = elem yield fn(last)",
"= iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images =",
"// 2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks)",
"**kwargs) for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs =",
"вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0 ** 2)) / PI2 #",
"= max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count =",
"in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right",
"# blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def",
"5, 6], [7, 8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)] == \\",
"fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0,",
"nsamples return angfreq # Чем больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF",
"self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs)",
"power of two \"\"\" # morle_samples - количество отсчетов для базового вейвлета morle_samples",
"type return 11 * (self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound, progressbar,",
"больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate,",
"[3]] assert j.tolist() == [[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half =",
"= overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in",
"next(halfs) overlapped_halfs = [left + right for left, right in grouper(halfs, 2)] #",
"- self.original_size if self.pad_size == 0: return array elif self.pad_size > 0: return",
"@property def frequencies(self): # Set coefficient in accordance with wavelet type return 11",
"frequencies(self): # Set coefficient in accordance with wavelet type return 11 * (self.omega0",
"left, right in grouper(halfs, 2)] # Cut pad size from last last_image_size =",
"9], ] def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return",
"morle_samples / samplerate # сколько базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count",
"next(items) for elem in items: yield last last = elem yield fn(last) def",
"assert False # Should never come here raise Exception('Pad size < 0') class",
"NumpyPadder(object): def __init__(self, size): self.size = size def __call__(self, array): self.original_size = len(array)",
"assert [list(r) for r in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4,",
"arrays: pair = split_array(array, halfsize) for j in filter(len, pair): yield j def",
"map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0, 1, 3] class NumpyPadder(object): def",
"> 0: return np.pad(array, (0, self.pad_size), 'constant') assert False # Should never come",
"LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval /",
"nsamples angfreq *= samplerate * PI2 / nsamples return angfreq # Чем больше,",
"maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1,",
"\\ [ [1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8,",
"self.size = size def __call__(self, array): self.original_size = len(array) self.pad_size = self.size -",
"half = mat.shape[1] / 2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs",
"5, 6], [4, 5, 6, 7, 8, 9], ] def iconcatenate_pairs(items): for pair",
"gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks",
"test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2],",
"[5, 6], [7]] def split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable): items",
"chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces =",
"two') self.nsamples = nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0)",
"+ omega0 ** 2)) / PI2 # scale - измеряется в секундах minimal_scale",
"zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]]) assert",
"__call__(self, array): self.original_size = len(array) self.pad_size = self.size - self.original_size if self.pad_size ==",
"windowed_pieces ] halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right for",
"morle_samples - количество отсчетов для базового вейвлета morle_samples = (omega0 + np.sqrt(2 +",
"self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant') assert False # Should never",
"samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient",
"[ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5,",
"[[1, 2], [3, 4], [5, 6], [7]] def split_array(array, where): return array[:where], array[where:]",
"9]] assert [list(r) for r in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3,",
"Should never come here raise Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self,",
"== [[2], [4]] def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] / 2",
"test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1], [3]]",
"\"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate",
"(omega0 + np.sqrt(2 + omega0 ** 2)) / PI2 # scale - измеряется",
"Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if",
"progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_:",
"Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples",
"last = next(items) for elem in items: yield last last = elem yield",
"raise Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0):",
"angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 +",
"np log = logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable): one, two",
"iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4, 5, 6], [4, 5, 6,",
"d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2], [3,",
"отсчетов для базового вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0 ** 2))",
"/ scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes",
"test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert",
"- измеряется в секундах minimal_scale = morle_samples / samplerate # сколько базовых вейвлетов",
"<filename>analyze/wavelet/base.py from functools import partial from itertools import chain, tee import logging import",
"7, 8, 9], ] def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def",
"i, j = split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1], [3]] assert",
"# сколько базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves",
"// 2 for array in arrays: pair = split_array(array, halfsize) for j in",
"last last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1)",
"from itertools import chain, tee import logging import numpy as np log =",
"omega0 ** 2)) / PI2 # scale - измеряется в секундах minimal_scale =",
"2], [3, 4]]) assert i.tolist() == [[1], [3]] assert j.tolist() == [[2], [4]]",
"of two \"\"\" # morle_samples - количество отсчетов для базового вейвлета morle_samples =",
"not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two') self.nsamples = nsamples self.omega0",
"4]]) assert i.tolist() == [[1], [3]] assert j.tolist() == [[2], [4]] def split_vertical(mat):",
"iterable): items = iter(iterable) last = next(items) for elem in items: yield last",
"scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two') self.nsamples",
"blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples =",
"__init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power",
"np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate * PI2 /",
"= self.nsamples // 2 chunks = gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces =",
"базового вейвлета morle_samples = (omega0 + np.sqrt(2 + omega0 ** 2)) / PI2",
"zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j",
"= [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert [list(r) for",
"def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and",
"val & (val - 1) == 0 def gen_halfs(arrays, size): halfsize = size",
"come here raise Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate,",
"pair = split_array(array, halfsize) for j in filter(len, pair): yield j def test_gen_halfs():",
"= chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right for left, right in",
"частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate",
"items: yield last last = elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda",
"if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two') self.nsamples = nsamples",
"size): self.size = size def __call__(self, array): self.original_size = len(array) self.pad_size = self.size",
"wavelet type return 11 * (self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound,",
"= NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs( chain([zero_pad],",
"[zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs)",
"complex_images)) next(halfs) overlapped_halfs = [left + right for left, right in grouper(halfs, 2)]",
"= samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval =",
"samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale",
"\"\"\" # morle_samples - количество отсчетов для базового вейвлета morle_samples = (omega0 +",
"- 1) == 0 def gen_halfs(arrays, size): halfsize = size // 2 for",
"* n)) def test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]]) assert i.tolist()",
"grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j = split_vertical([[1, 2],",
"and val & (val - 1) == 0 def gen_halfs(arrays, size): halfsize =",
"= np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32)",
"nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of",
"log = logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable): one, two =",
"[3, 4], [5, 6], [7]] def split_array(array, where): return array[:where], array[where:] def map_only_last(fn,",
"+ 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes * scale_resolution) return minimal_scale *",
"return angfreq # Чем больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF =",
"padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate):",
"/ skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count",
"np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes * scale_resolution) return minimal_scale",
"self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient in accordance with",
"BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must",
"logging import numpy as np log = logging.getLogger(__name__) PI2 = 2 * np.pi",
"split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] / 2 return mat[:, :half], mat[:,",
"[4, 5, 6, 7, 8, 9], ] def iconcatenate_pairs(items): for pair in pairwise(items):",
"def pairwise(iterable): one, two = tee(iterable) next(two, None) return zip(one, two) def grouper(iterable,",
"angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate * PI2 / nsamples return",
"array in arrays: pair = split_array(array, halfsize) for j in filter(len, pair): yield",
"2 for array in arrays: pair = split_array(array, halfsize) for j in filter(len,",
"1) == 0 def gen_halfs(arrays, size): halfsize = size // 2 for array",
"grouper(halfs, 2)] # Cut pad size from last last_image_size = padder.original_size // decimate",
"4, 5, 6], [4, 5, 6, 7, 8, 9], ] def iconcatenate_pairs(items): for",
"def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]",
"0 def gen_halfs(arrays, size): halfsize = size // 2 for array in arrays:",
"self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples //",
"def test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]]) assert i.tolist() == [[1],",
"progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs):",
"overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular",
"return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4,",
"3], [4, 5, 6], [7, 8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)]",
"len(array) self.pad_size = self.size - self.original_size if self.pad_size == 0: return array elif",
"frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *=",
"*= samplerate * PI2 / nsamples return angfreq # Чем больше, тем больше",
"4], [5, 6], [7]] def split_array(array, where): return array[:where], array[where:] def map_only_last(fn, iterable):",
"freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes =",
"padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples) overlapped_blocks = iconcatenate_pairs(",
"= np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes * scale_resolution) return",
"samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1,",
"filter(len, pair): yield j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert",
"scale - измеряется в секундах minimal_scale = morle_samples / samplerate # сколько базовых",
"r in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4, 5, 6], [4,",
"2, 3, 4, 5, 6], [4, 5, 6, 7, 8, 9], ] def",
"6, 7, 8, 9], ] def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair)",
"array[where:] def map_only_last(fn, iterable): items = iter(iterable) last = next(items) for elem in",
"last last = elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1,",
"tee(iterable) next(two, None) return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] * n))",
"базовых вейвлетов поместится (диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF",
"scales as fractional power of two \"\"\" # morle_samples - количество отсчетов для",
"2 * np.pi def pairwise(iterable): one, two = tee(iterable) next(two, None) return zip(one,",
"as np log = logging.getLogger(__name__) PI2 = 2 * np.pi def pairwise(iterable): one,",
"# Should never come here raise Exception('Pad size < 0') class BaseWaveletBox(object): def",
"= np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate * PI2",
"PI2 # scale - измеряется в секундах minimal_scale = morle_samples / samplerate #",
"0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise",
"= sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks,",
"] def iconcatenate_pairs(items): for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val",
"[5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5, 6], [7]]",
"== 0 def gen_halfs(arrays, size): halfsize = size // 2 for array in",
"angfreq # Чем больше, тем больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5",
"right for left, right in grouper(halfs, 2)] # Cut pad size from last",
"Cut pad size from last last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:,",
"Set coefficient in accordance with wavelet type return 11 * (self.omega0 / 70)",
"self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2)",
"(диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count /",
"from last last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs,",
"mat.shape[1] / 2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1,",
"mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3], [4, 5,",
"n)) def test_split_vertical(): i, j = split_vertical([[1, 2], [3, 4]]) assert i.tolist() ==",
"for left, right in grouper(halfs, 2)] # Cut pad size from last last_image_size",
"def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical(): i, j = split_vertical([[1,",
"def split_vertical(mat): mat = np.asarray(mat) half = mat.shape[1] / 2 return mat[:, :half],",
"[7, 8, 9]] assert [list(r) for r in iconcatenate_pairs(pairs)] == \\ [ [1,",
"/ nsamples return angfreq # Чем больше, тем больше октав снизу будет отброшено",
"= sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar,",
"[left + right for left, right in grouper(halfs, 2)] # Cut pad size",
"[1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5, 6],",
"секундах minimal_scale = morle_samples / samplerate # сколько базовых вейвлетов поместится (диапазон частот)",
"freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval",
"sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks)",
"omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def",
"max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale",
"skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count +",
"= np.asarray(mat) half = mat.shape[1] / 2 return mat[:, :half], mat[:, half:] def",
"be power of two') self.nsamples = nsamples self.omega0 = omega0 self.scales = autoscales(nsamples,",
"def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped) == [0, 1,",
"samplerate) @property def frequencies(self): # Set coefficient in accordance with wavelet type return",
"decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute",
"angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate *",
"angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq",
"assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5, 6], [7]] def split_array(array,",
"= gen_halfs(blocks, self.nsamples) padder = NumpyPadder(half_nsamples) equal_sized_pieces = map_only_last(padder, chunks) zero_pad = np.zeros(half_nsamples)",
"chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right for left, right in grouper(halfs,",
"array): self.original_size = len(array) self.pad_size = self.size - self.original_size if self.pad_size == 0:",
"(0, self.pad_size), 'constant') assert False # Should never come here raise Exception('Pad size",
"skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF * samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval =",
"self.pad_size == 0: return array elif self.pad_size > 0: return np.pad(array, (0, self.pad_size),",
"self.pad_size = self.size - self.original_size if self.pad_size == 0: return array elif self.pad_size",
"return array elif self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant') assert False",
"+ right for left, right in grouper(halfs, 2)] # Cut pad size from",
"import logging import numpy as np log = logging.getLogger(__name__) PI2 = 2 *",
"self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self):",
"__init__(self, size): self.size = size def __call__(self, array): self.original_size = len(array) self.pad_size =",
"overlapped_blocks = iconcatenate_pairs( chain([zero_pad], equal_sized_pieces, [zero_pad]) ) windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images",
"* samples_count / samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval",
"dtype=np.float32) angfreq[-nsamples/2 + 1:] -= nsamples angfreq *= samplerate * PI2 / nsamples",
"-= nsamples angfreq *= samplerate * PI2 / nsamples return angfreq # Чем",
"size // 2 for array in arrays: pair = split_array(array, halfsize) for j",
"2)] # Cut pad size from last last_image_size = padder.original_size // decimate overlapped_halfs[-1]",
"functools import partial from itertools import chain, tee import logging import numpy as",
"axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples, dtype=np.float32)",
"будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales",
"= 2 * np.pi def pairwise(iterable): one, two = tee(iterable) next(two, None) return",
"complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs =",
"scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes = 2 ** (indexes *",
"2 return mat[:, :half], mat[:, half:] def test_iconcatenate_pairs(): pairs = [[1, 2, 3],",
"progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2",
"**kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks",
"self.nsamples = nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies",
"class NumpyPadder(object): def __init__(self, size): self.size = size def __call__(self, array): self.original_size =",
"11 * (self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks",
"[ [1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8, 9],",
"(self.omega0 / 70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples)",
"None) return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)] * n)) def test_split_vertical():",
"\"\"\" Compute scales as fractional power of two \"\"\" # morle_samples - количество",
"indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes = np.arange(indexes_count + 1, dtype=np.float32) logarithmic_indexes =",
"= size def __call__(self, array): self.original_size = len(array) self.pad_size = self.size - self.original_size",
"[list(r) for r in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4, 5,",
"two = tee(iterable) next(two, None) return zip(one, two) def grouper(iterable, n): return zip(*([iter(iterable)]",
"/ PI2 # scale - измеряется в секундах minimal_scale = morle_samples / samplerate",
"= freq_interval / skipped_low_freq_interval maximal_scale = np.log2(visible_freq_interval) indexes_count = int(np.floor(maximal_scale / scale_resolution)) indexes",
"np.concatenate(overlapped_halfs, axis=1) def angularfreq(nsamples, samplerate): \"\"\" Compute angular frequencies \"\"\" angfreq = np.arange(nsamples,",
"/ samplerate skipped_low_freq_interval = max(1, 2**skip_n_lower_octaves) visible_freq_interval = freq_interval / skipped_low_freq_interval maximal_scale =",
"elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert list(mapped)",
"pair): yield j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d,",
"Compute scales as fractional power of two \"\"\" # morle_samples - количество отсчетов",
"< 0') class BaseWaveletBox(object): def __init__(self, nsamples, samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples):",
"2, 3], [4, 5, 6], [7, 8, 9]] assert [list(r) for r in",
"+ 1:] -= nsamples angfreq *= samplerate * PI2 / nsamples return angfreq",
"6], [4, 5, 6, 7, 8, 9], ] def iconcatenate_pairs(items): for pair in",
"sound.get_blocks(self.nsamples) # blocks = sound.get_blocks(self.nsamples//2) with progressbar(blocks) as blocks_: return self._apply_cwt(blocks_, progressbar, **kwargs)",
"never come here raise Exception('Pad size < 0') class BaseWaveletBox(object): def __init__(self, nsamples,",
"raise Exception(u'nsamples must be power of two') self.nsamples = nsamples self.omega0 = omega0",
"for pair in pairwise(items): yield np.concatenate(pair) def is_power_of_two(val): return val and val &",
"больше октав снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0):",
"0: return np.pad(array, (0, self.pad_size), 'constant') assert False # Should never come here",
"yield j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ] assert list(gen_halfs(d, 4))",
"] assert list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5, 6], [7]] def",
"return np.pad(array, (0, self.pad_size), 'constant') assert False # Should never come here raise",
"* np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ]",
"self.size - self.original_size if self.pad_size == 0: return array elif self.pad_size > 0:",
"in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4, 5, 6], [4, 5,",
"items = iter(iterable) last = next(items) for elem in items: yield last last",
"halfsize) for j in filter(len, pair): yield j def test_gen_halfs(): d = [",
"вейвлетов поместится (диапазон частот) freq_interval = samples_count / morle_samples skip_n_lower_octaves = LOWER_FQ_LIMIT_COEFF *",
"return self._apply_cwt(blocks_, progressbar, **kwargs) def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples",
"halfsize = size // 2 for array in arrays: pair = split_array(array, halfsize)",
"autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): # Set",
"fractional power of two \"\"\" # morle_samples - количество отсчетов для базового вейвлета",
"self.pad_size), 'constant') assert False # Should never come here raise Exception('Pad size <",
"0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute scales as fractional power of",
"for r in iconcatenate_pairs(pairs)] == \\ [ [1, 2, 3, 4, 5, 6],",
"= nsamples self.omega0 = omega0 self.scales = autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies =",
"3] class NumpyPadder(object): def __init__(self, size): self.size = size def __call__(self, array): self.original_size",
"samplerate, scale_resolution, omega0): if not is_power_of_two(nsamples): raise Exception(u'nsamples must be power of two')",
"if self.pad_size == 0: return array elif self.pad_size > 0: return np.pad(array, (0,",
"list(gen_halfs(d, 4)) == [[1, 2], [3, 4], [5, 6], [7]] def split_array(array, where):",
"== \\ [ [1, 2, 3, 4, 5, 6], [4, 5, 6, 7,",
"halfs = chain.from_iterable(map(split_vertical, complex_images)) next(halfs) overlapped_halfs = [left + right for left, right",
"[1, 2, 3, 4, 5, 6], [4, 5, 6, 7, 8, 9], ]",
"== 0: return array elif self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant')",
"Exception(u'nsamples must be power of two') self.nsamples = nsamples self.omega0 = omega0 self.scales",
"must be power of two') self.nsamples = nsamples self.omega0 = omega0 self.scales =",
"elif self.pad_size > 0: return np.pad(array, (0, self.pad_size), 'constant') assert False # Should",
"= autoscales(nsamples, samplerate, scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): #",
"= [left + right for left, right in grouper(halfs, 2)] # Cut pad",
"size from last last_image_size = padder.original_size // decimate overlapped_halfs[-1] = overlapped_halfs[-1][:, :last_image_size] return",
"x+1, range(3)) assert list(mapped) == [0, 1, 3] class NumpyPadder(object): def __init__(self, size):",
"scale_resolution, omega0) self.angular_frequencies = angularfreq(nsamples, samplerate) @property def frequencies(self): # Set coefficient in",
") windowed_pieces = overlapped_blocks * np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for",
"/ 70) / self.scales def sound_apply_cwt(self, sound, progressbar, **kwargs): blocks = sound.get_blocks(self.nsamples) #",
"is_power_of_two(val): return val and val & (val - 1) == 0 def gen_halfs(arrays,",
"= elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x: x+1, range(3)) assert",
"_apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks = gen_halfs(blocks,",
"= len(array) self.pad_size = self.size - self.original_size if self.pad_size == 0: return array",
"np.hanning(self.nsamples) complex_images = [ self.cwt(windowed_piece, decimate, **kwargs) for windowed_piece in windowed_pieces ] halfs",
"morle_samples = (omega0 + np.sqrt(2 + omega0 ** 2)) / PI2 # scale",
"size): halfsize = size // 2 for array in arrays: pair = split_array(array,",
"in filter(len, pair): yield j def test_gen_halfs(): d = [ [1,2,3,4], [5,6,7], ]",
"with wavelet type return 11 * (self.omega0 / 70) / self.scales def sound_apply_cwt(self,",
"PI2 / nsamples return angfreq # Чем больше, тем больше октав снизу будет",
"def _apply_cwt(self, blocks, progressbar, decimate, **kwargs): half_nsamples = self.nsamples // 2 chunks =",
"mat = np.asarray(mat) half = mat.shape[1] / 2 return mat[:, :half], mat[:, half:]",
"# morle_samples - количество отсчетов для базового вейвлета morle_samples = (omega0 + np.sqrt(2",
"def is_power_of_two(val): return val and val & (val - 1) == 0 def",
"for elem in items: yield last last = elem yield fn(last) def test_map_only_last():",
"[3, 4]]) assert i.tolist() == [[1], [3]] assert j.tolist() == [[2], [4]] def",
"scale_resolution, omega0): \"\"\" Compute scales as fractional power of two \"\"\" # morle_samples",
"assert list(mapped) == [0, 1, 3] class NumpyPadder(object): def __init__(self, size): self.size =",
"= iter(iterable) last = next(items) for elem in items: yield last last =",
"снизу будет отброшено LOWER_FQ_LIMIT_COEFF = 0.5 def autoscales(samples_count, samplerate, scale_resolution, omega0): \"\"\" Compute",
"right in grouper(halfs, 2)] # Cut pad size from last last_image_size = padder.original_size",
"4)) == [[1, 2], [3, 4], [5, 6], [7]] def split_array(array, where): return",
"yield last last = elem yield fn(last) def test_map_only_last(): mapped = map_only_last(lambda x:",
"x: x+1, range(3)) assert list(mapped) == [0, 1, 3] class NumpyPadder(object): def __init__(self,"
] |
[
"f_args = sig.parameters.keys() feed_args = False feed_kwargs = False arglist = [] for",
"Exception(f'the keyword \\'{arg}\\' is already specified in the workflow') else: break f_kwargs =",
"res.keys(): feed_kwargs = True arglist.append(arg) elif arg not in kwargs.keys() and arg not",
"these are free params... workflow_pars = [] for i, f in enumerate(workflow): sig",
"res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified in the workflow') else: break",
"typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args,",
"the workflow') else: break f_kwargs = {k:kwargs[k] for k in arglist} if feed_args",
"kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified in",
"and not feed_kwargs: res = f(*args, **res) elif not feed_args and feed_kwargs: res",
"f_kwargs = {k:kwargs[k] for k in arglist} if feed_args and feed_kwargs: res =",
"feed_kwargs = True arglist.append(arg) elif arg not in kwargs.keys() and arg not in",
"is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__",
"def pipeline(*args, **kwargs): # *args are for grad, **kwargs are the rest res",
"specified in the workflow') else: break f_kwargs = {k:kwargs[k] for k in arglist}",
"and arg not in res.keys(): feed_kwargs = True arglist.append(arg) elif arg not in",
"which of these are free params... workflow_pars = [] for i, f in",
"else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars,",
"arg in kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already",
"in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified in the workflow') else:",
"arg not in res.keys(): feed_kwargs = True arglist.append(arg) elif arg not in kwargs.keys()",
"and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified in the",
"f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs: res = f(*args, **res) elif",
"enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0",
"**f_kwargs) elif feed_args and not feed_kwargs: res = f(*args, **res) elif not feed_args",
"= [] for arg in f_args: if not feed_args or not feed_kwargs: if",
"Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): # *args are for grad,",
"= inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit(",
"in res.keys(): feed_kwargs = True arglist.append(arg) elif arg not in kwargs.keys() and arg",
"f(**res, **f_kwargs) else: res = f(**res) return res # not really too helpful,",
"x: 0 if x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1])",
"elif feed_args and not feed_kwargs: res = f(*args, **res) elif not feed_args and",
"not feed_kwargs: res = f(*args, **res) elif not feed_args and feed_kwargs: res =",
"= f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs: res = f(*args, **res)",
"workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty else 1) #",
"True arglist.append(arg) elif arg not in kwargs.keys() and arg not in res.keys(): feed_args",
"\\'{arg}\\' is already specified in the workflow') else: break f_kwargs = {k:kwargs[k] for",
"pipeline(*args, **kwargs): # *args are for grad, **kwargs are the rest res =",
"not in res.keys(): feed_args = True elif arg in kwargs.keys() and arg in",
"Callable: def pipeline(*args, **kwargs): # *args are for grad, **kwargs are the rest",
"not really too helpful, since can't parse which of these are free params...",
"**kwargs are the rest res = dict([]) for f in workflow: sig =",
"are free params... workflow_pars = [] for i, f in enumerate(workflow): sig =",
"Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): #",
"= False feed_kwargs = False arglist = [] for arg in f_args: if",
"elif arg in kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is",
"for k in arglist} if feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs)",
"inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline,",
"parse which of these are free params... workflow_pars = [] for i, f",
"else: res = f(**res) return res # not really too helpful, since can't",
"arglist.append(arg) elif arg not in kwargs.keys() and arg not in res.keys(): feed_args =",
"Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): # *args",
"= last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array, filter_spec_return=equinox.is_array",
"res = dict([]) for f in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys()",
"return res # not really too helpful, since can't parse which of these",
"feed_args and feed_kwargs: res = f(**res, **f_kwargs) else: res = f(**res) return res",
"arg not in kwargs.keys() and arg not in res.keys(): feed_args = True elif",
"arglist} if feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args and",
"inspect import equinox from typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False)",
"kwargs.keys() and arg not in res.keys(): feed_args = True elif arg in kwargs.keys()",
"= f(**res, **f_kwargs) else: res = f(**res) return res # not really too",
"not feed_args and feed_kwargs: res = f(**res, **f_kwargs) else: res = f(**res) return",
"and feed_kwargs: res = f(**res, **f_kwargs) else: res = f(**res) return res #",
"= sig.parameters.keys() feed_args = False feed_kwargs = False arglist = [] for arg",
"do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): # *args are for grad, **kwargs",
"not feed_args or not feed_kwargs: if arg in kwargs.keys() and arg not in",
"True elif arg in kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\'",
"feed_kwargs = False arglist = [] for arg in f_args: if not feed_args",
"workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs = False",
"= dict([]) for f in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args",
"= inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs = False arglist =",
"break f_kwargs = {k:kwargs[k] for k in arglist} if feed_args and feed_kwargs: res",
"res = f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs: res = f(*args,",
"key=lambda x: 0 if x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig =",
"in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x:",
"for f in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args = False",
"kwargs.keys() and arg not in res.keys(): feed_kwargs = True arglist.append(arg) elif arg not",
"sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs = False arglist",
"# *args are for grad, **kwargs are the rest res = dict([]) for",
"in the workflow') else: break f_kwargs = {k:kwargs[k] for k in arglist} if",
"res.keys(): feed_args = True elif arg in kwargs.keys() and arg in res.keys(): raise",
"really too helpful, since can't parse which of these are free params... workflow_pars",
"arg in kwargs.keys() and arg not in res.keys(): feed_kwargs = True arglist.append(arg) elif",
"# not really too helpful, since can't parse which of these are free",
"grad, **kwargs are the rest res = dict([]) for f in workflow: sig",
"feed_kwargs: if arg in kwargs.keys() and arg not in res.keys(): feed_kwargs = True",
"feed_kwargs: res = f(*args, **res) elif not feed_args and feed_kwargs: res = f(**res,",
"last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return",
"or not feed_kwargs: if arg in kwargs.keys() and arg not in res.keys(): feed_kwargs",
"are the rest res = dict([]) for f in workflow: sig = inspect.signature(f)",
"= inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default",
"f in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs",
"is already specified in the workflow') else: break f_kwargs = {k:kwargs[k] for k",
"if x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an =",
"f(*args, **res) elif not feed_args and feed_kwargs: res = f(**res, **f_kwargs) else: res",
"for grad, **kwargs are the rest res = dict([]) for f in workflow:",
"from typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def",
"def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): # *args are",
"= True arglist.append(arg) elif arg not in kwargs.keys() and arg not in res.keys():",
"in kwargs.keys() and arg not in res.keys(): feed_args = True elif arg in",
"sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig",
"print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit:",
"for arg in f_args: if not feed_args or not feed_kwargs: if arg in",
"arg in f_args: if not feed_args or not feed_kwargs: if arg in kwargs.keys()",
"feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs:",
"in arglist} if feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args",
"too helpful, since can't parse which of these are free params... workflow_pars =",
"res = f(*args, **res) elif not feed_args and feed_kwargs: res = f(**res, **f_kwargs)",
"= inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array, filter_spec_return=equinox.is_array ) else: return",
"not in kwargs.keys() and arg not in res.keys(): feed_args = True elif arg",
"if feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args and not",
"import functools import inspect import equinox from typing import Callable, Iterable def compose(workflow:",
"and arg not in res.keys(): feed_args = True elif arg in kwargs.keys() and",
"keyword \\'{arg}\\' is already specified in the workflow') else: break f_kwargs = {k:kwargs[k]",
"else: break f_kwargs = {k:kwargs[k] for k in arglist} if feed_args and feed_kwargs:",
"= {k:kwargs[k] for k in arglist} if feed_args and feed_kwargs: res = f(*args,",
"feed_args and not feed_kwargs: res = f(*args, **res) elif not feed_args and feed_kwargs:",
"= sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty else 1) # print(workflow_pars)",
"free params... workflow_pars = [] for i, f in enumerate(workflow): sig = inspect.signature(f)",
"import inspect import equinox from typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit:",
"raise Exception(f'the keyword \\'{arg}\\' is already specified in the workflow') else: break f_kwargs",
"# print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if",
"in f_args: if not feed_args or not feed_kwargs: if arg in kwargs.keys() and",
"inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ =",
"elif arg not in kwargs.keys() and arg not in res.keys(): feed_args = True",
"inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs = False arglist = []",
"feed_args = False feed_kwargs = False arglist = [] for arg in f_args:",
"import equinox from typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) ->",
"if arg in kwargs.keys() and arg not in res.keys(): feed_kwargs = True arglist.append(arg)",
"k in arglist} if feed_args and feed_kwargs: res = f(*args, **res, **f_kwargs) elif",
"not in res.keys(): feed_kwargs = True arglist.append(arg) elif arg not in kwargs.keys() and",
"import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs):",
"arg not in res.keys(): feed_args = True elif arg in kwargs.keys() and arg",
"in kwargs.keys() and arg not in res.keys(): feed_kwargs = True arglist.append(arg) elif arg",
"in res.keys(): feed_args = True elif arg in kwargs.keys() and arg in res.keys():",
"**kwargs): # *args are for grad, **kwargs are the rest res = dict([])",
"already specified in the workflow') else: break f_kwargs = {k:kwargs[k] for k in",
"+= list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty else",
"0 if x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an",
"an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array,",
"sig.parameters.keys() feed_args = False feed_kwargs = False arglist = [] for arg in",
"= [] for i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values())",
"**res, **f_kwargs) elif feed_args and not feed_kwargs: res = f(*args, **res) elif not",
"not feed_kwargs: if arg in kwargs.keys() and arg not in res.keys(): feed_kwargs =",
"and feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs: res",
"{k:kwargs[k] for k in arglist} if feed_args and feed_kwargs: res = f(*args, **res,",
"feed_kwargs: res = f(*args, **res, **f_kwargs) elif feed_args and not feed_kwargs: res =",
"**f_kwargs) else: res = f(**res) return res # not really too helpful, since",
"sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if",
"-> Callable: def pipeline(*args, **kwargs): # *args are for grad, **kwargs are the",
"list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty else 1)",
"1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an)",
"helpful, since can't parse which of these are free params... workflow_pars = []",
"workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default is inspect.Parameter.empty",
"arglist = [] for arg in f_args: if not feed_args or not feed_kwargs:",
"of these are free params... workflow_pars = [] for i, f in enumerate(workflow):",
"= f(*args, **res) elif not feed_args and feed_kwargs: res = f(**res, **f_kwargs) else:",
"since can't parse which of these are free params... workflow_pars = [] for",
"in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args = False feed_kwargs =",
"f(**res) return res # not really too helpful, since can't parse which of",
"False feed_kwargs = False arglist = [] for arg in f_args: if not",
"= f(**res) return res # not really too helpful, since can't parse which",
"feed_args or not feed_kwargs: if arg in kwargs.keys() and arg not in res.keys():",
"workflow_pars = [] for i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars +=",
"can't parse which of these are free params... workflow_pars = [] for i,",
"res = f(**res, **f_kwargs) else: res = f(**res) return res # not really",
"rest res = dict([]) for f in workflow: sig = inspect.signature(f) f_args =",
"the rest res = dict([]) for f in workflow: sig = inspect.signature(f) f_args",
"**res) elif not feed_args and feed_kwargs: res = f(**res, **f_kwargs) else: res =",
"inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array, filter_spec_return=equinox.is_array ) else: return pipeline",
"f_args: if not feed_args or not feed_kwargs: if arg in kwargs.keys() and arg",
"bool=False) -> Callable: def pipeline(*args, **kwargs): # *args are for grad, **kwargs are",
"[] for arg in f_args: if not feed_args or not feed_kwargs: if arg",
"x.default is inspect.Parameter.empty else 1) # print(workflow_pars) last_sig = inspect.signature(workflow[-1]) an = last_sig.return_annotation",
"inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda x: 0 if x.default is",
"params... workflow_pars = [] for i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars",
"if not feed_args or not feed_kwargs: if arg in kwargs.keys() and arg not",
"[] for i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars",
"workflow') else: break f_kwargs = {k:kwargs[k] for k in arglist} if feed_args and",
"feed_kwargs: res = f(**res, **f_kwargs) else: res = f(**res) return res # not",
"for i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars =",
"f in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars, key=lambda",
"= True elif arg in kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword",
"= False arglist = [] for arg in f_args: if not feed_args or",
"dict([]) for f in workflow: sig = inspect.signature(f) f_args = sig.parameters.keys() feed_args =",
"elif not feed_args and feed_kwargs: res = f(**res, **f_kwargs) else: res = f(**res)",
"pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array, filter_spec_return=equinox.is_array ) else:",
"res # not really too helpful, since can't parse which of these are",
"False arglist = [] for arg in f_args: if not feed_args or not",
"arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified in the workflow')",
"functools import inspect import equinox from typing import Callable, Iterable def compose(workflow: Iterable[Callable],",
"in kwargs.keys() and arg in res.keys(): raise Exception(f'the keyword \\'{arg}\\' is already specified",
"last_sig.return_annotation pipeline.__signature__ = inspect.Signature(workflow_pars, return_annotation=an) if do_jit: return equinox.filter_jit( pipeline, filter_spec=equinox.is_array, filter_spec_return=equinox.is_array )",
"equinox from typing import Callable, Iterable def compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable:",
"feed_args = True elif arg in kwargs.keys() and arg in res.keys(): raise Exception(f'the",
"i, f in enumerate(workflow): sig = inspect.signature(f) workflow_pars += list(sig.parameters.values()) workflow_pars = sorted(workflow_pars,",
"are for grad, **kwargs are the rest res = dict([]) for f in",
"compose(workflow: Iterable[Callable], do_jit: bool=False) -> Callable: def pipeline(*args, **kwargs): # *args are for",
"res = f(**res) return res # not really too helpful, since can't parse",
"*args are for grad, **kwargs are the rest res = dict([]) for f"
] |
[
"= os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records = [] if",
"we written to the output file records = [] for record in SeqIO.parse(input_file,",
"\"fasta\") count += 1 records = [] if records: # this only applies",
"import sys from Bio import SeqIO num_chunks = 0 if len(sys.argv) == 3:",
"elif len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\")",
"open(input_filename) as input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk",
"len(records) >= records_per_chunk ): if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else:",
"input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count)",
"written to the output file records = [] for record in SeqIO.parse(input_file, \"fasta\"):",
"need to count how many records are in the # input file record_count",
"0 with open(input_filename) as input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count +=",
"where input file is # split into chunks output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records,",
"records are in the # input file record_count = 0 with open(input_filename) as",
"have we written to the output file records = [] for record in",
"the output file records = [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if",
"file is # split into chunks output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\")",
"num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1]",
"record_count += 1 records_per_chunk = round(float(record_count) / num_chunks) count = 1 with open(input_filename)",
"#!/usr/bin/env python import os import sys from Bio import SeqIO num_chunks = 0",
"lines have we written to the output file records = [] for record",
"== 0 or ( count < num_chunks and len(records) >= records_per_chunk ): if",
"= int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1] else:",
"sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\")",
"record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records",
"records_per_chunk ): if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename =",
"count = 1 with open(input_filename) as input_file: chunk_record_count = 0 # how many",
"if num_chunks != 0: # if splitting into chunks we need to count",
"for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or ( count",
"os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records = [] if records:",
"0: output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\")",
"input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0:",
"mode where input file is # split into chunks output_filename = os.path.join(\"splits\", \"part{}\".format(count))",
"count how many records are in the # input file record_count = 0",
"file records = [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks ==",
"records.append(record) if num_chunks == 0 or ( count < num_chunks and len(records) >=",
"to the output file records = [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record)",
"= 1 with open(input_filename) as input_file: chunk_record_count = 0 # how many lines",
"== 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename,",
"for line in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) /",
"chunks we need to count how many records are in the # input",
"2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks !=",
"1 records_per_chunk = round(float(record_count) / num_chunks) count = 1 with open(input_filename) as input_file:",
"< num_chunks and len(records) >= records_per_chunk ): if num_chunks == 0: output_filename =",
"num_chunks and len(records) >= records_per_chunk ): if num_chunks == 0: output_filename = os.path.join(\"splits\",",
"open(input_filename) as input_file: chunk_record_count = 0 # how many lines have we written",
"count += 1 records = [] if records: # this only applies for",
"+= 1 records = [] if records: # this only applies for the",
"applies for the mode where input file is # split into chunks output_filename",
"the mode where input file is # split into chunks output_filename = os.path.join(\"splits\",",
"line in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) / num_chunks)",
"len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if",
"if splitting into chunks we need to count how many records are in",
"this only applies for the mode where input file is # split into",
"only applies for the mode where input file is # split into chunks",
"len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2:",
"in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or ( count < num_chunks",
"1 with open(input_filename) as input_file: chunk_record_count = 0 # how many lines have",
"split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if splitting into chunks",
"round(float(record_count) / num_chunks) count = 1 with open(input_filename) as input_file: chunk_record_count = 0",
"or ( count < num_chunks and len(records) >= records_per_chunk ): if num_chunks ==",
"if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) ==",
"Bio import SeqIO num_chunks = 0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2])",
"num_chunks = 0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1]",
"output file records = [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks",
"os.mkdir(\"splits\") if num_chunks != 0: # if splitting into chunks we need to",
"0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv)",
"else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if splitting",
"# input file record_count = 0 with open(input_filename) as input_file: for line in",
"== 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks",
"<gh_stars>0 #!/usr/bin/env python import os import sys from Bio import SeqIO num_chunks =",
"( count < num_chunks and len(records) >= records_per_chunk ): if num_chunks == 0:",
"[] if records: # this only applies for the mode where input file",
"we need to count how many records are in the # input file",
"records: # this only applies for the mode where input file is #",
"SeqIO num_chunks = 0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename =",
"int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage:",
"\"fasta\"): records.append(record) if num_chunks == 0 or ( count < num_chunks and len(records)",
"= [] if records: # this only applies for the mode where input",
"SeqIO.write(records, output_filename, \"fasta\") count += 1 records = [] if records: # this",
"from Bio import SeqIO num_chunks = 0 if len(sys.argv) == 3: num_chunks =",
"input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) / num_chunks) count =",
"with open(input_filename) as input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count += 1",
">= records_per_chunk ): if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename",
"sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if",
"0: # if splitting into chunks we need to count how many records",
"how many records are in the # input file record_count = 0 with",
"!= 0: # if splitting into chunks we need to count how many",
"0 # how many lines have we written to the output file records",
"and len(records) >= records_per_chunk ): if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id)",
"into chunks we need to count how many records are in the #",
"<input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if splitting into chunks we",
"SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or ( count < num_chunks and",
"with open(input_filename) as input_file: chunk_record_count = 0 # how many lines have we",
"how many lines have we written to the output file records = []",
"= [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or",
"line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) / num_chunks) count = 1 with",
"os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1",
"are in the # input file record_count = 0 with open(input_filename) as input_file:",
"num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records,",
"\"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records = [] if records: #",
"if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count))",
"python import os import sys from Bio import SeqIO num_chunks = 0 if",
"the # input file record_count = 0 with open(input_filename) as input_file: for line",
"in the # input file record_count = 0 with open(input_filename) as input_file: for",
"records_per_chunk = round(float(record_count) / num_chunks) count = 1 with open(input_filename) as input_file: chunk_record_count",
"output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count",
"[] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or (",
"if num_chunks == 0 or ( count < num_chunks and len(records) >= records_per_chunk",
"= sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename>",
"= 0 # how many lines have we written to the output file",
"many lines have we written to the output file records = [] for",
"if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) / num_chunks) count = 1",
"= 0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif",
"# if splitting into chunks we need to count how many records are",
"as input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk =",
"input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename = sys.argv[1] else: exit(\"Usage: split_fasta.py",
"num_chunks) count = 1 with open(input_filename) as input_file: chunk_record_count = 0 # how",
"0 or ( count < num_chunks and len(records) >= records_per_chunk ): if num_chunks",
"1 records = [] if records: # this only applies for the mode",
"many records are in the # input file record_count = 0 with open(input_filename)",
"= round(float(record_count) / num_chunks) count = 1 with open(input_filename) as input_file: chunk_record_count =",
"sys from Bio import SeqIO num_chunks = 0 if len(sys.argv) == 3: num_chunks",
"3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename =",
"num_chunks != 0: # if splitting into chunks we need to count how",
"in input_file: if line.lstrip().startswith(\">\"): record_count += 1 records_per_chunk = round(float(record_count) / num_chunks) count",
"as input_file: chunk_record_count = 0 # how many lines have we written to",
"/ num_chunks) count = 1 with open(input_filename) as input_file: chunk_record_count = 0 #",
"chunk_record_count = 0 # how many lines have we written to the output",
"to count how many records are in the # input file record_count =",
"input_file: chunk_record_count = 0 # how many lines have we written to the",
"= os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count +=",
"records = [] for record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0",
"os import sys from Bio import SeqIO num_chunks = 0 if len(sys.argv) ==",
"import SeqIO num_chunks = 0 if len(sys.argv) == 3: num_chunks = int(sys.argv[2]) input_filename",
"input file record_count = 0 with open(input_filename) as input_file: for line in input_file:",
"record in SeqIO.parse(input_file, \"fasta\"): records.append(record) if num_chunks == 0 or ( count <",
"else: output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records =",
"input file is # split into chunks output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename,",
"num_chunks == 0 or ( count < num_chunks and len(records) >= records_per_chunk ):",
"splitting into chunks we need to count how many records are in the",
"import os import sys from Bio import SeqIO num_chunks = 0 if len(sys.argv)",
"# this only applies for the mode where input file is # split",
"): if num_chunks == 0: output_filename = os.path.join(\"splits\", record.id) else: output_filename = os.path.join(\"splits\",",
"if records: # this only applies for the mode where input file is",
"[<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if splitting into chunks we need",
"== 3: num_chunks = int(sys.argv[2]) input_filename = sys.argv[1] elif len(sys.argv) == 2: input_filename",
"output_filename = os.path.join(\"splits\", \"part{}\".format(count)) SeqIO.write(records, output_filename, \"fasta\") count += 1 records = []",
"for the mode where input file is # split into chunks output_filename =",
"# how many lines have we written to the output file records =",
"exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: # if splitting into",
"output_filename, \"fasta\") count += 1 records = [] if records: # this only",
"= sys.argv[1] else: exit(\"Usage: split_fasta.py <input_filename> [<num_chunks>]\") os.mkdir(\"splits\") if num_chunks != 0: #",
"count < num_chunks and len(records) >= records_per_chunk ): if num_chunks == 0: output_filename",
"= 0 with open(input_filename) as input_file: for line in input_file: if line.lstrip().startswith(\">\"): record_count",
"file record_count = 0 with open(input_filename) as input_file: for line in input_file: if",
"+= 1 records_per_chunk = round(float(record_count) / num_chunks) count = 1 with open(input_filename) as",
"records = [] if records: # this only applies for the mode where",
"record_count = 0 with open(input_filename) as input_file: for line in input_file: if line.lstrip().startswith(\">\"):"
] |
[
"self.red_pin = red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR",
"return (x - in_min) * (out_max - out_min) // (in_max - in_min) +",
"= currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\",",
"elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB = b",
"Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR)",
"convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b)",
"rStep = 1 else: rStep -= 1 if g>self.currentValueG: gStep = 1 else:",
"green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x)",
"i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i",
"#rgb led lib from machine import PWM, Pin import utime def convert(x, in_min,",
"= PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x",
"== 'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x)",
"currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin",
"self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green",
"self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay =",
"def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG = 0, currentValueB=0):",
"for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for",
"'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay)",
"= convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x =",
"* (out_max - out_min) // (in_max - in_min) + out_min class RGBLed: anode",
"Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r",
"from machine import PWM, Pin import utime def convert(x, in_min, in_max, out_min, out_max):",
"Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR =",
"= convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm =",
"g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm",
"__init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin",
"else: bStep = -1 if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x",
"print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue",
"for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for",
"self.currentValueB = b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm",
"= PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self):",
"red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm",
"PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0)",
"def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def",
"= convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm =",
"= PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm =",
"if r>self.currentValueR: rStep = 1 else: rStep -= 1 if g>self.currentValueG: gStep =",
"green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def",
"in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r",
"PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG =",
"self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR:",
"for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for",
"bStep = 1 else: bStep = -1 if self.ledType == 'anode': for i",
"x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG =",
"1 if g>self.currentValueG: gStep = 1 else: gStep = -1 if b>self.currentValueB: bStep",
"-1 if b>self.currentValueB: bStep = 1 else: bStep = -1 if self.ledType ==",
"= 0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin",
"blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r",
"= PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG",
"- in_min) + out_min class RGBLed: anode = 'anode' cathode = 'cathode' def",
"currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin)",
"in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in",
"g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm",
"- out_min) // (in_max - in_min) + out_min class RGBLed: anode = 'anode'",
"red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def",
"convert(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min)",
"1 else: rStep -= 1 if g>self.currentValueG: gStep = 1 else: gStep =",
"g self.currentValueB = b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534)",
"in_min) * (out_max - out_min) // (in_max - in_min) + out_min class RGBLed:",
"b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin))",
"RGBLed: anode = 'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType,",
"green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm",
"r>self.currentValueR: rStep = 1 else: rStep -= 1 if g>self.currentValueG: gStep = 1",
"machine import PWM, Pin import utime def convert(x, in_min, in_max, out_min, out_max): return",
"currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType = ledType",
"red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin =",
"class RGBLed: anode = 'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin,",
"(in_max - in_min) + out_min class RGBLed: anode = 'anode' cathode = 'cathode'",
"def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1 else:",
"convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG = g self.currentValueB",
"green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x)",
"green_pin, blue_pin, ledType, currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin",
"import utime def convert(x, in_min, in_max, out_min, out_max): return (x - in_min) *",
"= b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm =",
"Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r self.currentValueG =",
"in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in",
"self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue",
"PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR =",
"b>self.currentValueB: bStep = 1 else: bStep = -1 if self.ledType == 'anode': for",
"if g>self.currentValueG: gStep = 1 else: gStep = -1 if b>self.currentValueB: bStep =",
"ledType, currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin =",
"= convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm =",
"slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1 else: rStep -= 1 if",
"PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0)",
"green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self):",
"def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01):",
"= ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def",
"== 'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r =",
"i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i",
"in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType ==",
"range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep):",
"blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB =",
"import PWM, Pin import utime def convert(x, in_min, in_max, out_min, out_max): return (x",
"self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red",
"def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType)",
"Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode':",
"def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r self.currentValueG = g self.currentValueB",
"def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def",
"self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def",
"if b>self.currentValueB: bStep = 1 else: bStep = -1 if self.ledType == 'anode':",
"= 'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR =",
"+ out_min class RGBLed: anode = 'anode' cathode = 'cathode' def __init__(self, red_pin,",
"0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType =",
"print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red",
"self.ledType == 'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r",
"in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in",
"range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG",
"// (in_max - in_min) + out_min class RGBLed: anode = 'anode' cathode =",
"blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def",
"'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,0,65534)",
"i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i",
"PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin))",
"ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self):",
"PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin))",
"Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType ==",
"PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x =",
"red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x)",
"utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay)",
"= convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG = g",
"red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif",
"convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0)",
"== 'anode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r =",
"blue_pin, ledType, currentValueR = 0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin",
"r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534)",
"def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1 else: rStep -= 1",
"blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB",
"out_min, out_max): return (x - in_min) * (out_max - out_min) // (in_max -",
"convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin))",
"PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255)",
"cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1 else: rStep",
"= 1 else: bStep = -1 if self.ledType == 'anode': for i in",
"self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin))",
"setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r self.currentValueG = g self.currentValueB =",
"x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x",
"out_min) // (in_max - in_min) + out_min class RGBLed: anode = 'anode' cathode",
"convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0)",
"show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current",
"out_max): return (x - in_min) * (out_max - out_min) // (in_max - in_min)",
"self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1",
"gStep = 1 else: gStep = -1 if b>self.currentValueB: bStep = 1 else:",
"1 else: gStep = -1 if b>self.currentValueB: bStep = 1 else: bStep =",
"g>self.currentValueG: gStep = 1 else: gStep = -1 if b>self.currentValueB: bStep = 1",
"else: gStep = -1 if b>self.currentValueB: bStep = 1 else: bStep = -1",
"= convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i",
"= 1 else: rStep -= 1 if g>self.currentValueG: gStep = 1 else: gStep",
"= PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm =",
"<filename>RGBLed_lib.py #rgb led lib from machine import PWM, Pin import utime def convert(x,",
"convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin))",
"'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay)",
"x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x",
"= r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,65534,0) g =",
"currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin)",
"= PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG = g self.currentValueB = b",
"print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b):",
"= r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,0,65534) g =",
"blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534)",
"convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534)",
"range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep):",
"self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin))",
"r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm",
"green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm",
"g self.currentValueB = b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0)",
"= PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm =",
"x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x",
"(out_max - out_min) // (in_max - in_min) + out_min class RGBLed: anode =",
"currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin)",
"self.currentValueB = b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm",
"= -1 if b>self.currentValueB: bStep = 1 else: bStep = -1 if self.ledType",
"in_min, in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) //",
"= 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG =",
"= PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType",
"gStep = -1 if b>self.currentValueB: bStep = 1 else: bStep = -1 if",
"red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm",
"i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR =",
"= green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG =",
"= 1 else: gStep = -1 if b>self.currentValueB: bStep = 1 else: bStep",
"Pin import utime def convert(x, in_min, in_max, out_min, out_max): return (x - in_min)",
"utime.sleep(delay) elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm",
"= convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g)",
"i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i",
"range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep):",
"r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm",
"def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep",
"convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin))",
"for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for",
"red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x)",
"= PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm =",
"in_max, out_min, out_max): return (x - in_min) * (out_max - out_min) // (in_max",
"if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm =",
"green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode':",
"self.currentValueR = r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,65534,0) g",
"out_min class RGBLed: anode = 'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin,",
"= 0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType",
"PWM, Pin import utime def convert(x, in_min, in_max, out_min, out_max): return (x -",
"led lib from machine import PWM, Pin import utime def convert(x, in_min, in_max,",
"1 else: bStep = -1 if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep):",
"convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i in",
"yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if",
"green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG = currentValueG",
"utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay)",
"self.ledType == 'anode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r",
"self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255)",
"self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current",
"= g self.currentValueB = b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b =",
"self.currentValueG = g self.currentValueB = b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b",
"blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255)",
"rStep -= 1 if g>self.currentValueG: gStep = 1 else: gStep = -1 if",
"in_min) + out_min class RGBLed: anode = 'anode' cathode = 'cathode' def __init__(self,",
"= convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm =",
"PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin))",
"= blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB =",
"self.ledType = ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB)",
"def convert(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max -",
"= convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x =",
"elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm =",
"= PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR",
"utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay)",
"in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in",
"b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r)",
"-1 if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0) red_pin_pwm",
"= convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x =",
"cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG",
"if self.ledType == 'anode': self.currentValueR = r self.currentValueG = g self.currentValueB = b",
"white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay",
"currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin = blue_pin",
"self.blue_pin = blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG = currentValueG self.currentValueB",
"print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR",
"r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0)",
"'anode': self.currentValueR = r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,65534,0)",
"self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep = 1 else: rStep -=",
"= currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\",",
"Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB)",
"else: rStep -= 1 if g>self.currentValueG: gStep = 1 else: gStep = -1",
"for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif",
"= convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g)",
"= PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self):",
"anode = 'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR",
"print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType",
"'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0, currentValueG = 0,",
"= g self.currentValueB = b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b =",
"lib from machine import PWM, Pin import utime def convert(x, in_min, in_max, out_min,",
"b = convert(b,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r)",
"off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def magenta(self): self.setColor(255,0,255) def cyan(self):",
"= currentValueG self.currentValueB = currentValueB self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\",",
"Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG) print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if",
"= b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm =",
"= PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self):",
"self.currentValueG = g self.currentValueB = b r = convert(r,0,255,0,65534) g = convert(g,0,255,0,65534) b",
"x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x",
"magenta(self): self.setColor(255,0,255) def cyan(self): self.setColor(0,255,255) def slowSet(self,r,g,b,delay = 0.01): if r>self.currentValueR: rStep =",
"PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType ==",
"== 'cathode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,0,65534) red_pin_pwm = PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x)",
"- in_min) * (out_max - out_min) // (in_max - in_min) + out_min class",
"range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep):",
"utime def convert(x, in_min, in_max, out_min, out_max): return (x - in_min) * (out_max",
"red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG = g",
"range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode':",
"PWM(Pin(self.red_pin)) red_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin))",
"Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green Value:\",self.currentValueG)",
"= -1 if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x = convert(i,0,255,65534,0)",
"self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current",
"convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin))",
"b r = convert(r,0,255,65534,0) g = convert(g,0,255,65534,0) b = convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin))",
"= 0.01): if r>self.currentValueR: rStep = 1 else: rStep -= 1 if g>self.currentValueG:",
"print(\"Current Blue Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r self.currentValueG",
"= red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR =",
"x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for",
"utime.sleep(delay) for i in range(self.currentValueG,g,gStep): x = convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay)",
"self.green_pin = green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR = currentValueR self.currentValueG",
"print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led Type:\",self.ledType) print(\"Current Red Value:\",self.currentValueR) print(\"Current Green",
"-= 1 if g>self.currentValueG: gStep = 1 else: gStep = -1 if b>self.currentValueB:",
"bStep = -1 if self.ledType == 'anode': for i in range(self.currentValueR,r,rStep): x =",
"convert(i,0,255,0,65534) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534)",
"i in range(self.currentValueB,b,bStep): x = convert(i,0,255,65534,0) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType",
"PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG = g self.currentValueB = b self.Set(r,g,b)",
"= convert(i,0,255,65534,0) green_pin_pwm = PWM(Pin(self.green_pin)) green_pin_pwm.duty_u16(x) utime.sleep(delay) for i in range(self.currentValueB,b,bStep): x =",
"blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR = r self.currentValueG = g self.currentValueB =",
"(x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min",
"Value:\",self.currentValueB) def setColor(self,r,g,b): if self.ledType == 'anode': self.currentValueR = r self.currentValueG = g",
"self.currentValueR = r self.currentValueG = g self.currentValueB = b r = convert(r,0,255,0,65534) g",
"0.01): if r>self.currentValueR: rStep = 1 else: rStep -= 1 if g>self.currentValueG: gStep",
"red_pin self.green_pin = green_pin self.blue_pin = blue_pin self.ledType = ledType self.currentValueR = currentValueR",
"red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) def off(self): self.setColor(0,0,0) def white(self): self.setColor(255,255,255) def yellow(self): self.setColor(255,255,0) def",
"blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) elif self.ledType == 'cathode': for i in range(self.currentValueR,r,rStep):",
"green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b) elif self.ledType == 'cathode': self.currentValueR = r self.currentValueG = g self.currentValueB",
"'anode' cathode = 'cathode' def __init__(self, red_pin, green_pin, blue_pin, ledType, currentValueR = 0,",
"0, currentValueG = 0, currentValueB=0): self.red_pin = red_pin self.green_pin = green_pin self.blue_pin =",
"self.Set(currentValueR,currentValueG,currentValueB) def show(self): print(\"Red Pin:\", self.red_pin) print(\"Green Pin:\", self.green_pin) print(\"Blue Pin:\", self.blue_pin) print(\"Led",
"for i in range(self.currentValueB,b,bStep): x = convert(i,0,255,0,65534) blue_pin_pwm = PWM(Pin(self.blue_pin)) blue_pin_pwm.duty_u16(x) utime.sleep(delay) self.currentValueR",
"convert(b,0,255,65534,0) red_pin_pwm = PWM(Pin(self.red_pin)) green_pin_pwm = PWM(Pin(self.green_pin)) blue_pin_pwm = PWM(Pin(self.blue_pin)) red_pin_pwm.duty_u16(r) green_pin_pwm.duty_u16(g) blue_pin_pwm.duty_u16(b)"
] |
[
"out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm =",
"hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig)",
"#1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes",
"* from layers import * from util import * from model import *",
"return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with",
"fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close()",
"= plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram",
"in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents",
"dim=-1) # Reconstruction #print(\"Shapes of quantized and original mels to the deocder: \",",
"None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant =",
"#print(\"Shape of linear outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits,",
"[] current_element = None for element in arr: if current_element is None: current_element",
"is None: current_element = element arr_new.append(element) elif element == current_element: continue else: current_element",
"use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network =",
"= self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B,",
"{} B = mels.size(0) # Add noise to raw audio mels_noisy = mels",
"* math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm /",
"= embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0,",
"requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes =",
"mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty,",
"= self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3))",
"(index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes",
"forward_noreconstruction(self, mels, embedding): outputs = {} B = mels.size(0) # Add noise to",
"index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes))",
"= torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and original mels to",
"- embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes",
"quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID",
"# Reconstruction #print(\"Shapes of quantized and original mels to the deocder: \", quantized.shape,",
"embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses",
"# https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0",
"target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3, keepdim=True)",
"max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes =",
"#emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1)",
"with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm =",
"mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty,",
"embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses)",
"def get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale *",
"self.plot_histogram: assert self.assistant is not None hists = hist_2classes.cpu().numpy() fig = plt.figure() #",
"min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses",
"K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2)",
"= quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb))",
"math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2,",
"= mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1)",
"[] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes,",
"4, 1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder",
"Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding):",
"max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes)",
"index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor",
"index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0,",
"3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter",
"128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels,",
"if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents,",
"self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(),",
"(1, 4, 1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1)",
"min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes",
"x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1 and embedding: \",",
"element == current_element: continue else: current_element = element arr_new.append(element) return arr_new class SILA(nn.Module):",
"entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses) #",
"output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach() + x out1 = (x.detach()",
"embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128]",
"#emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get the LID logits",
"mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of",
"model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric tensor",
"plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64)",
"entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and",
"x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of",
"index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes",
"r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim",
"https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig =",
"= torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index:",
"and original mels to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized,",
"output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1,",
"= (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1))",
"GPU RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses =",
"* index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes +",
"x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64]",
"> 0) / len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes",
"math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None if",
"self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb",
"forward_getlid(self, mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb =",
"x = target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes",
"dim=0) # index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes",
"dim=-1) # Get the LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized =",
"* prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = - (prob_3classes",
"x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric",
"latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy:",
"mels.size(0) # Add noise to raw audio mels_noisy = mels * (0.02 *",
"linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self,",
"self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs)",
"scale if scale is not None else 0.06 self.embedding_scale = target_scale self.normalize_scale =",
"x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1,",
"(x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0]",
"len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) /",
"80, linear_dim = 1025, use_arff = 0, assistant = None): super(SILA, self).__init__() if",
"def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim = 80, linear_dim = 1025,",
"Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self, arr):",
"= hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses",
"entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N",
"'.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses))",
"= (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2)",
"CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128,",
"n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [ (2, 4, 1), (2,",
"* torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels",
"None hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2)",
"embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes)",
"(prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist()",
"Remove repeated entries def deduplicate(self, arr): arr_new = [] current_element = None for",
"weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure()",
"print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries def",
"vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2))",
"+ self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = '",
"embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes",
"self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes,",
"/ 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes >",
"for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \",",
"(prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = -",
"#print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) //",
"embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2))",
"x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2],",
"x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses",
"mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty, entropy =",
"- (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) +",
"(x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes,",
"in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = '",
"embedding_dim=256, input_dim=80, r = 4, mel_dim = 80, linear_dim = 1025, use_arff =",
"= output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape",
"mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes,",
"emb], dim=-1) # Get the LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized",
"r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True)",
"= {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def",
"mels to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None)",
"2) self.use_arff = use_arff def forward(self, mels, embedding): outputs = {} B =",
"self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}')",
"#print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits",
"mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb))",
"print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm =",
"of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits =",
"use_arff def forward(self, mels, embedding): outputs = {} B = mels.size(0) # Add",
"= - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes",
"embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128]",
"numeric tensor n_channels == 1 usually Output: (B, T, n_channels, vec_len) numeric tensor",
"prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses *",
"self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor self.n_classes =",
"min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if",
"# index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1,",
"in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents",
"embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if",
"of quantized and original mels to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments",
"= mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy,",
"#print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:,",
"= nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels, embedding): outputs = {}",
"encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B,",
"target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale *",
"vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID logits",
"= mels.size(0) # Add noise to raw audio mels_noisy = mels * (0.02",
"Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses =",
"self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm =",
"max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram:",
"x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and",
"self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16,",
"index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0)",
"arr: if current_element is None: current_element = element arr_new.append(element) elif element == current_element:",
"= nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True)",
"assistant def forward(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale",
"mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes,",
"if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized,",
"entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes =",
"# Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized =",
"mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step:",
"vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset",
"# self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant",
"-1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1)",
"-1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \",",
"= self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] =",
"Get approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) #",
"prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item()",
"nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels, embedding): outputs = {} B",
"index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes,",
"max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not None",
"continue else: current_element = element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256,",
"index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) *",
"hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64,",
"= None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels,",
"128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim,",
"(n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant",
"entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and",
"4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc",
"numeric tensor #print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape) # Perform chunking",
"= (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1))",
"return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy",
"(prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = -",
"self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels,",
"keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0",
"embedding.shape) # Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes",
"mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet",
"self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses",
"Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes,",
"quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1])",
"encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1],",
"= embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) #",
"0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes *",
"mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels",
"x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape,",
"= SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r",
"return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding):",
"latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for",
"latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2)",
"original mels to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels,",
"= self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) # Return",
"= 80, linear_dim = 1025, use_arff = 0, assistant = None): super(SILA, self).__init__()",
"self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4,",
"elif element == current_element: continue else: current_element = element arr_new.append(element) return arr_new class",
"os, sys FALCON_DIR = os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers import",
"tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes =",
"index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = -",
"x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses",
"\", latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self, arr): arr_new = []",
"* torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1],",
"index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes",
"self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine",
"0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes +",
"#print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones if",
"plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists =",
"arr_new.append(element) elif element == current_element: continue else: current_element = element arr_new.append(element) return arr_new",
"torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of",
"self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes)",
"linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) # Return return mel_outputs,",
"fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) /",
"os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers import * from util import",
"plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3)",
"entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1],",
"entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized",
"\", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class",
"K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs",
"= - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes",
"quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim,",
"* 2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256,",
"min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes",
"0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale",
"is not None hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2)",
"embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] -",
"(index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1,",
"from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric",
"if current_element is None: current_element = element arr_new.append(element) elif element == current_element: continue",
"normalize: target_scale = scale if scale is not None else 0.06 self.embedding_scale =",
"index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes",
"-1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1)",
"- x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x -",
"of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of",
"tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes =",
"fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close()",
"nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) *",
"plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes =",
"prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item()",
"= output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes =",
"self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes",
"plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig =",
"return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim =",
"4, 1), (1, 4, 1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers,",
"keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale",
"vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1],",
"1), (2, 4, 1), (1, 4, 1), (2, 4, 1), ] self.downsampling_encoder =",
"4, 1), (2, 4, 1), (2, 4, 1), (1, 4, 1), (2, 4,",
"4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (1, 4,",
"n_channels == 1 usually Output: (B, T, n_channels, vec_len) numeric tensor \"\"\" def",
"# https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig",
"= embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) #",
"= mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \", r)",
"= target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses /",
"# Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes =",
"self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) /",
"index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale:",
"[] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes:",
"target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes",
"SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r =",
"vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B,",
"- x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes,",
"#quantized = torch.cat([quantized, emb], dim=-1) # Get the LID logits #print(\"Shape of quantized:",
"dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0)",
"fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes",
"None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3,",
"min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) /",
"* math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm /",
"assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant)",
"= (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k)",
"mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized,",
"* self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor self.n_classes",
"util import * from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T,",
"hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes =",
"lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses",
"emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and original mels to the deocder:",
"avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes = []",
"(N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0],",
"self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True))",
"= (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) +",
"linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B = mels.shape[0]",
"plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy()",
"and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes)",
"n_channels, vec_len) numeric tensor n_channels == 1 usually Output: (B, T, n_channels, vec_len)",
"of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:,",
"target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes",
"hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes =",
"= mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels:",
"mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1)",
"class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric tensor n_channels == 1",
"dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels)",
"mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) //",
"keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm *",
"embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] -",
"output and x: \", output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach() +",
"self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim *",
"self.assistant is not None hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists,",
"self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r",
"#logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1:",
"output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0],",
"(2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim)",
"dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape)",
"of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel",
"= - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses",
"if self.plot_histogram: assert self.assistant is not None hists = hist_2classes.cpu().numpy() fig = plt.figure()",
"= index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes >",
"lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits,",
"= n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant def forward(self, x0, chunk_size=512):",
"\", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True,",
"RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses = []",
"in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = '",
"len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) /",
"+ self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses",
"vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy",
"keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm *",
"batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels, embedding): outputs",
"= 4, mel_dim = 80, linear_dim = 1025, use_arff = 0, assistant =",
"> 0) / len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses",
"else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3",
"(index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes =",
"hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig)",
"alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs =",
"= torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled",
"plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig =",
"* from util import * from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input:",
"embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) *",
"= torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get the LID logits #print(\"Shape",
"= plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists",
"element in arr: if current_element is None: current_element = element arr_new.append(element) elif element",
"output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0],",
"n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True,",
"plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists,",
"hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes =",
"the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1])",
"* self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes",
"= [] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk",
"import os, sys FALCON_DIR = os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers",
"arr_new = [] current_element = None for element in arr: if current_element is",
"= - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes",
"(N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5,",
"embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1],",
"(2, 4, 1), (2, 4, 1), (1, 4, 1), (2, 4, 1), ]",
"= self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B,",
"embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of",
"= torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape",
"self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, vq_penalty.mean(), encoder_penalty.mean(),",
"self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1,",
"self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) # Return return",
"# Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized =",
"per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim,",
"-1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses],",
"Get the LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _,",
"4, mel_dim = 80, linear_dim = 1025, use_arff = 0, assistant = None):",
"else: current_element = element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80,",
"= hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses',",
"tensor n_channels == 1 usually Output: (B, T, n_channels, vec_len) numeric tensor \"\"\"",
"prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0)",
"#print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape",
"self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x =",
"audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy",
"16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels)",
"element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4,",
"self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else:",
"Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes = []",
"fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3)",
"requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses =",
"output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x: \",",
"prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = - (prob_4classes *",
"(prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = -",
"torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and original mels to the",
"self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128)",
"output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output",
"hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1))",
"target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2,",
"emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1)",
"(2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (1,",
"= self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes,",
"self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale =",
"in arr: if current_element is None: current_element = element arr_new.append(element) elif element ==",
"keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0,",
"vec_len) numeric tensor n_channels == 1 usually Output: (B, T, n_channels, vec_len) numeric",
"__init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale = scale",
"embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes",
"* self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels,",
"encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized,",
"current_element = None for element in arr: if current_element is None: current_element =",
"1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1),",
"LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) =",
"the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of",
"entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm",
"plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure()",
"quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [ (2, 4, 1),",
"1 usually Output: (B, T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels,",
"mels, embedding): outputs = {} B = mels.size(0) # Add noise to raw",
"emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if",
"= hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes",
"and embedding: \", x1.shape, embedding.shape) # Perform chunking to avoid overflowing GPU RAM.",
"self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty,",
"vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [ (2, 4, 1), (2, 4,",
"x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2))",
"get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3))",
"0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb =",
"def forward_noreconstruction(self, mels, embedding): outputs = {} B = mels.size(0) # Add noise",
"(B, T, n_channels, vec_len) numeric tensor n_channels == 1 usually Output: (B, T,",
"hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1))",
"index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2,",
"mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty,",
"self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes =",
"def deduplicate(self, arr): arr_new = [] current_element = None for element in arr:",
"1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1",
"keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes =",
"embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192]",
"vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant",
"r = 4, mel_dim = 80, linear_dim = 1025, use_arff = 0, assistant",
"index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0)",
"# Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses",
"self.assistant = assistant def forward(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm",
"{self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self):",
"fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close()",
"assistant=None): super().__init__() if normalize: target_scale = scale if scale is not None else",
"print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy:",
"k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class",
"(index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) #",
"self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm",
"quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy =",
"entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID logits #mels_lid =",
"self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and",
"and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses)",
"+ x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) +",
"mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy)",
"self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb",
"2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale)",
"quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \",",
"torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram",
"k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class",
"assert self.assistant is not None hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter",
"forward(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3))",
"x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm",
"to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape",
"def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale =",
"self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k)",
"> 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1)",
"entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs = {} B",
"x.shape, output_2classes.shape) out0 = (output - x).detach() + x out1 = (x.detach() -",
"long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes",
"= hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes",
"mel_dim = 80, linear_dim = 1025, use_arff = 0, assistant = None): super(SILA,",
"1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc =",
"mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #",
"embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) #",
"x: \", output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach() + x out1",
"Class Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self,",
"self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes,",
"0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) +",
"embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy =",
"embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes =",
"current_element = element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r",
"min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not",
"self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4)",
"embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] -",
"embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2))",
"plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists =",
"sys.path.append(FALCON_DIR) from models import * from layers import * from util import *",
"scale=None, assistant=None): super().__init__() if normalize: target_scale = scale if scale is not None",
"entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4",
"embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses",
"target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2,",
"mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \",",
"= torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x: \", output.shape,",
"self.after_update() self.plot_histogram = 0 self.assistant = assistant def forward(self, x0, chunk_size=512): fig =",
"self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() *",
"* prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes",
"\", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \",",
"outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs:",
"self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2),",
"- (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses =",
"torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and original",
"len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) /",
"= (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1))",
"max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes *",
"= torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy)",
"self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor self.n_classes = n_classes",
"hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4,",
"mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B =",
"mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs:",
"self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k)",
"'.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes))",
"= quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16,",
"-1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x:",
"1025, use_arff = 0, assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer =",
"assistant) encoder_layers = [ (2, 4, 1), (2, 4, 1), (2, 4, 1),",
"Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \",",
"+ 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape",
"= embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len)",
"mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels =",
"vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale = scale if scale is",
"= self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb))",
"FALCON_DIR = os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers import * from",
"embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2))",
"// self.r, -1) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get",
"print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy:",
"vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb =",
"self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels, embedding): outputs =",
"= {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples,",
"(B, T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False,",
"* math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm",
"of output and x: \", output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach()",
"else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs",
"self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes,",
"* prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes +",
"x1.shape, embedding.shape) # Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes = []",
"None: current_element = element arr_new.append(element) elif element == current_element: continue else: current_element =",
"#self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim",
"index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not None hists = hist_2classes.cpu().numpy()",
"\", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] -",
"and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes)",
"Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes,",
"requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor",
"phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else:",
"after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2,",
"/ 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter",
"= (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes",
"self.use_arff = use_arff def forward(self, mels, embedding): outputs = {} B = mels.size(0)",
"embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get",
"mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape",
"self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self,",
"- (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes =",
"== current_element: continue else: current_element = element arr_new.append(element) return arr_new class SILA(nn.Module): def",
"= self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1)",
"target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2,",
"self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes",
"index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1)",
"- (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes =",
"for element in arr: if current_element is None: current_element = element arr_new.append(element) elif",
"None for element in arr: if current_element is None: current_element = element arr_new.append(element)",
"x1 and embedding: \", x1.shape, embedding.shape) # Perform chunking to avoid overflowing GPU",
"normalize=True, assistant = assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant =",
"if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer",
"__init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim = 80, linear_dim = 1025, use_arff",
"= embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0,",
"tensor #print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape) # Perform chunking to",
"self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else:",
"* (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape)",
"self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = -",
"import * from layers import * from util import * from model import",
"noise to raw audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003",
"self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale:",
"torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale",
"SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim = 80, linear_dim =",
"out0 = (output - x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2",
"#print(\"Shape of output and x: \", output.shape, x.shape, output_2classes.shape) out0 = (output -",
"out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm",
"= nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet",
"index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat:",
"mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels",
"hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert",
"* prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = - (prob_4classes",
"output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1,",
"mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized",
"prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item()",
"x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x",
"self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes =",
"encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID logits #mels_lid",
"= quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [ (2, 4,",
"for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes) print(\"3",
"#mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r,",
"super().__init__() if normalize: target_scale = scale if scale is not None else 0.06",
"embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy",
"entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale",
"[2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim])",
"input_dim=80, r = 4, mel_dim = 80, linear_dim = 1025, use_arff = 0,",
"nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def forward(self,",
"latents_2classes, entropy_2classes) print(\"3 Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents",
"of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \",",
"Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits =",
"self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels)",
"* index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses +",
"and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:,",
"of x1 and embedding: \", x1.shape, embedding.shape) # Perform chunking to avoid overflowing",
"to raw audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 *",
"and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty, entropy",
"hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1))",
"embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes =",
"self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len,",
"4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter",
"= self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes,",
"outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy",
"target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512):",
"torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x: \", output.shape, x.shape,",
"Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \",",
"= [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256,",
"# Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels,",
"(0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled",
"latents_2classes = ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for",
"target_scale = scale if scale is not None else 0.06 self.embedding_scale = target_scale",
"0) / len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes >",
"encoder_layers = [ (2, 4, 1), (2, 4, 1), (2, 4, 1), (2,",
"* index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long",
"self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant def forward(self, x0,",
"models import * from layers import * from util import * from model",
"https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig",
"= 0 self.assistant = assistant def forward(self, x0, chunk_size=512): fig = None if",
"self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len,",
"embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1,",
"in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape,",
"(index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist()",
"1, vec_len) numeric tensor #print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape) #",
"mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape,",
"class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim = 80, linear_dim",
"assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True,",
"] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256,",
"projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff",
"vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes",
"_, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes,",
"+ self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes",
"mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs",
"emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels",
"= [] index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0):",
"self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb =",
"index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses = [] for",
"from models import * from layers import * from util import * from",
"= 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes",
"self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k in",
"quantized.squeeze(2) # Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized)",
"self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return",
"tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant def forward(self,",
"inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb],",
"of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:,",
"= nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes #",
"lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs = {} B = mels.size(0) #",
"= CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc =",
"self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig =",
"(output - x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x",
"emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled =",
"\", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] -",
"= plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists =",
"= hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes',",
"x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1 and",
"output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x: \", output.shape, x.shape, output_2classes.shape)",
"for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses",
"'.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes))",
"# Remove repeated entries def deduplicate(self, arr): arr_new = [] current_element = None",
"= nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True)",
"Input: (B, T, n_channels, vec_len) numeric tensor n_channels == 1 usually Output: (B,",
"0, assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4),",
"= target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None",
"plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram =",
"current_element = element arr_new.append(element) elif element == current_element: continue else: current_element = element",
"/ 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() #",
"n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None):",
"self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff",
"latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents",
"(prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes",
"= (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}')",
"self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def",
"prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item()",
"torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled =",
"0) / len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses >",
"self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) #",
"logits #print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized)",
"mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get the",
"x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2))",
"entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self, arr): arr_new =",
"self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and",
"\", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def",
"(N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes)",
"x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape,",
"self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized",
"if scale is not None else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale",
"n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale = scale if",
"self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3,",
"arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim = 80,",
"\", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape)",
"mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy =",
"index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) #",
"(x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return",
"\", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs:",
"-1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs =",
"keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale",
"arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r = 4, mel_dim",
"#mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and mels_downsampled: \",",
"= target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels,",
"#print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled:",
"approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2))",
"index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1)",
"= x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses =",
"= hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes",
"scale is not None else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else:",
"embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2],",
"dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff:",
"= target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes /",
"entropy def forward_getlid(self, mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1)",
"* class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric tensor n_channels ==",
"target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2,",
"/ len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0)",
"\"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale",
"from layers import * from util import * from model import * class",
":,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] -",
"quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty,",
"* prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses",
"(2, 4, 1), (1, 4, 1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim,",
"not None else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale =",
"len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes",
"current_element is None: current_element = element arr_new.append(element) elif element == current_element: continue else:",
"input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network",
"' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in",
"= [] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk,",
"output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes =",
"- embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0)",
"entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale *",
"for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes",
"= torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses =",
"not None hists = hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) /",
"assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers =",
"element arr_new.append(element) elif element == current_element: continue else: current_element = element arr_new.append(element) return",
"plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes =",
"x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes,",
"= self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 =",
"keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale",
"keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm *",
"index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256]",
"phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the",
"n_classes # self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0",
"n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape)",
"(2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (2,",
"mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs",
"UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim",
"\", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class",
"= index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes =",
"= 0, assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256,",
"= [ (2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4,",
"= torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and",
"index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = '",
"if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self,",
"and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self, arr): arr_new",
"index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes =",
"-1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get the LID",
"/ self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm",
"B = mels.size(0) # Add noise to raw audio mels_noisy = mels *",
"self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet =",
"self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [ (2,",
"' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in",
"= quantized.squeeze(2) # Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) =",
"- output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] =",
"current_element: continue else: current_element = element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self,",
"= embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape",
"embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor",
"Reconstruction #print(\"Shapes of quantized and original mels to the deocder: \", quantized.shape, mels.shape)",
"\", output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach() + x out1 =",
"mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of",
"import * from util import * from model import * class quantizer_kotha_arff(nn.Module): \"\"\"",
"self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1,",
"+ self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses =",
"= index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant",
"4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale)",
"= torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update()",
"index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size,",
"\", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if",
"self.plot_histogram = 0 self.assistant = assistant def forward(self, x0, chunk_size=512): fig = None",
"self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes =",
"index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of",
"of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff:",
"hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes",
"index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1)",
"is not None else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale",
"step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128,",
"1), (2, 4, 1), (2, 4, 1), (1, 4, 1), (2, 4, 1),",
"nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_3classes = nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) *",
"(2, 4, 1), (2, 4, 1), (2, 4, 1), (1, 4, 1), (2,",
"= (output - x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 =",
"entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1))",
"torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor hist_2classes",
"= self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses",
"torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses,",
"(index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for",
"* self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels,",
"self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes)",
"chunking to avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes",
"hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not None hists",
"= None for element in arr: if current_element is None: current_element = element",
"out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0,",
"plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0) /",
"output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes,",
"torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and",
"entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy",
"nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset:",
"math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2,",
"entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes)",
"of linear outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(),",
"= (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes =",
"= - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1)",
"#quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return",
"= 1025, use_arff = 0, assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer",
"* math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None",
"index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5)",
"self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0)",
"= self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2))",
"1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (1, 4, 1),",
"/ self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes",
"(lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes,",
"nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8,",
"torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones",
"3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale)",
"vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes # self.offset: (n_channels) long",
"= {} B = mels.size(0) # Add noise to raw audio mels_noisy =",
"\", mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2))",
"index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5)",
"#print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones quantized,",
"#print(\"Shapes of quantized and original mels to the deocder: \", quantized.shape, mels.shape) mel_outputs,",
"and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized, vq_penalty,",
"index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses =",
"prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0) / len(index_3classes) entropy_3classes = - (prob_3classes *",
"= self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy",
"= self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1)",
"nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) *",
"embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0)",
"= self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine",
"+ self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes = ' '.join(str(k) for k",
"if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True))",
"target_scale else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2,",
"math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2,",
"/ self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def",
"super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant)",
"* x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric tensor",
"self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _,",
"- embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes,",
":,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0)",
"entropy def forward_noreconstruction(self, mels, embedding): outputs = {} B = mels.size(0) # Add",
"n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5)",
"= element arr_new.append(element) elif element == current_element: continue else: current_element = element arr_new.append(element)",
"hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses =",
"0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of",
"= target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes /",
"#mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy =",
"max=3.5) if self.plot_histogram: assert self.assistant is not None hists = hist_2classes.cpu().numpy() fig =",
"Class Latents and entropy: \", latents_3classes, entropy_3classes) print(\"4 Class Latents and entropy: \",",
"entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0) / len(index_nclasses)",
"math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm *",
"entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) #",
"for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2",
"embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2))",
"output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes =",
"mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim)",
"> 0) / len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes",
"/ self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses =",
"= index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5,",
"quantized = quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb =",
"None else 0.06 self.embedding_scale = target_scale self.normalize_scale = target_scale else: self.embedding_scale = 1e-3",
"= scale if scale is not None else 0.06 self.embedding_scale = target_scale self.normalize_scale",
"(N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1 and embedding: \", x1.shape,",
"embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes",
"LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) #",
"weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes",
"entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2)",
"index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes,",
"= hist_2classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes',",
"hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig)",
"/ len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist()",
"mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape)",
"output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1)",
"and x: \", output.shape, x.shape, output_2classes.shape) out0 = (output - x).detach() + x",
"print(\"4 Class Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy:",
"self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized",
"= self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2))",
"= os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers import * from util",
"\", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape)",
"latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated",
"* math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm /",
"= mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels,",
"# Add noise to raw audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp()",
"T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None,",
"emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1)",
"import * from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels,",
"self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64)",
"[] index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes",
"numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2],",
"= [] for x1_chunk in x1.split(chunk_size, dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and",
"embedding: \", x1.shape, embedding.shape) # Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes",
"CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim)",
"* self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True)",
"output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of",
"latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for",
"https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(64) / 64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes",
"entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy =",
"quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized and original mels",
"prob_nclasses.log()).sum().item() index1_2classes = (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes =",
"nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet =",
"= assistant def forward(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm =",
"if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0 /",
"the LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_)",
"= mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs)",
"output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses",
"entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove repeated entries",
"torch.cat([quantized, emb], dim=-1) # Get the LID logits #print(\"Shape of quantized: \", quantized.shape)",
"(out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad():",
"+ self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0,",
"/ x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes =",
"= DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales",
"quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs #emb",
"# https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy()",
"+ self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) * index_nclasses.size(1)) # index1:",
"self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \",",
"self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda() * n_classes",
"self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and",
"entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes)",
"layers import * from util import * from model import * class quantizer_kotha_arff(nn.Module):",
"64) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_nclasses', fig) plt.close() self.plot_histogram = 0 prob_2classes = hist_2classes.masked_select(hist_2classes > 0)",
"= None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant",
"x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape",
"embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192]",
"2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim])",
"mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs",
"/ len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0)",
"1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) * self.embedding_scale)",
"n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale = scale if scale",
"- embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes",
"entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs = {}",
"x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2],",
"{x.std()}') x1 = x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels,",
"index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) *",
"max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses =",
"= element arr_new.append(element) return arr_new class SILA(nn.Module): def __init__(self, embedding_dim=256, input_dim=80, r =",
"+ (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2,",
"self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1)",
"linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) #",
"mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape)",
"DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales =",
"= use_arff def forward(self, mels, embedding): outputs = {} B = mels.size(0) #",
"/ len(index_4classes) entropy_4classes = - (prob_4classes * prob_4classes.log()).sum().item() prob_nclasses = hist_nclasses.masked_select(hist_nclasses > 0)",
"and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled",
"self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments,",
"= plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists",
"= CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2,",
"entropy_nclasses) # Remove repeated entries def deduplicate(self, arr): arr_new = [] current_element =",
"mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb",
"assistant = assistant) encoder_layers = [ (2, 4, 1), (2, 4, 1), (2,",
"plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists,",
"fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists",
"weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure()",
"= nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def",
"repeated entries def deduplicate(self, arr): arr_new = [] current_element = None for element",
"= x.reshape(x.size(0) * x.size(1), x.size(2), 1, x.size(3)) # x1: (N*samples, n_channels, 1, vec_len)",
"\"\"\" Input: (B, T, n_channels, vec_len) numeric tensor n_channels == 1 usually Output:",
"self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k)",
"vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__()",
"and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:,",
"output_nclasses], dim=-1) #print(\"Shape of output and x: \", output.shape, x.shape, output_2classes.shape) out0 =",
"x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x",
"memory_lengths=None) #print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape",
"linear outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(),",
"self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True))",
"forward(self, mels, embedding): outputs = {} B = mels.size(0) # Add noise to",
"// self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels",
"sys FALCON_DIR = os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from layers import *",
"Latents and entropy: \", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses,",
"self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes =",
"-1) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones",
"output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes",
"# https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy()",
"0) / len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes >",
"1), (1, 4, 1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128,",
"<filename>local/model_vqvae.py<gh_stars>1-10 import os, sys FALCON_DIR = os.environ.get('FALCONDIR') sys.path.append(FALCON_DIR) from models import * from",
"mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get",
"x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes, output_4classes, output_nclasses], dim=-1) #print(\"Shape of output",
"fig) plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) /",
"quantized = quantized.squeeze(2) # Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_)",
"* index_nclasses.size(1)) # index1: (N*samples*n_channels) long tensor output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes",
"out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x -",
"= self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2))",
"mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb],",
"0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] - embedding_4classes).norm(dim=3).argmin(dim=2)) index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2))",
"embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes",
"outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \",",
"lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb =",
"self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm =",
"/ self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes =",
"emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of quantized",
"return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs = {} B = mels.size(0)",
"B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy =",
"entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty,",
"else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers = [",
"entropy_4classes, entropy_nclasses) def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2))",
"x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output = torch.cat([output_2classes, output_3classes,",
"* self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset = torch.arange(n_channels).cuda()",
"self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy",
"emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels: \", mels.shape)",
"0 self.assistant = assistant def forward(self, x0, chunk_size=512): fig = None if self.normalize_scale:",
"entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty,",
"index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses + self.offset).view(index_nclasses.size(0) *",
"#logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses)",
"self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm",
"if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, vq_penalty.mean(),",
"self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm",
"normalize=False, scale=None, assistant=None): super().__init__() if normalize: target_scale = scale if scale is not",
"torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5)",
"self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant =",
"= torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate",
"* torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled =",
"= hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes',",
"T, n_channels, vec_len) numeric tensor n_channels == 1 usually Output: (B, T, n_channels,",
"self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm =",
"len(index_nclasses) entropy_nclasses = - (prob_nclasses * prob_nclasses.log()).sum().item() index1_2classes = (index_2classes + self.offset).view(index_2classes.size(0) *",
"if normalize: target_scale = scale if scale is not None else 0.06 self.embedding_scale",
"x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1],",
"- output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0,",
"_, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(),",
"[ (2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1),",
"dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor hist_2classes =",
"raw audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels)",
"[] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses = [] for x1_chunk in",
"hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) prob_2classes = hist_2classes.masked_select(hist_2classes > 0) / len(index_2classes) entropy_2classes",
"= self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return",
"= target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes /",
"= ' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \",",
"output_4classes, output_nclasses], dim=-1) #print(\"Shape of output and x: \", output.shape, x.shape, output_2classes.shape) out0",
"overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes = [] index_chunks_nclasses",
"def forward(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale *",
"# Get approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2)",
"audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape",
"Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized,",
"embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric",
"torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) #",
"= index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not None hists =",
"* torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb))",
"-1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and mels_downsampled:",
"import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric tensor n_channels",
"def forward_getlid(self, mels, embedding): B = mels.shape[0] emb = embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb",
"= self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) #",
"= output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses = output_flat_nclasses.view(x.shape[0], x.shape[1], x.shape[2], -1) output =",
"encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy =",
"numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if",
"mels_downsampled.shape) # Get approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized =",
"long tensor self.n_classes = n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant def",
"x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes",
"/ len(index_2classes) entropy_2classes = - (prob_2classes * prob_2classes.log()).sum().item() prob_3classes = hist_3classes.masked_select(hist_3classes > 0)",
"embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x]",
"= self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0 / x0.norm(dim=3, keepdim=True) embedding_2classes",
"quantized.squeeze(2) # Combine inputs #emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) #emb = torch.tanh(self.embedding_fc(emb)) #quantized",
"== 1 usually Output: (B, T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self,",
"= torch.cat([quantized, emb], dim=-1) # Get the LID logits #print(\"Shape of quantized: \",",
"#self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc",
"self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True)",
"inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb],",
"weights=np.ones(2) / 2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() #",
"x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1],",
"= self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2))",
"projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear = nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per",
"hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1))",
"https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig) plt.close() hists = hist_4classes.cpu().numpy() fig",
"* self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True)",
"= [] current_element = None for element in arr: if current_element is None:",
"lid_logits, entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs",
"quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len) numeric tensor n_channels == 1 usually",
"* from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B, T, n_channels, vec_len)",
"= assistant) encoder_layers = [ (2, 4, 1), (2, 4, 1), (2, 4,",
"use_arff = 0, assistant = None): super(SILA, self).__init__() if use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1,",
"self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses =",
"logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine",
"-1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes of",
"= index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes = index_4classes.float().cpu().histc(bins=4, min=-0.5,",
"/ 4) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_4classes', fig) plt.close() hists = hist_nclasses.cpu().numpy() fig = plt.figure() #",
"linear_dim = 1025, use_arff = 0, assistant = None): super(SILA, self).__init__() if use_arff:",
"= self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits,",
"index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3,",
"k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes =",
"self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes",
"* (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb =",
"(index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist()",
"output_2classes.shape) out0 = (output - x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2)",
"index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses",
"/ self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig = None if self.normalize_scale: target_norm",
"entries def deduplicate(self, arr): arr_new = [] current_element = None for element in",
"self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits,",
"k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses =",
"entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs = {} B =",
"entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized =",
"else: self.embedding_scale = 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len,",
"= nn.Parameter(torch.randn(n_channels, 3, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True)",
"emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1)",
"2) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_2classes', fig) hists = hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists,",
"* self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True)",
"/ self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm",
"dim=-1) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy) #print(\"Shape of mels and",
"linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim, K=8, projections=[256, embedding_dim]) self.lid_lstm",
"#mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs",
"torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #print(\"Shape of mels: \", mels.shape) mels_downsampled = self.downsampling_encoder(mels_noisy)",
"return mel_outputs, linear_outputs, alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B",
"index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long",
"= self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1 = x.reshape(x.size(0) * x.size(1),",
"= self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm / self.embedding0_nclasses.norm(dim=2, keepdim=True)) def get_quantizedindices(self, x0, chunk_size=512): fig",
"- (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes > 0) / len(index_4classes) entropy_4classes =",
"x).detach() + x out1 = (x.detach() - output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2)",
"embedding): outputs = {} B = mels.size(0) # Add noise to raw audio",
"= mels_downsampled.view(B, mels_downsampled.size(1) // self.r, -1) #print(\"Shape of mels and mels_downsampled: \", mels.shape,",
"Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized,",
"= 1e-3 #1e-3 self.normalize_scale = None self.embedding0_2classes = nn.Parameter(torch.randn(n_channels, 2, vec_len, requires_grad=True) *",
"= r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear =",
"= torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor",
"' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k in",
"approximate phones quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Get",
"= embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0],",
"= nn.Linear(mel_dim * 2, linear_dim) print(\"Outputs per step: \", r) #self.lid_postnet = CBHG(embedding_dim,",
"= None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm *",
"target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm / self.embedding0_2classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale *",
"-1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy = mels mels_downsampled",
"'.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes, entropy_2classes)",
"# x1: (N*samples, n_channels, 1, vec_len) numeric tensor #print(\"Shape of x1 and embedding:",
"+ self.offset).view(index_2classes.size(0) * index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes =",
"else: x = x0 embedding_2classes = self.embedding0_2classes embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes",
"arr): arr_new = [] current_element = None for element in arr: if current_element",
"#print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape) # Perform chunking to avoid",
"embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction",
"* x0 / x0.norm(dim=3, keepdim=True) embedding_2classes = target_norm * self.embedding0_2classes / self.embedding0_2classes.norm(dim=2, keepdim=True)",
"= self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape) # Return return mel_outputs, linear_outputs,",
"# output_flat: (N*samples*n_channels, vec_len) numeric tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes",
"def after_update(self): if self.normalize_scale: with torch.no_grad(): target_norm = self.embedding_scale * math.sqrt(self.embedding0_2classes.size(2)) self.embedding0_2classes.mul_(target_norm /",
"= (index_2classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_3classes = (index_3classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) +",
"long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes = index_3classes.float().cpu().histc(bins=3, min=-0.5, max=2.5) hist_4classes",
"lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B = mels.shape[0] emb =",
"self.embedding0_2classes.norm(dim=2, keepdim=True) embedding_3classes = target_norm * self.embedding0_3classes / self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm",
"1), (2, 4, 1), ] self.downsampling_encoder = DownsamplingEncoderStrict(embedding_dim, encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder =",
"fig = None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm",
"= mels * (0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:]",
"self.offset).cpu().numpy().tolist() index1_4classes = (index_4classes.squeeze(1) + self.offset).cpu().numpy().tolist() index1_nclasses = (index_nclasses.squeeze(1) + self.offset).cpu().numpy().tolist() latents_2classes =",
"# index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5, max=1.5) hist_3classes =",
"else: latents, entropy = self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized =",
"= self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb",
"vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses",
"#mels_noisy = mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized,",
"self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses = (index_nclasses",
"vec_len) numeric tensor #print(\"Shape of x1 and embedding: \", x1.shape, embedding.shape) # Perform",
"quantized and original mels to the deocder: \", quantized.shape, mels.shape) mel_outputs, alignments =",
"+ 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb",
"(lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B, mels_downsampled.shape[1],",
"= self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2))",
"hist_3classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(3) / 3) plt.gca().yaxis.set_major_formatter(PercentFormatter(1)) self.assistant.log_image('latent_histograms_3classes', fig)",
"\", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B,",
"\", latents_4classes, entropy_4classes) print(\"N Class Latents and entropy: \", latents_nclasses, entropy_nclasses) # Remove",
"mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb], dim=-1) #print(\"Shape of mels:",
"x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes.shape) index_chunks_2classes.append((x1_chunk[:, :,:, 0:64]",
"mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled = mels_downsampled.view(B, mels_downsampled.size(1)",
"from util import * from model import * class quantizer_kotha_arff(nn.Module): \"\"\" Input: (B,",
"target_norm = self.embedding_scale * math.sqrt(self.embedding0_3classes.size(2)) self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale *",
"mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r, -1) #mels_downsampled =",
"_, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) # Combine inputs emb = embedding.unsqueeze(1).expand(B,",
"4, 1), (2, 4, 1), (2, 4, 1), (2, 4, 1), (2, 4,",
"output).float().norm(dim=3).pow(2) out2 = (x - output.detach()).float().norm(dim=3).pow(2) + (x - x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1,",
"to avoid overflowing GPU RAM. index_chunks_2classes = [] index_chunks_3classes = [] index_chunks_4classes =",
"self.embedding0_3classes.mul_(target_norm / self.embedding0_3classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True))",
"usually Output: (B, T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes,",
"torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy",
"\", mels.shape, mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes,",
"/ self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x",
"normalize=True, assistant = assistant) encoder_layers = [ (2, 4, 1), (2, 4, 1),",
"= ' '.join(str(k) for k in self.deduplicate(index1_2classes)) latents_3classes = ' '.join(str(k) for k",
"= output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_4classes = output_flat_4classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_nclasses =",
"self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim = mel_dim self.last_linear",
"# Get the LID logits #print(\"Shape of quantized: \", quantized.shape) #quantized = self.lid_postnet(quantized)",
"= ' '.join(str(k) for k in self.deduplicate(index1_4classes)) latents_nclasses = ' '.join(str(k) for k",
"mels_downsampled.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) quantized = torch.cat([quantized, emb], dim=-1) # Reconstruction #print(\"Shapes",
"tensor output_2classes = output_flat_2classes.view(x.shape[0], x.shape[1], x.shape[2], -1) output_3classes = output_flat_3classes.view(x.shape[0], x.shape[1], x.shape[2], -1)",
"mel outputs: \", mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear",
"def forward(self, mels, embedding): outputs = {} B = mels.size(0) # Add noise",
"= target_norm * self.embedding0_nclasses / self.embedding0_nclasses.norm(dim=2, keepdim=True) else: x = x0 embedding_2classes =",
"outputs = {} B = mels.size(0) # Add noise to raw audio mels_noisy",
"quantized.shape) #quantized = self.lid_postnet(quantized) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff:",
"min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is not None hists = hist_2classes.cpu().numpy() fig",
"chunk_size=512): fig = None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x =",
"deocder: \", quantized.shape, mels.shape) mel_outputs, alignments = self.decoder(quantized, mels, memory_lengths=None) #print(\"Shape of mel",
"' '.join(str(k) for k in self.deduplicate(index1_nclasses)) print(\"2 Class Latents and entropy: \", latents_2classes,",
"embedding_3classes = self.embedding0_3classes embedding_4classes = self.embedding0_4classes embedding_nclasses = self.embedding0_nclasses #logger.log(f'std[x] = {x.std()}') x1",
"Add noise to raw audio mels_noisy = mels * (0.02 * torch.randn(mels.shape).cuda()).exp() +",
"plt.close() hists = hist_4classes.cpu().numpy() fig = plt.figure() # https://stackoverflow.com/questions/51473993/plot-an-histogram-with-y-axis-as-percentage-using-funcformatter plt.hist(hists, weights=np.ones(4) / 4)",
"latents_nclasses, entropy_nclasses) # Remove repeated entries def deduplicate(self, arr): arr_new = [] current_element",
"#print(\"Shape of mel outputs: \", mel_outputs.shape) mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of",
"self.embedding_scale * math.sqrt(self.embedding0_4classes.size(2)) self.embedding0_4classes.mul_(target_norm / self.embedding0_4classes.norm(dim=2, keepdim=True)) target_norm = self.embedding_scale * math.sqrt(self.embedding0_nclasses.size(2)) self.embedding0_nclasses.mul_(target_norm",
"mels_downsampled.shape) # Get approximate phones if self.use_arff: quantized, vq_penalty, encoder_penalty, entropy_2classes, entropy_3classes, entropy_4classes,",
"requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len, requires_grad=True) * self.embedding_scale) self.offset =",
"deduplicate(self, arr): arr_new = [] current_element = None for element in arr: if",
"* n_classes # self.offset: (n_channels) long tensor self.n_classes = n_classes self.after_update() self.plot_histogram =",
"index_2classes.size(1)) index1_3classes = (index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0)",
"mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels_noisy, emb],",
"\", x1.shape, embedding.shape) # Perform chunking to avoid overflowing GPU RAM. index_chunks_2classes =",
"self.quantizer.get_quantizedindices(mels_downsampled.unsqueeze(2)) quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2)) quantized = quantized.squeeze(2) # Combine inputs",
"of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate phones quantized, vq_penalty,",
"(0.02 * torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B,",
"None if self.normalize_scale: target_norm = self.normalize_scale * math.sqrt(x0.size(3)) x = target_norm * x0",
"dim=0): #print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$",
"bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff = use_arff def forward(self, mels, embedding):",
"index_chunks_nclasses.append((x1_chunk[:,:,:,192:256] - embedding_nclasses).norm(dim=3).argmin(dim=2)) index_2classes = torch.cat(index_chunks_2classes, dim=0) index_3classes = torch.cat(index_chunks_3classes, dim=0) index_4classes =",
"> 0) / len(index_3classes) entropy_3classes = - (prob_3classes * prob_3classes.log()).sum().item() prob_4classes = hist_4classes.masked_select(hist_4classes",
"embedding_dim]) self.lid_lstm = nn.LSTM(embedding_dim, 128, bidirectional=True, batch_first=True) self.lid_fc = nn.Linear(128, 2) self.use_arff =",
"torch.cat(index_chunks_3classes, dim=0) index_4classes = torch.cat(index_chunks_4classes, dim=0) index_nclasses = torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples,",
"(index_3classes + self.offset).view(index_3classes.size(0) * index_3classes.size(1)) index1_4classes = (index_4classes + self.offset).view(index_4classes.size(0) * index_4classes.size(1)) index1_nclasses",
"Output: (B, T, n_channels, vec_len) numeric tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len,",
"#self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8,",
"self.embedding0_4classes = nn.Parameter(torch.randn(n_channels, 4, vec_len, requires_grad=True) * self.embedding_scale) self.embedding0_nclasses = nn.Parameter(torch.randn(n_channels, 16, vec_len,",
"entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses return lid_logits, entropy def forward_noreconstruction(self, mels, embedding): outputs =",
"= ' '.join(str(k) for k in self.deduplicate(index1_3classes)) latents_4classes = ' '.join(str(k) for k",
"mel_outputs.shape) linear_outputs = self.postnet(mel_outputs) linear_outputs = self.last_linear(linear_outputs) #print(\"Shape of linear outputs: \", linear_outputs.shape)",
"= UpsampleNetwork(self.decoder.upsample_scales) self.r = r self.postnet = CBHG(mel_dim, K=8, projections=[256, mel_dim]) self.mel_dim =",
"= embedding.unsqueeze(1).expand(B, mels.shape[1], -1) emb = torch.tanh(self.embedding_fc(emb)) mels_noisy = torch.cat([mels, emb], dim=-1) #mels_noisy",
"alignments, lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy def forward_getlid(self, mels, embedding): B = mels.shape[0] emb",
"dim=-1) #print(\"Shape of output and x: \", output.shape, x.shape, output_2classes.shape) out0 = (output",
"torch.tanh(self.embedding_fc(emb)) #quantized = torch.cat([quantized, emb], dim=-1) # Get the LID logits #print(\"Shape of",
"torch.randn(mels.shape).cuda()).exp() + 0.003 * torch.randn_like(mels) #mels_noisy = mels_noisy[:,fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b,:] emb = embedding.unsqueeze(1).expand(B, mels_noisy.shape[1], -1)",
"encoder_layers, input_dim=mel_dim+128, use_batchnorm=1) #self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2]",
"#print(\"Shapes of x1_chunk, embedding_2classes, embedding_3classes and embedding_4classes: \", x1_chunk[:,:,:,:63].shape, embedding_2classes.shape, embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:,",
"mel_outputs = mel_outputs.view(B, -1, self.mel_dim) #print(\"Shape of mel outputs: \", mel_outputs.shape) linear_outputs =",
"entropy_2classes, entropy_3classes, entropy_4classes, entropy_nclasses = self.quantizer(mels_downsampled.unsqueeze(2)) else: quantized, vq_penalty, encoder_penalty, entropy = self.quantizer(mels_downsampled.unsqueeze(2))",
"= mels mels_downsampled = self.downsampling_encoder(mels_noisy) # Get approximate phones if self.use_arff: quantized, vq_penalty,",
"self.r, -1) #print(\"Shape of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) # Get approximate",
"tensor \"\"\" def __init__(self, n_channels, n_classes, vec_len, normalize=False, scale=None, assistant=None): super().__init__() if normalize:",
"self.embedding0_3classes.norm(dim=2, keepdim=True) embedding_4classes = target_norm * self.embedding0_4classes / self.embedding0_4classes.norm(dim=2, keepdim=True) embedding_nclasses = target_norm",
"output_flat_2classes = embedding_2classes.view(-1, embedding_2classes.size(2)).index_select(dim=0, index=index1_2classes) output_flat_3classes = embedding_3classes.view(-1, embedding_3classes.size(2)).index_select(dim=0, index=index1_3classes) output_flat_4classes = embedding_4classes.view(-1,",
"(lid_hidden,_) = self.lid_lstm(quantized) lid_logits = self.lid_fc(lid_hidden[-1]) if self.use_arff: return lid_logits, vq_penalty.mean(), encoder_penalty.mean(), entropy_2classes,",
"of mels and mels_downsampled: \", mels.shape, mels_downsampled.shape) #mels = mels.view(B, mels.size(1) // self.r,",
"x0).float().norm(dim=3).pow(2) #logger.log(f'std[embedding0] = {self.embedding0.view(-1, embedding.size(2)).index_select(dim=0, index=index1).std()}') return (out0, out1, out2, entropy_2classes, entropy_3classes, entropy_4classes,",
"index_4classes.float().cpu().histc(bins=4, min=-0.5, max=3.5) hist_nclasses = index_nclasses.float().cpu().histc(bins=64, min=-0.5, max=3.5) if self.plot_histogram: assert self.assistant is",
"4, 1), (2, 4, 1), (1, 4, 1), (2, 4, 1), ] self.downsampling_encoder",
"n_classes self.after_update() self.plot_histogram = 0 self.assistant = assistant def forward(self, x0, chunk_size=512): fig",
"# Get the LID logits #mels_lid = self.lid_postnet(quantized.transpose(1,2)) _, (lid_hidden,_) = self.lid_lstm(quantized) lid_logits",
"output_flat_4classes = embedding_4classes.view(-1, embedding_4classes.size(2)).index_select(dim=0, index=index1_4classes) output_flat_nclasses = embedding_nclasses.view(-1, embedding_nclasses.size(2)).index_select(dim=0, index=index1_nclasses) # output_flat: (N*samples*n_channels,",
"use_arff: self.quantizer = quantizer_kotha_arff(n_channels=1, n_classes=256, vec_len=int(embedding_dim/4), normalize=True, assistant = assistant) else: self.quantizer =",
"= torch.cat(index_chunks_nclasses, dim=0) # index: (N*samples, n_channels) long tensor hist_2classes = index_2classes.float().cpu().histc(bins=2, min=-0.5,",
"#self.decoder = SpecLSTM(input_dim=embedding_dim) self.embedding_fc = nn.Linear(256, 128) #self.decoder.upsample_scales = [2,2] #self.decoder.upsample_network = UpsampleNetwork(self.decoder.upsample_scales)",
"= assistant) else: self.quantizer = quantizer_kotha(n_channels=1, n_classes=16, vec_len=embedding_dim, normalize=True, assistant = assistant) encoder_layers",
"embedding_3classes.shape, embedding_4classes$ index_chunks_2classes.append((x1_chunk[:, :,:, 0:64] - embedding_2classes).norm(dim=3).argmin(dim=2)) index_chunks_3classes.append((x1_chunk[:, :,:,64:128] - embedding_3classes).norm(dim=3).argmin(dim=2)) index_chunks_4classes.append((x1_chunk[:,:,:,128:192] -"
] |
[
"install cpu \"\"\" elif backends[0] == 'cpu': msg = \"Only one compute device",
"msg = \"Only one compute device found: \" + repr(backends) msg += \"\"\"",
"_cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1: import warnings if len(backends) ==",
"get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys import",
". import generators from . import data from ._cli import * from .",
"# # This Source Code is licensed under the MIT 2.0 license. #",
"be accelerated since the only device found is CPU. Consider adding OpenCL or",
"Most of the operations won't be accelerated since the only device found is",
"cpu \"\"\" elif backends[0] == 'cpu': msg = \"Only one compute device found:",
"elif backends[0] == 'cpu': msg = \"Only one compute device found: \" +",
"from ._cli import * from . import _cli __all__ = [\"compute\", \"generators\", \"data\"]",
"benefit from the accelerated versions of the algorithms this library provides. \"\"\" warnings.warn(msg,",
"of the algorithms this library provides. \"\"\" warnings.warn(msg, RuntimeWarning) del backends del stderr",
"try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys import stderr if __SHAPELETS_SETUP__:",
"msg = \"\"\" No backends available. Please use shapelets command line tool to",
"use shapelets command line tool to install a new backend. For example: shapelets",
"under the MIT 2.0 license. # the terms can be found in LICENSE.md",
"here from . import compute from . import generators from . import data",
"__all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1: import warnings if",
"backends available. Please use shapelets command line tool to install a new backend.",
"Normal initialization here from . import compute from . import generators from .",
"= False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else:",
"from . import generators from . import data from ._cli import * from",
"import warnings if len(backends) == 0: msg = \"\"\" No backends available. Please",
"at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import get_versions __version__ = get_versions()['version']",
"compute.get_available_backends() if len(backends) <= 1: import warnings if len(backends) == 0: msg =",
"in LICENSE.md at the root of # this project, or at http://mozilla.org/MPL/2.0/. from",
"from . import data from ._cli import * from . import _cli __all__",
"annotations from ._version import get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except",
"1: import warnings if len(backends) == 0: msg = \"\"\" No backends available.",
"OpenCL or CUDA support to your environment to benefit from the accelerated versions",
"<reponame>shapelets/shapelets-compute # Copyright (c) 2021 Grumpy Cat Software S.L. # # This Source",
"Cat Software S.L. # # This Source Code is licensed under the MIT",
"line tool to install a new backend. For example: shapelets install cpu \"\"\"",
"source directory.\\n\") else: # Normal initialization here from . import compute from .",
"import compute from . import generators from . import data from ._cli import",
"license. # the terms can be found in LICENSE.md at the root of",
"command line tool to install a new backend. For example: shapelets install cpu",
"from __future__ import annotations from ._version import get_versions __version__ = get_versions()['version'] del get_versions",
"project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import get_versions __version__",
"Grumpy Cat Software S.L. # # This Source Code is licensed under the",
"support to your environment to benefit from the accelerated versions of the algorithms",
"new backend. For example: shapelets install cpu \"\"\" elif backends[0] == 'cpu': msg",
"2021 Grumpy Cat Software S.L. # # This Source Code is licensed under",
"__version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from",
"the MIT 2.0 license. # the terms can be found in LICENSE.md at",
"at the root of # this project, or at http://mozilla.org/MPL/2.0/. from __future__ import",
"be found in LICENSE.md at the root of # this project, or at",
"stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal initialization here from",
"found is CPU. Consider adding OpenCL or CUDA support to your environment to",
"import get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ =",
"if len(backends) <= 1: import warnings if len(backends) == 0: msg = \"\"\"",
"Code is licensed under the MIT 2.0 license. # the terms can be",
"backends = compute.get_available_backends() if len(backends) <= 1: import warnings if len(backends) == 0:",
"accelerated versions of the algorithms this library provides. \"\"\" warnings.warn(msg, RuntimeWarning) del backends",
"sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal initialization",
"= \"\"\" No backends available. Please use shapelets command line tool to install",
"or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import get_versions __version__ =",
"CUDA support to your environment to benefit from the accelerated versions of the",
"compute from . import generators from . import data from ._cli import *",
"import * from . import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ +=",
"stderr.write(\"Running from source directory.\\n\") else: # Normal initialization here from . import compute",
"\"\"\" elif backends[0] == 'cpu': msg = \"Only one compute device found: \"",
"+ repr(backends) msg += \"\"\" Most of the operations won't be accelerated since",
"LICENSE.md at the root of # this project, or at http://mozilla.org/MPL/2.0/. from __future__",
"shapelets command line tool to install a new backend. For example: shapelets install",
"if len(backends) == 0: msg = \"\"\" No backends available. Please use shapelets",
"import generators from . import data from ._cli import * from . import",
". import compute from . import generators from . import data from ._cli",
"your environment to benefit from the accelerated versions of the algorithms this library",
"len(backends) <= 1: import warnings if len(backends) == 0: msg = \"\"\" No",
"._version import get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__",
"\"\"\" No backends available. Please use shapelets command line tool to install a",
"\" + repr(backends) msg += \"\"\" Most of the operations won't be accelerated",
"is licensed under the MIT 2.0 license. # the terms can be found",
"shapelets install cpu \"\"\" elif backends[0] == 'cpu': msg = \"Only one compute",
"== 'cpu': msg = \"Only one compute device found: \" + repr(backends) msg",
"of # this project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version",
"accelerated since the only device found is CPU. Consider adding OpenCL or CUDA",
"to your environment to benefit from the accelerated versions of the algorithms this",
"available. Please use shapelets command line tool to install a new backend. For",
"== 0: msg = \"\"\" No backends available. Please use shapelets command line",
"del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys import stderr",
"'cpu': msg = \"Only one compute device found: \" + repr(backends) msg +=",
"Copyright (c) 2021 Grumpy Cat Software S.L. # # This Source Code is",
"won't be accelerated since the only device found is CPU. Consider adding OpenCL",
"MIT 2.0 license. # the terms can be found in LICENSE.md at the",
"+= _cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1: import warnings if len(backends)",
"import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends()",
"NameError: __SHAPELETS_SETUP__ = False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source",
"else: # Normal initialization here from . import compute from . import generators",
"0: msg = \"\"\" No backends available. Please use shapelets command line tool",
"the terms can be found in LICENSE.md at the root of # this",
"CPU. Consider adding OpenCL or CUDA support to your environment to benefit from",
"\"Only one compute device found: \" + repr(backends) msg += \"\"\" Most of",
"of the operations won't be accelerated since the only device found is CPU.",
"only device found is CPU. Consider adding OpenCL or CUDA support to your",
"versions of the algorithms this library provides. \"\"\" warnings.warn(msg, RuntimeWarning) del backends del",
"initialization here from . import compute from . import generators from . import",
"http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import get_versions __version__ = get_versions()['version'] del",
"except NameError: __SHAPELETS_SETUP__ = False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from",
"._cli import * from . import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__",
"one compute device found: \" + repr(backends) msg += \"\"\" Most of the",
"repr(backends) msg += \"\"\" Most of the operations won't be accelerated since the",
"found: \" + repr(backends) msg += \"\"\" Most of the operations won't be",
"backend. For example: shapelets install cpu \"\"\" elif backends[0] == 'cpu': msg =",
"from ._version import get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError:",
"the root of # this project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations",
"= get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys",
"from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal",
"__future__ import annotations from ._version import get_versions __version__ = get_versions()['version'] del get_versions try:",
"Software S.L. # # This Source Code is licensed under the MIT 2.0",
"is CPU. Consider adding OpenCL or CUDA support to your environment to benefit",
"This Source Code is licensed under the MIT 2.0 license. # the terms",
"# Normal initialization here from . import compute from . import generators from",
"__SHAPELETS_SETUP__ = False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\")",
"data from ._cli import * from . import _cli __all__ = [\"compute\", \"generators\",",
"import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal initialization here",
"found in LICENSE.md at the root of # this project, or at http://mozilla.org/MPL/2.0/.",
"to install a new backend. For example: shapelets install cpu \"\"\" elif backends[0]",
"S.L. # # This Source Code is licensed under the MIT 2.0 license.",
"the only device found is CPU. Consider adding OpenCL or CUDA support to",
"_cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if",
"licensed under the MIT 2.0 license. # the terms can be found in",
"= [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends) <=",
"__all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends)",
"(c) 2021 Grumpy Cat Software S.L. # # This Source Code is licensed",
"[\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1:",
"msg += \"\"\" Most of the operations won't be accelerated since the only",
"install a new backend. For example: shapelets install cpu \"\"\" elif backends[0] ==",
"For example: shapelets install cpu \"\"\" elif backends[0] == 'cpu': msg = \"Only",
"# This Source Code is licensed under the MIT 2.0 license. # the",
"example: shapelets install cpu \"\"\" elif backends[0] == 'cpu': msg = \"Only one",
"False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: #",
"device found is CPU. Consider adding OpenCL or CUDA support to your environment",
"terms can be found in LICENSE.md at the root of # this project,",
"+= \"\"\" Most of the operations won't be accelerated since the only device",
"= \"Only one compute device found: \" + repr(backends) msg += \"\"\" Most",
"__SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal initialization here from . import",
"from . import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends",
"\"\"\" Most of the operations won't be accelerated since the only device found",
"the accelerated versions of the algorithms this library provides. \"\"\" warnings.warn(msg, RuntimeWarning) del",
"Source Code is licensed under the MIT 2.0 license. # the terms can",
"or CUDA support to your environment to benefit from the accelerated versions of",
"from . import compute from . import generators from . import data from",
"warnings if len(backends) == 0: msg = \"\"\" No backends available. Please use",
"__SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys import stderr if __SHAPELETS_SETUP__: stderr.write(\"Running",
"generators from . import data from ._cli import * from . import _cli",
"Please use shapelets command line tool to install a new backend. For example:",
"<= 1: import warnings if len(backends) == 0: msg = \"\"\" No backends",
"can be found in LICENSE.md at the root of # this project, or",
"since the only device found is CPU. Consider adding OpenCL or CUDA support",
"= compute.get_available_backends() if len(backends) <= 1: import warnings if len(backends) == 0: msg",
". import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__ backends =",
"get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False from sys import stderr if",
"No backends available. Please use shapelets command line tool to install a new",
"import annotations from ._version import get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__",
"2.0 license. # the terms can be found in LICENSE.md at the root",
"Consider adding OpenCL or CUDA support to your environment to benefit from the",
"from source directory.\\n\") else: # Normal initialization here from . import compute from",
"root of # this project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from",
"\"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1: import warnings",
"a new backend. For example: shapelets install cpu \"\"\" elif backends[0] == 'cpu':",
"the operations won't be accelerated since the only device found is CPU. Consider",
"# the terms can be found in LICENSE.md at the root of #",
"len(backends) == 0: msg = \"\"\" No backends available. Please use shapelets command",
"environment to benefit from the accelerated versions of the algorithms this library provides.",
"if __SHAPELETS_SETUP__: stderr.write(\"Running from source directory.\\n\") else: # Normal initialization here from .",
"directory.\\n\") else: # Normal initialization here from . import compute from . import",
". import data from ._cli import * from . import _cli __all__ =",
"# Copyright (c) 2021 Grumpy Cat Software S.L. # # This Source Code",
"get_versions __version__ = get_versions()['version'] del get_versions try: __SHAPELETS_SETUP__ except NameError: __SHAPELETS_SETUP__ = False",
"* from . import _cli __all__ = [\"compute\", \"generators\", \"data\"] __all__ += _cli.__all__",
"operations won't be accelerated since the only device found is CPU. Consider adding",
"from the accelerated versions of the algorithms this library provides. \"\"\" warnings.warn(msg, RuntimeWarning)",
"backends[0] == 'cpu': msg = \"Only one compute device found: \" + repr(backends)",
"compute device found: \" + repr(backends) msg += \"\"\" Most of the operations",
"tool to install a new backend. For example: shapelets install cpu \"\"\" elif",
"to benefit from the accelerated versions of the algorithms this library provides. \"\"\"",
"# this project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import",
"device found: \" + repr(backends) msg += \"\"\" Most of the operations won't",
"this project, or at http://mozilla.org/MPL/2.0/. from __future__ import annotations from ._version import get_versions",
"\"generators\", \"data\"] __all__ += _cli.__all__ backends = compute.get_available_backends() if len(backends) <= 1: import",
"import data from ._cli import * from . import _cli __all__ = [\"compute\",",
"adding OpenCL or CUDA support to your environment to benefit from the accelerated"
] |
[
"open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count",
"f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count = 1 while not answer.startswith(\"We\"):",
"1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1",
"answer = r.text.strip() count += 1 print(f\"Requesting next file with answer. Requested: {count}\")",
"answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting next file",
"= requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting next file with answer.",
"= f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count = 1 while not",
"+= 1 print(f\"Requesting next file with answer. Requested: {count}\") else: final_answer = answer",
"count = 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count",
"not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting next",
"while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting",
"f: first_url = f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count = 1",
"r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting next file with",
"as f: first_url = f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count =",
"with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r = requests.get(first_url) answer = r.text.strip()",
"first_url = f.readline().strip() r = requests.get(first_url) answer = r.text.strip() count = 1 while",
"import requests base_url = \"https://stepic.org/media/attachments/course67/3.6.3/\" with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r",
"= \"https://stepic.org/media/attachments/course67/3.6.3/\" with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r = requests.get(first_url) answer",
"count += 1 print(f\"Requesting next file with answer. Requested: {count}\") else: final_answer =",
"= r.text.strip() count = 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer =",
"requests.get(first_url) answer = r.text.strip() count = 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\")",
"answer = r.text.strip() count = 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer",
"= requests.get(first_url) answer = r.text.strip() count = 1 while not answer.startswith(\"We\"): r =",
"r.text.strip() count = 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip()",
"= 1 while not answer.startswith(\"We\"): r = requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count +=",
"r = requests.get(first_url) answer = r.text.strip() count = 1 while not answer.startswith(\"We\"): r",
"requests base_url = \"https://stepic.org/media/attachments/course67/3.6.3/\" with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r =",
"= r.text.strip() count += 1 print(f\"Requesting next file with answer. Requested: {count}\") else:",
"requests.get(f\"{base_url}{answer}\") answer = r.text.strip() count += 1 print(f\"Requesting next file with answer. Requested:",
"\"https://stepic.org/media/attachments/course67/3.6.3/\" with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r = requests.get(first_url) answer =",
"1 print(f\"Requesting next file with answer. Requested: {count}\") else: final_answer = answer print(final_answer)",
"base_url = \"https://stepic.org/media/attachments/course67/3.6.3/\" with open(\"solutions/week-3/dataset_3378_3.txt\") as f: first_url = f.readline().strip() r = requests.get(first_url)",
"r.text.strip() count += 1 print(f\"Requesting next file with answer. Requested: {count}\") else: final_answer"
] |
[
"tested for the following: * Must be turned on ``workflow_dispatch``. * Must be",
"release workflow) and ``workflow_dispatch``. .. note:: You can manually trigger the AWS tests",
"the pipeline GitHub repository and selecting the `nf-core AWS full size tests` workflow",
"given. \"\"\" passed = [] warned = [] failed = [] fn =",
".. note:: You can manually trigger the AWS tests by going to the",
"workflow incurs AWS costs, therefore it should only be triggered for pipeline releases:",
"pipeline on full size datasets on AWS. This should ensure that the pipeline",
"a warning is given. \"\"\" passed = [] warned = [] failed =",
"(AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test",
"turned on for published releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] ==",
"wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert",
"turned on ``workflow_dispatch``. * Must be turned on for ``workflow_run`` with ``workflows: [\"nf-core",
"\"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\")",
"GitHub Actions workflow is called ``awsfulltest.yml``, and it can be found in the",
"push (release)\"]`` and ``types: [completed]`` * Should run the profile ``test_full`` that should",
"with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]`` * Should run the",
"== [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not",
"failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with",
"The ``.github/workflows/awsfulltest.yml`` file is tested for the following: * Must be turned on",
"to small test datasets run on GitHub Actions, we provide the possibility of",
"releases: ``workflow_run`` (after the docker hub release workflow) and ``workflow_dispatch``. .. note:: You",
"directory. .. warning:: This workflow incurs AWS costs, therefore it should only be",
"KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") #",
"provide a resource estimation. The GitHub Actions workflow is called ``awsfulltest.yml``, and it",
"\".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf =",
"Check that the action is only turned on for published releases try: assert",
"the `Actions` tab on the pipeline GitHub repository and selecting the `nf-core AWS",
"in the ``.github/workflows/`` directory. .. warning:: This workflow incurs AWS costs, therefore it",
"be triggered for pipeline releases: ``workflow_run`` (after the docker hub release workflow) and",
"is triggered correctly\") # Warn if `-profile test` is still unchanged try: steps",
"yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid. In addition to",
"wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in steps if \"run\" in step.keys()])",
"Actions workflow is called ``awsfulltest.yml``, and it can be found in the ``.github/workflows/``",
"the pipeline runs as expected on AWS and provide a resource estimation. The",
"datasets on AWS. This should ensure that the pipeline runs as expected on",
"GitHub Actions awsfulltest is valid. In addition to small test datasets run on",
"``workflow_run`` (after the docker hub release workflow) and ``workflow_dispatch``. .. note:: You can",
"therefore it should only be triggered for pipeline releases: ``workflow_run`` (after the docker",
"actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid. In addition to small test",
"addition to small test datasets run on GitHub Actions, we provide the possibility",
"on AWS and provide a resource estimation. The GitHub Actions workflow is called",
"can be found in the ``.github/workflows/`` directory. .. warning:: This workflow incurs AWS",
"ensure that the pipeline runs as expected on AWS and provide a resource",
"for step in steps if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml`",
"use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\") return",
"full size tests` workflow on the left. .. tip:: For tests on full",
"pipeline GitHub repository and selecting the `nf-core AWS full size tests` workflow on",
"<https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the",
"steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in steps if \"run\"",
"Tower <https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for",
"should test full datasets, not `-profile test`\") return {\"passed\": passed, \"warned\": warned, \"failed\":",
"``.github/workflows/awsfulltest.yml`` file is tested for the following: * Must be turned on ``workflow_dispatch``.",
"assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"]",
"releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"]",
"as expected on AWS and provide a resource estimation. The GitHub Actions workflow",
"wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in",
"not parse yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test \" #",
"e)]} aws_profile = \"-profile test \" # Check that the action is only",
"except Exception as e: return {\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn,",
"any([aws_profile in step[\"run\"] for step in steps if \"run\" in step.keys()]) except (AssertionError,",
"file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test \" # Check that the",
"it should only be triggered for pipeline releases: ``workflow_run`` (after the docker hub",
"a resource estimation. The GitHub Actions workflow is called ``awsfulltest.yml``, and it can",
"def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid. In addition to small",
"``.github/workflows/`` directory. .. warning:: This workflow incurs AWS costs, therefore it should only",
"for published releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker",
"\"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except",
"data prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature can be employed. The",
"``types: [completed]`` * Should run the profile ``test_full`` that should be edited to",
"``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]`` * Should run",
"[] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\")",
"warned = [] failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if",
"You can manually trigger the AWS tests by going to the `Actions` tab",
"note:: You can manually trigger the AWS tests by going to the `Actions`",
"test full datasets, not `-profile test`\") return {\"passed\": passed, \"warned\": warned, \"failed\": failed}",
"to provide the links to full-size datasets. If it runs the profile ``test``,",
"the ``.github/workflows/`` directory. .. warning:: This workflow incurs AWS costs, therefore it should",
"if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile",
"by going to the `Actions` tab on the pipeline GitHub repository and selecting",
"``workflow_dispatch``. * Must be turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker push",
"as fh: wf = yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could not",
"that should be edited to provide the links to full-size datasets. If it",
"pipeline releases: ``workflow_run`` (after the docker hub release workflow) and ``workflow_dispatch``. .. note::",
"is tested for the following: * Must be turned on ``workflow_dispatch``. * Must",
"we provide the possibility of testing the pipeline on full size datasets on",
"is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile",
"the possibility of testing the pipeline on full size datasets on AWS. This",
"release, `Nextflow Tower <https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is",
"workflow is called ``awsfulltest.yml``, and it can be found in the ``.github/workflows/`` directory.",
"full-size datasets. If it runs the profile ``test``, a warning is given. \"\"\"",
".. tip:: For tests on full data prior to release, `Nextflow Tower <https://tower.nf>`_",
"except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered",
"selecting the `nf-core AWS full size tests` workflow on the left. .. tip::",
"provide the links to full-size datasets. If it runs the profile ``test``, a",
"(after the docker hub release workflow) and ``workflow_dispatch``. .. note:: You can manually",
"= [] failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn):",
"correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile test` is still",
"\"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf = yaml.safe_load(fh)",
"passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not",
"#!/usr/bin/env python import os import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest",
"and ``types: [completed]`` * Should run the profile ``test_full`` that should be edited",
"For tests on full data prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature",
".. warning:: This workflow incurs AWS costs, therefore it should only be triggered",
"on for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]`` *",
"be turned on ``workflow_dispatch``. * Must be turned on for ``workflow_run`` with ``workflows:",
"\"-profile test \" # Check that the action is only turned on for",
"This should ensure that the pipeline runs as expected on AWS and provide",
"(release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError):",
"runs the profile ``test``, a warning is given. \"\"\" passed = [] warned",
"= [] warned = [] failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\",",
"test datasets run on GitHub Actions, we provide the possibility of testing the",
"Should run the profile ``test_full`` that should be edited to provide the links",
"following: * Must be turned on ``workflow_dispatch``. * Must be turned on for",
"in steps if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not",
"\"r\") as fh: wf = yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could",
"on ``workflow_dispatch``. * Must be turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker",
"[\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except",
"triggered for pipeline releases: ``workflow_run`` (after the docker hub release workflow) and ``workflow_dispatch``.",
"except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should",
"= [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn,",
"test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for",
"in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"]",
"should be edited to provide the links to full-size datasets. If it runs",
"In addition to small test datasets run on GitHub Actions, we provide the",
"it can be found in the ``.github/workflows/`` directory. .. warning:: This workflow incurs",
"and selecting the `nf-core AWS full size tests` workflow on the left. ..",
"warning is given. \"\"\" passed = [] warned = [] failed = []",
"testing the pipeline on full size datasets on AWS. This should ensure that",
"left. .. tip:: For tests on full data prior to release, `Nextflow Tower",
"step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml`",
"``test_full`` that should be edited to provide the links to full-size datasets. If",
"Exception as e: return {\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn, e)]}",
"python import os import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is",
"not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile test`",
"Must be turned on ``workflow_dispatch``. * Must be turned on for ``workflow_run`` with",
"the left. .. tip:: For tests on full data prior to release, `Nextflow",
"and it can be found in the ``.github/workflows/`` directory. .. warning:: This workflow",
"full size datasets on AWS. This should ensure that the pipeline runs as",
"on for published releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core",
"\"\"\"Checks the GitHub Actions awsfulltest is valid. In addition to small test datasets",
"hub release workflow) and ``workflow_dispatch``. .. note:: You can manually trigger the AWS",
"workflow on the left. .. tip:: For tests on full data prior to",
"wf = yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could not parse yaml",
"(release)\"]`` and ``types: [completed]`` * Should run the profile ``test_full`` that should be",
"# Warn if `-profile test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert",
"that the pipeline runs as expected on AWS and provide a resource estimation.",
"feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the following: *",
"runs as expected on AWS and provide a resource estimation. The GitHub Actions",
"`-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\") return {\"passed\":",
"triggered correctly\") # Warn if `-profile test` is still unchanged try: steps =",
"open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except Exception as e: return {\"failed\":",
"pipeline runs as expected on AWS and provide a resource estimation. The GitHub",
"import os import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid.",
"estimation. The GitHub Actions workflow is called ``awsfulltest.yml``, and it can be found",
"tab on the pipeline GitHub repository and selecting the `nf-core AWS full size",
"for the following: * Must be turned on ``workflow_dispatch``. * Must be turned",
"(AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\")",
"`Nextflow Tower <https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested",
"assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\"",
"os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except Exception as",
"yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could not parse yaml file: {},",
"can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the following: * Must",
"datasets run on GitHub Actions, we provide the possibility of testing the pipeline",
"is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step",
"the docker hub release workflow) and ``workflow_dispatch``. .. note:: You can manually trigger",
"= wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in steps if \"run\" in",
"links to full-size datasets. If it runs the profile ``test``, a warning is",
"tests by going to the `Actions` tab on the pipeline GitHub repository and",
"is only turned on for published releases try: assert \"workflow_run\" in wf[True] assert",
"repository and selecting the `nf-core AWS full size tests` workflow on the left.",
"# Check that the action is only turned on for published releases try:",
"= yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could not parse yaml file:",
"docker hub release workflow) and ``workflow_dispatch``. .. note:: You can manually trigger the",
"workflow) and ``workflow_dispatch``. .. note:: You can manually trigger the AWS tests by",
"of testing the pipeline on full size datasets on AWS. This should ensure",
"return {\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile",
"the profile ``test_full`` that should be edited to provide the links to full-size",
"Warn if `-profile test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile",
"aws_profile = \"-profile test \" # Check that the action is only turned",
"steps if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use",
"Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError,",
"Actions awsfulltest is valid. In addition to small test datasets run on GitHub",
"if `-profile test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in",
"* Should run the profile ``test_full`` that should be edited to provide the",
"triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile test` is",
"size datasets on AWS. This should ensure that the pipeline runs as expected",
"== [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True]",
"to full-size datasets. If it runs the profile ``test``, a warning is given.",
"full data prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature can be employed.",
"If it runs the profile ``test``, a warning is given. \"\"\" passed =",
"{}, {}\".format(fn, e)]} aws_profile = \"-profile test \" # Check that the action",
"only turned on for published releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"]",
"the GitHub Actions awsfulltest is valid. In addition to small test datasets run",
"the following: * Must be turned on ``workflow_dispatch``. * Must be turned on",
"= \"-profile test \" # Check that the action is only turned on",
"Must be turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and",
"assert any([aws_profile in step[\"run\"] for step in steps if \"run\" in step.keys()]) except",
"launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the following:",
"tests` workflow on the left. .. tip:: For tests on full data prior",
"``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]`` * Should run the profile",
"found in the ``.github/workflows/`` directory. .. warning:: This workflow incurs AWS costs, therefore",
"parse yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test \" # Check",
"run on GitHub Actions, we provide the possibility of testing the pipeline on",
"with open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except Exception as e: return",
"to the `Actions` tab on the pipeline GitHub repository and selecting the `nf-core",
"file is tested for the following: * Must be turned on ``workflow_dispatch``. *",
"= os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as fh:",
"assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\")",
"failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if",
"[] warned = [] failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\")",
"should only be triggered for pipeline releases: ``workflow_run`` (after the docker hub release",
"{}\".format(fn, e)]} aws_profile = \"-profile test \" # Check that the action is",
"* Must be turned on ``workflow_dispatch``. * Must be turned on for ``workflow_run``",
"does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile",
"small test datasets run on GitHub Actions, we provide the possibility of testing",
"only be triggered for pipeline releases: ``workflow_run`` (after the docker hub release workflow)",
"push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError,",
"for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]`` * Should",
"be found in the ``.github/workflows/`` directory. .. warning:: This workflow incurs AWS costs,",
"Actions, we provide the possibility of testing the pipeline on full size datasets",
"tests on full data prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature can",
"resource estimation. The GitHub Actions workflow is called ``awsfulltest.yml``, and it can be",
"``test``, a warning is given. \"\"\" passed = [] warned = [] failed",
"os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf",
"valid. In addition to small test datasets run on GitHub Actions, we provide",
"os import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid. In",
"`-profile test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"]",
"AWS and provide a resource estimation. The GitHub Actions workflow is called ``awsfulltest.yml``,",
"step in steps if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does",
"warning:: This workflow incurs AWS costs, therefore it should only be triggered for",
"that the action is only turned on for published releases try: assert \"workflow_run\"",
"\"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert wf[True][\"workflow_run\"][\"types\"] ==",
"AWS costs, therefore it should only be triggered for pipeline releases: ``workflow_run`` (after",
"correctly\") # Warn if `-profile test` is still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"]",
"KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full",
"turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types: [completed]``",
"still unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in",
"published releases try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push",
"* Must be turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]``",
"test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\") return {\"passed\": passed,",
"incurs AWS costs, therefore it should only be triggered for pipeline releases: ``workflow_run``",
"and ``workflow_dispatch``. .. note:: You can manually trigger the AWS tests by going",
"{\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test",
"step[\"run\"] for step in steps if \"run\" in step.keys()]) except (AssertionError, KeyError, TypeError):",
"on the pipeline GitHub repository and selecting the `nf-core AWS full size tests`",
"to release, `Nextflow Tower <https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml`` file",
"as e: return {\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn, e)]} aws_profile",
"on AWS. This should ensure that the pipeline runs as expected on AWS",
"awsfulltest is valid. In addition to small test datasets run on GitHub Actions,",
"can manually trigger the AWS tests by going to the `Actions` tab on",
"warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\") return {\"passed\": passed, \"warned\": warned,",
"try: with open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except Exception as e:",
"\"\"\" passed = [] warned = [] failed = [] fn = os.path.join(self.wf_path,",
"\"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else:",
"on full size datasets on AWS. This should ensure that the pipeline runs",
"be employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the following: * Must be",
"datasets. If it runs the profile ``test``, a warning is given. \"\"\" passed",
"not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\")",
"``awsfulltest.yml``, and it can be found in the ``.github/workflows/`` directory. .. warning:: This",
"wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is",
"This workflow incurs AWS costs, therefore it should only be triggered for pipeline",
"for pipeline releases: ``workflow_run`` (after the docker hub release workflow) and ``workflow_dispatch``. ..",
"test \" # Check that the action is only turned on for published",
"profile ``test_full`` that should be edited to provide the links to full-size datasets.",
"try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in steps if",
"[] failed = [] fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try:",
"import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions awsfulltest is valid. In addition",
"in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml`",
"run the profile ``test_full`` that should be edited to provide the links to",
"and provide a resource estimation. The GitHub Actions workflow is called ``awsfulltest.yml``, and",
"else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets, not `-profile test`\") return {\"passed\": passed, \"warned\":",
"assert wf[True][\"workflow_run\"][\"types\"] == [\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml`",
"AWS. This should ensure that the pipeline runs as expected on AWS and",
"the action is only turned on for published releases try: assert \"workflow_run\" in",
"the profile ``test``, a warning is given. \"\"\" passed = [] warned =",
"``workflow_dispatch``. .. note:: You can manually trigger the AWS tests by going to",
"tip:: For tests on full data prior to release, `Nextflow Tower <https://tower.nf>`_ launch",
"edited to provide the links to full-size datasets. If it runs the profile",
"The GitHub Actions workflow is called ``awsfulltest.yml``, and it can be found in",
"if os.path.isfile(fn): try: with open(fn, \"r\") as fh: wf = yaml.safe_load(fh) except Exception",
"\" # Check that the action is only turned on for published releases",
"manually trigger the AWS tests by going to the `Actions` tab on the",
"profile ``test``, a warning is given. \"\"\" passed = [] warned = []",
"unchanged try: steps = wf[\"jobs\"][\"run-awstest\"][\"steps\"] assert any([aws_profile in step[\"run\"] for step in steps",
"on GitHub Actions, we provide the possibility of testing the pipeline on full",
"GitHub Actions, we provide the possibility of testing the pipeline on full size",
"`Actions` tab on the pipeline GitHub repository and selecting the `nf-core AWS full",
"try: assert \"workflow_run\" in wf[True] assert wf[True][\"workflow_run\"][\"workflows\"] == [\"nf-core Docker push (release)\"] assert",
"in step[\"run\"] for step in steps if \"run\" in step.keys()]) except (AssertionError, KeyError,",
"called ``awsfulltest.yml``, and it can be found in the ``.github/workflows/`` directory. .. warning::",
"the pipeline on full size datasets on AWS. This should ensure that the",
"AWS full size tests` workflow on the left. .. tip:: For tests on",
"trigger the AWS tests by going to the `Actions` tab on the pipeline",
"fn = os.path.join(self.wf_path, \".github\", \"workflows\", \"awsfulltest.yml\") if os.path.isfile(fn): try: with open(fn, \"r\") as",
"is given. \"\"\" passed = [] warned = [] failed = [] fn",
"is valid. In addition to small test datasets run on GitHub Actions, we",
"wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is",
"going to the `Actions` tab on the pipeline GitHub repository and selecting the",
"[completed]`` * Should run the profile ``test_full`` that should be edited to provide",
"expected on AWS and provide a resource estimation. The GitHub Actions workflow is",
"provide the possibility of testing the pipeline on full size datasets on AWS.",
"AWS tests by going to the `Actions` tab on the pipeline GitHub repository",
"on the left. .. tip:: For tests on full data prior to release,",
"TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered correctly\") else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn",
"it runs the profile ``test``, a warning is given. \"\"\" passed = []",
"passed = [] warned = [] failed = [] fn = os.path.join(self.wf_path, \".github\",",
"yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test \" # Check that",
"the links to full-size datasets. If it runs the profile ``test``, a warning",
"be edited to provide the links to full-size datasets. If it runs the",
"size tests` workflow on the left. .. tip:: For tests on full data",
"action is only turned on for published releases try: assert \"workflow_run\" in wf[True]",
"costs, therefore it should only be triggered for pipeline releases: ``workflow_run`` (after the",
"e: return {\"failed\": [\"Could not parse yaml file: {}, {}\".format(fn, e)]} aws_profile =",
"TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else: warned.append(\"`.github/workflows/awsfulltest.yml` should test full datasets,",
"GitHub repository and selecting the `nf-core AWS full size tests` workflow on the",
"on full data prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature can be",
"Docker push (release)\"]`` and ``types: [completed]`` * Should run the profile ``test_full`` that",
"[\"nf-core Docker push (release)\"]`` and ``types: [completed]`` * Should run the profile ``test_full``",
"prior to release, `Nextflow Tower <https://tower.nf>`_ launch feature can be employed. The ``.github/workflows/awsfulltest.yml``",
"[\"Could not parse yaml file: {}, {}\".format(fn, e)]} aws_profile = \"-profile test \"",
"the `nf-core AWS full size tests` workflow on the left. .. tip:: For",
"in step.keys()]) except (AssertionError, KeyError, TypeError): passed.append(\"`.github/workflows/awsfulltest.yml` does not use `-profile test`\") else:",
"`nf-core AWS full size tests` workflow on the left. .. tip:: For tests",
"employed. The ``.github/workflows/awsfulltest.yml`` file is tested for the following: * Must be turned",
"fh: wf = yaml.safe_load(fh) except Exception as e: return {\"failed\": [\"Could not parse",
"be turned on for ``workflow_run`` with ``workflows: [\"nf-core Docker push (release)\"]`` and ``types:",
"[\"completed\"] assert \"workflow_dispatch\" in wf[True] except (AssertionError, KeyError, TypeError): failed.append(\"`.github/workflows/awsfulltest.yml` is not triggered",
"possibility of testing the pipeline on full size datasets on AWS. This should",
"<filename>nf_core/lint/actions_awsfulltest.py<gh_stars>0 #!/usr/bin/env python import os import yaml def actions_awsfulltest(self): \"\"\"Checks the GitHub Actions",
"the AWS tests by going to the `Actions` tab on the pipeline GitHub",
"else: passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile test` is still unchanged",
"is called ``awsfulltest.yml``, and it can be found in the ``.github/workflows/`` directory. ..",
"passed.append(\"`.github/workflows/awsfulltest.yml` is triggered correctly\") # Warn if `-profile test` is still unchanged try:",
"should ensure that the pipeline runs as expected on AWS and provide a"
] |
[
"Wait for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process",
"end of scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield process finally: #",
"Inc. and its affiliates. # # This source code is licensed under the",
"(c) Facebook, Inc. and its affiliates. # # This source code is licensed",
"= f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job failed with returncode",
"0): process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=timeout) except",
"# Process has not yet terminated, kill it. if process.poll() is None: #",
"'.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills",
"terminated, kill it. if process.poll() is None: # kill() was added in Python",
"7, 0): process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=timeout)",
"if process.poll() is None: # kill() was added in Python 3.7. if sys.version_info",
"process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired:",
"on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in",
"process: try: yield process finally: # Process has not yet terminated, kill it.",
"signal. Signal returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass",
"pass # Stubborn process won't die, nothing can be done. raise @contextmanager def",
"= process.returncode try: # Try and decode the name of a signal. Signal",
"in the root directory of this source tree. import subprocess import sys from",
"def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at end of scope.\"\"\" with",
"@contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at end of scope.\"\"\"",
"as process: try: yield process finally: # Process has not yet terminated, kill",
"# Try and decode the name of a signal. Signal returncodes # are",
"its affiliates. # # This source code is licensed under the MIT license",
"and its affiliates. # # This source code is licensed under the MIT",
">= (3, 7, 0): process.kill() else: process.terminate() # Wait for shutdown to complete.",
"was added in Python 3.7. if sys.version_info >= (3, 7, 0): process.kill() else:",
"of scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield process finally: # Process",
"nothing can be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process",
"This source code is licensed under the MIT license found in the #",
"f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job failed with returncode {returncode}\\n\"",
"contextmanager from signal import Signals from subprocess import Popen as _Popen from typing",
"are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job",
"complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can",
"# # This source code is licensed under the MIT license found in",
"process termination at end of scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield",
"license found in the # LICENSE file in the root directory of this",
"Try and decode the name of a signal. Signal returncodes # are negative.",
"of this source tree. import subprocess import sys from contextlib import contextmanager from",
"# LICENSE file in the root directory of this source tree. import subprocess",
"signal import Signals from subprocess import Popen as _Popen from typing import List",
"f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess",
"be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at",
"negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job failed",
"except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be done. raise",
"Stubborn process won't die, nothing can be done. raise @contextmanager def Popen(*args, **kwargs):",
"try: yield process finally: # Process has not yet terminated, kill it. if",
"def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input,",
"communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout)",
"found in the # LICENSE file in the root directory of this source",
"\"\"\"subprocess.Popen() with resilient process termination at end of scope.\"\"\" with _Popen(*args, **kwargs) as",
"as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: #",
"Copyright (c) Facebook, Inc. and its affiliates. # # This source code is",
"# are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation",
"except subprocess.TimeoutExpired: # kill() was added in Python 3.7. if sys.version_info >= (3,",
") as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try:",
"stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: # Try and decode",
"to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing",
"with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout)",
"LICENSE file in the root directory of this source tree. import subprocess import",
"yield process finally: # Process has not yet terminated, kill it. if process.poll()",
"process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be done.",
"int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr =",
"process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: # Try and decode the name",
"licensed under the MIT license found in the # LICENSE file in the",
"added in Python 3.7. if sys.version_info >= (3, 7, 0): process.kill() else: process.terminate()",
"returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job failed with",
"Popen as _Popen from typing import List def run_command(cmd: List[str], timeout: int): with",
"name of a signal. Signal returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\"",
"returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None,",
") return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\"",
"process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass #",
"raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at end of",
"Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at end of scope.\"\"\" with _Popen(*args,",
"({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command:",
"subprocess.TimeoutExpired: # kill() was added in Python 3.7. if sys.version_info >= (3, 7,",
"process won't die, nothing can be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen()",
"shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't die,",
"try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be",
"at end of scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield process finally:",
"Python 3.7. if sys.version_info >= (3, 7, 0): process.kill() else: process.terminate() # Wait",
"it. if process.poll() is None: # kill() was added in Python 3.7. if",
"# Copyright (c) Facebook, Inc. and its affiliates. # # This source code",
"decode the name of a signal. Signal returncodes # are negative. returncode =",
"subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be done. raise @contextmanager",
"MIT license found in the # LICENSE file in the root directory of",
"process.returncode try: # Try and decode the name of a signal. Signal returncodes",
"Wait for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process",
"with resilient process termination at end of scope.\"\"\" with _Popen(*args, **kwargs) as process:",
"return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python 3.7. if",
"def run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as",
"stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return",
"List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout,",
"stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode",
"timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python",
"if sys.version_info >= (3, 7, 0): process.kill() else: process.terminate() # Wait for shutdown",
"process.poll() is None: # kill() was added in Python 3.7. if sys.version_info >=",
"Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout) if",
"of a signal. Signal returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except",
"finally: # Process has not yet terminated, kill it. if process.poll() is None:",
"List def run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True )",
"if process.returncode: returncode = process.returncode try: # Try and decode the name of",
"for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't",
"shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't die,",
"Signals from subprocess import Popen as _Popen from typing import List def run_command(cmd:",
"try: # Try and decode the name of a signal. Signal returncodes #",
"ValueError: pass raise OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\"",
"the name of a signal. Signal returncodes # are negative. returncode = f\"{returncode}",
"stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: # Try and",
"this source tree. import subprocess import sys from contextlib import contextmanager from signal",
"raise OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\"",
"process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be done.",
"(3, 7, 0): process.kill() else: process.terminate() # Wait for shutdown to complete. try:",
"in the # LICENSE file in the root directory of this source tree.",
"is None: # kill() was added in Python 3.7. if sys.version_info >= (3,",
"typing import List def run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,",
"has not yet terminated, kill it. if process.poll() is None: # kill() was",
"termination at end of scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield process",
"{stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on",
"timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr",
"sys from contextlib import contextmanager from signal import Signals from subprocess import Popen",
"process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired:",
"run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process:",
"won't die, nothing can be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with",
"subprocess import Popen as _Popen from typing import List def run_command(cmd: List[str], timeout:",
"under the MIT license found in the # LICENSE file in the root",
"import subprocess import sys from contextlib import contextmanager from signal import Signals from",
"Facebook, Inc. and its affiliates. # # This source code is licensed under",
"from typing import List def run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE,",
"affiliates. # # This source code is licensed under the MIT license found",
"stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode =",
"can be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination",
"# Stubborn process won't die, nothing can be done. raise @contextmanager def Popen(*args,",
"returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise OSError(",
"not yet terminated, kill it. if process.poll() is None: # kill() was added",
"OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" )",
"which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill()",
"try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can be",
"with _Popen(*args, **kwargs) as process: try: yield process finally: # Process has not",
"0): process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=60) except",
"root directory of this source tree. import subprocess import sys from contextlib import",
"the MIT license found in the # LICENSE file in the root directory",
"_Popen from typing import List def run_command(cmd: List[str], timeout: int): with Popen( cmd,",
"done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient process termination at end",
"import List def run_command(cmd: List[str], timeout: int): with Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True",
"# Wait for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn",
"pass raise OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr:",
"import Popen as _Popen from typing import List def run_command(cmd: List[str], timeout: int):",
"f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return",
"resilient process termination at end of scope.\"\"\" with _Popen(*args, **kwargs) as process: try:",
"**kwargs) as process: try: yield process finally: # Process has not yet terminated,",
"else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass",
"process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python 3.7. if sys.version_info",
"in Python 3.7. if sys.version_info >= (3, 7, 0): process.kill() else: process.terminate() #",
"file in the root directory of this source tree. import subprocess import sys",
"code is licensed under the MIT license found in the # LICENSE file",
"and decode the name of a signal. Signal returncodes # are negative. returncode",
"timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python 3.7. if sys.version_info >=",
"is licensed under the MIT license found in the # LICENSE file in",
"process finally: # Process has not yet terminated, kill it. if process.poll() is",
"subprocess import sys from contextlib import contextmanager from signal import Signals from subprocess",
"contextlib import contextmanager from signal import Signals from subprocess import Popen as _Popen",
"3.7. if sys.version_info >= (3, 7, 0): process.kill() else: process.terminate() # Wait for",
"Signal returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError: pass raise",
"for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't",
"kill it. if process.poll() is None: # kill() was added in Python 3.7.",
"a signal. Signal returncodes # are negative. returncode = f\"{returncode} ({Signals(abs(returncode)).name})\" except ValueError:",
"source code is licensed under the MIT license found in the # LICENSE",
"returncode = process.returncode try: # Try and decode the name of a signal.",
"sys.version_info >= (3, 7, 0): process.kill() else: process.terminate() # Wait for shutdown to",
"the # LICENSE file in the root directory of this source tree. import",
"# Wait for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn",
"_Popen(*args, **kwargs) as process: try: yield process finally: # Process has not yet",
"except ValueError: pass raise OSError( f\"Compilation job failed with returncode {returncode}\\n\" f\"Command: {'",
"with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process,",
"the root directory of this source tree. import subprocess import sys from contextlib",
"import contextmanager from signal import Signals from subprocess import Popen as _Popen from",
"cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode:",
"process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: # Try",
"tree. import subprocess import sys from contextlib import contextmanager from signal import Signals",
"Process has not yet terminated, kill it. if process.poll() is None: # kill()",
"{returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None):",
"from subprocess import Popen as _Popen from typing import List def run_command(cmd: List[str],",
"f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate()",
"kill() was added in Python 3.7. if sys.version_info >= (3, 7, 0): process.kill()",
"input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except",
"complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing can",
"process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=60) except subprocess.TimeoutExpired: pass #",
"else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass",
"die, nothing can be done. raise @contextmanager def Popen(*args, **kwargs): \"\"\"subprocess.Popen() with resilient",
"timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired:",
"**kwargs): \"\"\"subprocess.Popen() with resilient process termination at end of scope.\"\"\" with _Popen(*args, **kwargs)",
"yet terminated, kill it. if process.poll() is None: # kill() was added in",
"try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python 3.7.",
"= process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode try: # Try and decode the",
"process.returncode: returncode = process.returncode try: # Try and decode the name of a",
"# kill() was added in Python 3.7. if sys.version_info >= (3, 7, 0):",
"universal_newlines=True ) as process: stdout, stderr = process.communicate(timeout=timeout) if process.returncode: returncode = process.returncode",
"scope.\"\"\" with _Popen(*args, **kwargs) as process: try: yield process finally: # Process has",
"to complete. try: process.communicate(timeout=timeout) except subprocess.TimeoutExpired: pass # Stubborn process won't die, nothing",
"\"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: #",
"source tree. import subprocess import sys from contextlib import contextmanager from signal import",
"failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def",
"None: # kill() was added in Python 3.7. if sys.version_info >= (3, 7,",
"job failed with returncode {returncode}\\n\" f\"Command: {' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout",
"kills subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was",
"7, 0): process.kill() else: process.terminate() # Wait for shutdown to complete. try: process.communicate(timeout=60)",
"# This source code is licensed under the MIT license found in the",
"as _Popen from typing import List def run_command(cmd: List[str], timeout: int): with Popen(",
"subprocess on timeout.\"\"\" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added",
"import sys from contextlib import contextmanager from signal import Signals from subprocess import",
"import Signals from subprocess import Popen as _Popen from typing import List def",
"{' '.join(cmd)}\\n\" f\"Stderr: {stderr.strip()}\" ) return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which",
"from signal import Signals from subprocess import Popen as _Popen from typing import",
"from contextlib import contextmanager from signal import Signals from subprocess import Popen as",
"return stdout def communicate(process, input=None, timeout=None): \"\"\"subprocess.communicate() which kills subprocess on timeout.\"\"\" try:",
"directory of this source tree. import subprocess import sys from contextlib import contextmanager"
] |
[
"return f'<Task: {self._func.__name__} not yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled to",
"None def __str__(self): if not self._interval: return f'<Task: {self._func.__name__} not yet scheduled to",
"every X units! (e.g. every 30 seconds) :param int,float value: Interval :param str",
"60 self._interval = seconds self._next_run = time.monotonic() + self._interval return self def run(self):",
"unit == storm_scheduler.HOURS: seconds += seconds * 60 * 60 elif unit ==",
"self._interval return self def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args,",
"\"\"\"Are we ready to run again?\"\"\" return self.next_run <= 0 @property def next_run(self):",
"class Task: def __init__(self, func, *args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task",
"float') elif value <= 0: raise exception.TaskError('Interval cannot be zero or negative') elif",
"elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list of",
"we ready to run again?\"\"\" return self.next_run <= 0 @property def next_run(self): \"\"\"Time",
"a task every X units! (e.g. every 30 seconds) :param int,float value: Interval",
"{self._func.__name__} not yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled to run every",
"should_run(self): \"\"\"Are we ready to run again?\"\"\" return self.next_run <= 0 @property def",
"= str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES: seconds += seconds *",
"seconds) :param int,float value: Interval :param str unit: Time unit (e.g. seconds, minutes,",
"import Callable import storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__) class Task:",
"<filename>storm_scheduler/task.py import logging import time from typing import Callable import storm_scheduler from storm_scheduler",
"def should_run(self): \"\"\"Are we ready to run again?\"\"\" return self.next_run <= 0 @property",
"in the list of supported time units\") unit = str(unit).lower() seconds = value",
"def __init__(self, func, *args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function needs",
"needs to be an integer or float') elif value <= 0: raise exception.TaskError('Interval",
":param int,float value: Interval :param str unit: Time unit (e.g. seconds, minutes, hours,",
"60 * 60 self._interval = seconds self._next_run = time.monotonic() + self._interval return self",
"return self def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs)",
"args self._kwargs = kwargs self._interval = None self._next_run = None self.last_runtime = None",
"0.01) self._next_run = time.monotonic() + interval @property def should_run(self): \"\"\"Are we ready to",
"run again?\"\"\" return self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining until next",
"logging import time from typing import Callable import storm_scheduler from storm_scheduler import exception",
"to be an integer or float') elif value <= 0: raise exception.TaskError('Interval cannot",
"exception.TaskError('Interval cannot be zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit",
"storm_scheduler.MINUTES: seconds += seconds * 60 elif unit == storm_scheduler.HOURS: seconds += seconds",
"to run again?\"\"\" return self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining until",
"<= 0: raise exception.TaskError('Interval cannot be zero or negative') elif unit not in",
"an integer or float') elif value <= 0: raise exception.TaskError('Interval cannot be zero",
"start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}')",
"storm_scheduler import exception LOG = logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs):",
"be zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not",
"time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime",
"start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property",
"{self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task every X units! (e.g. every",
"TaskError: This is raised when there is an issue with the Task. \"\"\"",
"in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list of supported time units\")",
"+= seconds * 60 * 60 * 60 self._interval = seconds self._next_run =",
"Callable import storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__) class Task: def",
"from storm_scheduler import exception LOG = logging.getLogger(__name__) class Task: def __init__(self, func, *args,",
"Callable): raise exception.TaskError('Task function needs to be callable') self._func = func self._args =",
"every(self, value, unit='seconds'): \"\"\"Run a task every X units! (e.g. every 30 seconds)",
"unit = str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES: seconds += seconds",
"to run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task every X",
"the Task. \"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to",
"of supported time units\") unit = str(unit).lower() seconds = value if unit ==",
"why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() - start_time interval = max(self._interval",
"def every(self, value, unit='seconds'): \"\"\"Run a task every X units! (e.g. every 30",
"seconds += seconds * 60 elif unit == storm_scheduler.HOURS: seconds += seconds *",
"* 60 elif unit == storm_scheduler.DAYS: seconds += seconds * 60 * 60",
"time.monotonic() - start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() +",
"raise exception.TaskError('Interval cannot be zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise",
"seconds += seconds * 60 * 60 elif unit == storm_scheduler.DAYS: seconds +=",
"LOG = logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs): if not isinstance(func,",
"is raised when there is an issue with the Task. \"\"\" if not",
"= max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property def should_run(self):",
"the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task",
"logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs): if not isinstance(func, Callable): raise",
"unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list of supported",
"cannot be zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}'",
"zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in",
"elif unit == storm_scheduler.HOURS: seconds += seconds * 60 * 60 elif unit",
"Task: def __init__(self, func, *args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function",
"Time unit (e.g. seconds, minutes, hours, days) :raises TaskError: This is raised when",
"is an issue with the Task. \"\"\" if not isinstance(value, (int, float)): raise",
"+= seconds * 60 * 60 elif unit == storm_scheduler.DAYS: seconds += seconds",
"if not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to be an integer",
"not isinstance(func, Callable): raise exception.TaskError('Task function needs to be callable') self._func = func",
"every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task every X units! (e.g.",
"run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task every X units!",
"units! (e.g. every 30 seconds) :param int,float value: Interval :param str unit: Time",
"func self._args = args self._kwargs = kwargs self._interval = None self._next_run = None",
"= seconds self._next_run = time.monotonic() + self._interval return self def run(self): \"\"\"Execute the",
"\"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why:",
"Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error:",
"not self._interval: return f'<Task: {self._func.__name__} not yet scheduled to run>' return f'<Task: {self._func.__name__}",
"== storm_scheduler.DAYS: seconds += seconds * 60 * 60 * 60 self._interval =",
"time units\") unit = str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES: seconds",
"self def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except",
"hours, days) :raises TaskError: This is raised when there is an issue with",
"**kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function needs to be callable') self._func",
"60 * 60 * 60 self._interval = seconds self._next_run = time.monotonic() + self._interval",
"be callable') self._func = func self._args = args self._kwargs = kwargs self._interval =",
"scheduled to run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task every",
"value, unit='seconds'): \"\"\"Run a task every X units! (e.g. every 30 seconds) :param",
"None self.last_runtime = None def __str__(self): if not self._interval: return f'<Task: {self._func.__name__} not",
"= value if unit == storm_scheduler.MINUTES: seconds += seconds * 60 elif unit",
"typing import Callable import storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__) class",
"self._next_run = time.monotonic() + interval @property def should_run(self): \"\"\"Are we ready to run",
"exception.TaskError('Task interval needs to be an integer or float') elif value <= 0:",
"self._func = func self._args = args self._kwargs = kwargs self._interval = None self._next_run",
"import exception LOG = logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs): if",
"with the Task. \"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs",
"raise exception.TaskError('Task interval needs to be an integer or float') elif value <=",
"Task. \"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to be",
"self._interval = seconds self._next_run = time.monotonic() + self._interval return self def run(self): \"\"\"Execute",
"self._args = args self._kwargs = kwargs self._interval = None self._next_run = None self.last_runtime",
"not yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>'",
"try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime =",
"raised when there is an issue with the Task. \"\"\" if not isinstance(value,",
"\"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to be an",
"storm_scheduler.DAYS: seconds += seconds * 60 * 60 * 60 self._interval = seconds",
"* 60 self._interval = seconds self._next_run = time.monotonic() + self._interval return self def",
"time from typing import Callable import storm_scheduler from storm_scheduler import exception LOG =",
"= time.monotonic() + self._interval return self def run(self): \"\"\"Execute the Task.\"\"\" start_time =",
"self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining until next run.\"\"\" return self._next_run",
"def __str__(self): if not self._interval: return f'<Task: {self._func.__name__} not yet scheduled to run>'",
"there is an issue with the Task. \"\"\" if not isinstance(value, (int, float)):",
"raise exception.TaskError('Task function needs to be callable') self._func = func self._args = args",
"task every X units! (e.g. every 30 seconds) :param int,float value: Interval :param",
"except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() - start_time",
"yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def",
"= logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs): if not isinstance(func, Callable):",
"LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() - start_time interval = max(self._interval -",
"- self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property def should_run(self): \"\"\"Are we",
"@property def should_run(self): \"\"\"Are we ready to run again?\"\"\" return self.next_run <= 0",
"self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property def should_run(self): \"\"\"Are we ready",
"callable') self._func = func self._args = args self._kwargs = kwargs self._interval = None",
"+ self._interval return self def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try:",
"self._interval = None self._next_run = None self.last_runtime = None def __str__(self): if not",
"30 seconds) :param int,float value: Interval :param str unit: Time unit (e.g. seconds,",
"exception LOG = logging.getLogger(__name__) class Task: def __init__(self, func, *args, **kwargs): if not",
"minutes, hours, days) :raises TaskError: This is raised when there is an issue",
"* 60 * 60 elif unit == storm_scheduler.DAYS: seconds += seconds * 60",
"{self._func.__name__} scheduled to run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a task",
"+= seconds * 60 elif unit == storm_scheduler.HOURS: seconds += seconds * 60",
"__init__(self, func, *args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function needs to",
"value <= 0: raise exception.TaskError('Interval cannot be zero or negative') elif unit not",
"60 elif unit == storm_scheduler.HOURS: seconds += seconds * 60 * 60 elif",
"run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as",
"if not isinstance(func, Callable): raise exception.TaskError('Task function needs to be callable') self._func =",
"unit='seconds'): \"\"\"Run a task every X units! (e.g. every 30 seconds) :param int,float",
"be an integer or float') elif value <= 0: raise exception.TaskError('Interval cannot be",
"supported time units\") unit = str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES:",
"seconds = value if unit == storm_scheduler.MINUTES: seconds += seconds * 60 elif",
"def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError",
"Interval :param str unit: Time unit (e.g. seconds, minutes, hours, days) :raises TaskError:",
"= time.monotonic() try: self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally:",
"finally: self.last_runtime = time.monotonic() - start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run",
"(e.g. every 30 seconds) :param int,float value: Interval :param str unit: Time unit",
"every 30 seconds) :param int,float value: Interval :param str unit: Time unit (e.g.",
"seconds += seconds * 60 * 60 * 60 self._interval = seconds self._next_run",
"- start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() + interval",
"X units! (e.g. every 30 seconds) :param int,float value: Interval :param str unit:",
"seconds self._next_run = time.monotonic() + self._interval return self def run(self): \"\"\"Execute the Task.\"\"\"",
"time.monotonic() + interval @property def should_run(self): \"\"\"Are we ready to run again?\"\"\" return",
"None self._next_run = None self.last_runtime = None def __str__(self): if not self._interval: return",
"as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() - start_time interval =",
"exception.TaskError('Task function needs to be callable') self._func = func self._args = args self._kwargs",
"str unit: Time unit (e.g. seconds, minutes, hours, days) :raises TaskError: This is",
"60 elif unit == storm_scheduler.DAYS: seconds += seconds * 60 * 60 *",
"Error: {why}') finally: self.last_runtime = time.monotonic() - start_time interval = max(self._interval - self.last_runtime,",
"str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES: seconds += seconds * 60",
"max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property def should_run(self): \"\"\"Are",
"func, *args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function needs to be",
"units\") unit = str(unit).lower() seconds = value if unit == storm_scheduler.MINUTES: seconds +=",
"self._next_run = time.monotonic() + self._interval return self def run(self): \"\"\"Execute the Task.\"\"\" start_time",
"isinstance(func, Callable): raise exception.TaskError('Task function needs to be callable') self._func = func self._args",
":param str unit: Time unit (e.g. seconds, minutes, hours, days) :raises TaskError: This",
"storm_scheduler.HOURS: seconds += seconds * 60 * 60 elif unit == storm_scheduler.DAYS: seconds",
"interval @property def should_run(self): \"\"\"Are we ready to run again?\"\"\" return self.next_run <=",
"function needs to be callable') self._func = func self._args = args self._kwargs =",
"interval needs to be an integer or float') elif value <= 0: raise",
"storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__) class Task: def __init__(self, func,",
"seconds * 60 * 60 * 60 self._interval = seconds self._next_run = time.monotonic()",
"return self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining until next run.\"\"\" return",
"(int, float)): raise exception.TaskError('Task interval needs to be an integer or float') elif",
"value if unit == storm_scheduler.MINUTES: seconds += seconds * 60 elif unit ==",
"\"\"\"Run a task every X units! (e.g. every 30 seconds) :param int,float value:",
"integer or float') elif value <= 0: raise exception.TaskError('Interval cannot be zero or",
"needs to be callable') self._func = func self._args = args self._kwargs = kwargs",
"self._kwargs = kwargs self._interval = None self._next_run = None self.last_runtime = None def",
"elif value <= 0: raise exception.TaskError('Interval cannot be zero or negative') elif unit",
"run>' return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def every(self, value, unit='seconds'):",
"= None self._next_run = None self.last_runtime = None def __str__(self): if not self._interval:",
"negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list",
"= None self.last_runtime = None def __str__(self): if not self._interval: return f'<Task: {self._func.__name__}",
"storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list of supported time units\") unit",
"**self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() -",
"list of supported time units\") unit = str(unit).lower() seconds = value if unit",
"self.last_runtime = time.monotonic() - start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run =",
"unit == storm_scheduler.DAYS: seconds += seconds * 60 * 60 * 60 self._interval",
"import time from typing import Callable import storm_scheduler from storm_scheduler import exception LOG",
"self._func(*self._args, **self._kwargs) except exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic()",
"self._next_run = None self.last_runtime = None def __str__(self): if not self._interval: return f'<Task:",
"return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run",
"the list of supported time units\") unit = str(unit).lower() seconds = value if",
"'{unit}' not in the list of supported time units\") unit = str(unit).lower() seconds",
"from typing import Callable import storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__)",
"f'<Task: {self._func.__name__} not yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled to run",
"unit (e.g. seconds, minutes, hours, days) :raises TaskError: This is raised when there",
"if unit == storm_scheduler.MINUTES: seconds += seconds * 60 elif unit == storm_scheduler.HOURS:",
"{why}') finally: self.last_runtime = time.monotonic() - start_time interval = max(self._interval - self.last_runtime, 0.01)",
"seconds, minutes, hours, days) :raises TaskError: This is raised when there is an",
"* 60 * 60 self._interval = seconds self._next_run = time.monotonic() + self._interval return",
"or float') elif value <= 0: raise exception.TaskError('Interval cannot be zero or negative')",
"seconds * 60 elif unit == storm_scheduler.HOURS: seconds += seconds * 60 *",
"when there is an issue with the Task. \"\"\" if not isinstance(value, (int,",
"60 * 60 elif unit == storm_scheduler.DAYS: seconds += seconds * 60 *",
"not isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to be an integer or",
"*args, **kwargs): if not isinstance(func, Callable): raise exception.TaskError('Task function needs to be callable')",
"+ interval @property def should_run(self): \"\"\"Are we ready to run again?\"\"\" return self.next_run",
"exception.TaskError as why: LOG.warning(f'Task Error: {why}') finally: self.last_runtime = time.monotonic() - start_time interval",
":raises TaskError: This is raised when there is an issue with the Task.",
"unit: Time unit (e.g. seconds, minutes, hours, days) :raises TaskError: This is raised",
"* 60 elif unit == storm_scheduler.HOURS: seconds += seconds * 60 * 60",
"<= 0 @property def next_run(self): \"\"\"Time remaining until next run.\"\"\" return self._next_run -",
"= time.monotonic() + interval @property def should_run(self): \"\"\"Are we ready to run again?\"\"\"",
"= args self._kwargs = kwargs self._interval = None self._next_run = None self.last_runtime =",
"not in the list of supported time units\") unit = str(unit).lower() seconds =",
"time.monotonic() + self._interval return self def run(self): \"\"\"Execute the Task.\"\"\" start_time = time.monotonic()",
"self.last_runtime = None def __str__(self): if not self._interval: return f'<Task: {self._func.__name__} not yet",
"0 @property def next_run(self): \"\"\"Time remaining until next run.\"\"\" return self._next_run - time.monotonic()",
"__str__(self): if not self._interval: return f'<Task: {self._func.__name__} not yet scheduled to run>' return",
"again?\"\"\" return self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining until next run.\"\"\"",
"int,float value: Interval :param str unit: Time unit (e.g. seconds, minutes, hours, days)",
"This is raised when there is an issue with the Task. \"\"\" if",
"issue with the Task. \"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task interval",
"not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the list of supported time",
"== storm_scheduler.MINUTES: seconds += seconds * 60 elif unit == storm_scheduler.HOURS: seconds +=",
"elif unit == storm_scheduler.DAYS: seconds += seconds * 60 * 60 * 60",
"kwargs self._interval = None self._next_run = None self.last_runtime = None def __str__(self): if",
"to run>' return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def every(self, value,",
"== storm_scheduler.HOURS: seconds += seconds * 60 * 60 elif unit == storm_scheduler.DAYS:",
"(e.g. seconds, minutes, hours, days) :raises TaskError: This is raised when there is",
"seconds * 60 * 60 elif unit == storm_scheduler.DAYS: seconds += seconds *",
"* 60 * 60 * 60 self._interval = seconds self._next_run = time.monotonic() +",
"unit == storm_scheduler.MINUTES: seconds += seconds * 60 elif unit == storm_scheduler.HOURS: seconds",
"= kwargs self._interval = None self._next_run = None self.last_runtime = None def __str__(self):",
"self._interval: return f'<Task: {self._func.__name__} not yet scheduled to run>' return f'<Task: {self._func.__name__} scheduled",
"= time.monotonic() - start_time interval = max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic()",
"ready to run again?\"\"\" return self.next_run <= 0 @property def next_run(self): \"\"\"Time remaining",
"= None def __str__(self): if not self._interval: return f'<Task: {self._func.__name__} not yet scheduled",
"if not self._interval: return f'<Task: {self._func.__name__} not yet scheduled to run>' return f'<Task:",
"import logging import time from typing import Callable import storm_scheduler from storm_scheduler import",
"0: raise exception.TaskError('Interval cannot be zero or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS:",
"an issue with the Task. \"\"\" if not isinstance(value, (int, float)): raise exception.TaskError('Task",
"to be callable') self._func = func self._args = args self._kwargs = kwargs self._interval",
"interval = max(self._interval - self.last_runtime, 0.01) self._next_run = time.monotonic() + interval @property def",
"or negative') elif unit not in storm_scheduler.ALLOWED_TIME_UNITS: raise exception.TaskError(f\"Unit '{unit}' not in the",
"f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def every(self, value, unit='seconds'): \"\"\"Run a",
"isinstance(value, (int, float)): raise exception.TaskError('Task interval needs to be an integer or float')",
"value: Interval :param str unit: Time unit (e.g. seconds, minutes, hours, days) :raises",
"exception.TaskError(f\"Unit '{unit}' not in the list of supported time units\") unit = str(unit).lower()",
"float)): raise exception.TaskError('Task interval needs to be an integer or float') elif value",
"import storm_scheduler from storm_scheduler import exception LOG = logging.getLogger(__name__) class Task: def __init__(self,",
"days) :raises TaskError: This is raised when there is an issue with the",
"scheduled to run>' return f'<Task: {self._func.__name__} scheduled to run every {self._interval}s>' def every(self,",
"raise exception.TaskError(f\"Unit '{unit}' not in the list of supported time units\") unit =",
"= func self._args = args self._kwargs = kwargs self._interval = None self._next_run ="
] |
[
"tweepy import time from datetime import datetime from dateutil.parser import parse from pymongo",
"track): self.start_time = time.time() self.sec_limit = sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer()",
"class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit self.track",
"to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter",
"Parser # Parses Data and uploads to MongoDB import twitter_access import mongo_access from",
"user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city",
"self.sec_limit = sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def",
"mongo_access from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream",
"= city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\":",
"= pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x =",
"import twitter_access import mongo_access from tweepy.streaming import StreamListener from tweepy import OAuthHandler from",
"= db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time",
"import mongo_access from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import",
"self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"])",
"tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"]",
"= tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment =",
"Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit",
"Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages",
"self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0]",
"pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+',",
"self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x =",
"self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str =",
"import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd # Connect to",
"= client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def __init__(self,",
"longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count,",
"parse from pymongo import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer",
"time from datetime import datetime from dateutil.parser import parse from pymongo import MongoClient",
"import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import",
"= MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class class",
"datetime import datetime from dateutil.parser import parse from pymongo import MongoClient import os",
"= Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener)",
"x if (time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] ==",
"x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x if (time.time() - self.start_time)",
"db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def",
"= self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude =",
"< self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str",
"pandas as pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\")",
"= time.time() self.sec_limit = sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities =",
"tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment",
"self.start_time = time.time() self.sec_limit = sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities",
"tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude",
"twitter_access import mongo_access from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy",
"listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth,",
"= track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x):",
"import time from datetime import datetime from dateutil.parser import parse from pymongo import",
"from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import",
"return False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track)",
"= SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x = x.encode('ascii',",
"= tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city =",
"uploaded on MongoDB') return True else: print('End parsing.....') print('Time limit is reached') return",
"status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY)",
"import json import re import tweepy import time from datetime import datetime from",
"created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count",
"self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x",
"MongoDB import twitter_access import mongo_access from tweepy.streaming import StreamListener from tweepy import OAuthHandler",
"= {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj)",
"tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id",
"def on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '',",
"SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii')",
"track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream =",
"import SentimentIntensityAnalyzer import pandas as pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL)",
"json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text =",
"clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"]",
"from tweepy import OAuthHandler from tweepy import Stream import json import re import",
"is uploaded on MongoDB') return True else: print('End parsing.....') print('Time limit is reached')",
"text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count",
"as pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo",
"from tweepy import Stream import json import re import tweepy import time from",
"Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets #",
"Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit self.track =",
"clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x if",
"Parses Data and uploads to MongoDB import twitter_access import mongo_access from tweepy.streaming import",
"self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def",
"= tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id =",
"geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text,",
"from dateutil.parser import parse from pymongo import MongoClient import os import psycopg2 from",
"True else: print('End parsing.....') print('Time limit is reached') return False def on_error(self, status):",
"tweets_mongo = db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track):",
"is reached') return False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener =",
"on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY,",
"= tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text",
"from pymongo import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import",
"track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data): def clean_tweet(x): x",
"\"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True else:",
"import datetime from dateutil.parser import parse from pymongo import MongoClient import os import",
"re.sub(r'http\\S+', '', x) return x if (time.time() - self.start_time) < self.sec_limit: tweet =",
"sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude = city['Lng'].values[0]",
"def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x",
"def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth =",
"\"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True else: print('End parsing.....') print('Time",
"Twitter Parser # Parses Data and uploads to MongoDB import twitter_access import mongo_access",
"twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages = ['en'], track = track)",
"MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd",
"x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x if (time.time()",
"tweepy import Stream import json import re import tweepy import time from datetime",
"else: print('End parsing.....') print('Time limit is reached') return False def on_error(self, status): print(status)",
"import parse from pymongo import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import",
"# Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time()",
"# text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude",
"client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class",
"return True else: print('End parsing.....') print('Time limit is reached') return False def on_error(self,",
"tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text)",
"reached') return False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit,",
"import re import tweepy import time from datetime import datetime from dateutil.parser import",
"= tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user",
"sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self, data):",
"- self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at =",
"user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) #",
"= city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count,",
"longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True else: print('End parsing.....')",
"tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import json",
"= json.loads(data) if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text",
"parsing.....') print('Time limit is reached') return False def on_error(self, status): print(status) def parse_and_populate(sec_limit,",
"from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd # Connect to MongoDB client_mongo",
"retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] #",
"Data and uploads to MongoDB import twitter_access import mongo_access from tweepy.streaming import StreamListener",
"tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count",
"OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages = ['en'], track =",
"pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo =",
"track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages =",
"(time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False: created_at",
"city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude,",
"= self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"],",
"x = re.sub(r'http\\S+', '', x) return x if (time.time() - self.start_time) < self.sec_limit:",
"print('End parsing.....') print('Time limit is reached') return False def on_error(self, status): print(status) def",
"= parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count =",
"tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation",
"and uploads to MongoDB import twitter_access import mongo_access from tweepy.streaming import StreamListener from",
"psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd # Connect to MongoDB",
"uploads to MongoDB import twitter_access import mongo_access from tweepy.streaming import StreamListener from tweepy",
"self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"],",
"import pandas as pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo =",
"db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time =",
"print('Tweet is uploaded on MongoDB') return True else: print('End parsing.....') print('Time limit is",
"dateutil.parser import parse from pymongo import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment",
"SentimentIntensityAnalyzer import pandas as pd # Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo",
"favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count = tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment",
"= sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls') def on_data(self,",
"'', x) return x if (time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data)",
"city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id,",
"False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth",
"import Stream import json import re import tweepy import time from datetime import",
"False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"]",
"Stream import json import re import tweepy import time from datetime import datetime",
"os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd # Connect",
"x) return x if (time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data) if",
"# Parses Data and uploads to MongoDB import twitter_access import mongo_access from tweepy.streaming",
"parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream",
"MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser",
"\"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True",
"data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return",
"auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages = ['en'],",
"import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as",
"import tweepy import time from datetime import datetime from dateutil.parser import parse from",
"tweet[\"user\"][\"followers_count\"] # text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample()",
"def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET)",
"from datetime import datetime from dateutil.parser import parse from pymongo import MongoClient import",
"Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit",
"sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit self.track = track self.analyser =",
"StreamListener from tweepy import OAuthHandler from tweepy import Stream import json import re",
"= x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x if (time.time() -",
"{\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet",
"import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd #",
"vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas as pd # Connect to MongoDB client_mongo =",
"tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"]",
"time.time() self.sec_limit = sec_limit self.track = track self.analyser = SentimentIntensityAnalyzer() self.cities = pd.read_excel('CitiesEnriched.xls')",
"latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count,",
"MongoDB') return True else: print('End parsing.....') print('Time limit is reached') return False def",
"= OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN, twitter_access.ACCESS_TOKEN_SECRET) stream = Stream(auth, listener) stream.filter(languages = ['en'], track",
"tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True else: print('End parsing.....') print('Time limit",
"datetime from dateutil.parser import parse from pymongo import MongoClient import os import psycopg2",
"text sentiment tweet_sentiment = self.analyser.polarity_scores(text) # user geolocation city = self.cities.sample() longitude =",
"OAuthHandler from tweepy import Stream import json import re import tweepy import time",
"# Connect to MongoDB client_mongo = MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets",
"print(status) def parse_and_populate(sec_limit, track): listener = Output_Listener(sec_limit, track) auth = OAuthHandler(twitter_access.API_KEY, twitter_access.API_SECRET_KEY) auth.set_access_token(twitter_access.ACCESS_TOKEN,",
"# user geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj",
"# Twitter Parser # Parses Data and uploads to MongoDB import twitter_access import",
"\"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return True else: print('End",
"MongoClient(mongo_access.URL) db_mongo = client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener):",
"\"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is",
"'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x) return x if (time.time() - self.start_time) <",
"== False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count =",
"\"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on",
"parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"]",
"if tweet[\"retweeted\"] == False: created_at = parse(tweet[\"created_at\"]) tweet_id_str = tweet[\"id_str\"] text = clean_tweet(tweet[\"text\"])",
"json import re import tweepy import time from datetime import datetime from dateutil.parser",
"Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit =",
"= re.sub(r'http\\S+', '', x) return x if (time.time() - self.start_time) < self.sec_limit: tweet",
"def __init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit self.track = track",
"return x if (time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"]",
"on MongoDB') return True else: print('End parsing.....') print('Time limit is reached') return False",
"\"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB')",
"\"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded",
"client_mongo.get_database(\"alikhanlab-twitter\") tweets_mongo = db_mongo.tweets # Twitter Parser Class class Output_Listener(StreamListener): def __init__(self, sec_limit,",
"if (time.time() - self.start_time) < self.sec_limit: tweet = json.loads(data) if tweet[\"retweeted\"] == False:",
"re import tweepy import time from datetime import datetime from dateutil.parser import parse",
"\"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude} tweets_mongo.insert_one(obj) print('Tweet is uploaded on MongoDB') return",
"__init__(self, sec_limit, track): self.start_time = time.time() self.sec_limit = sec_limit self.track = track self.analyser",
"tweepy import OAuthHandler from tweepy import Stream import json import re import tweepy",
"limit is reached') return False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track): listener",
"obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"], \"neu_score\":tweet_sentiment[\"neu\"], \"pos_score\":tweet_sentiment[\"pos\"], \"retweet_count\":retweet_count, \"favorite_count\":favorite_count, \"user_id\":user_id, \"user_followers_count\":user_followers_count, \"user_long\": longitude, \"user_lat\":latitude}",
"= clean_tweet(tweet[\"text\"]) retweet_count = tweet[\"retweet_count\"] favorite_count = tweet[\"favorite_count\"] user_id = tweet[\"user\"][\"id_str\"] user_followers_count =",
"to MongoDB import twitter_access import mongo_access from tweepy.streaming import StreamListener from tweepy import",
"import OAuthHandler from tweepy import Stream import json import re import tweepy import",
"pymongo import MongoClient import os import psycopg2 from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import pandas",
"city = self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj = {\"track\":self.track[0],\"created_at\":created_at,\"tweet_id_str\":tweet_id_str,\"text\":text, \"neg_score\":tweet_sentiment[\"neg\"],",
"on_data(self, data): def clean_tweet(x): x = x.encode('ascii', 'ignore').decode('ascii') x = re.sub(r'http\\S+', '', x)",
"user geolocation city = self.cities.sample() longitude = city['Lng'].values[0] latitude = city['Lat'].values[0] obj =",
"print('Time limit is reached') return False def on_error(self, status): print(status) def parse_and_populate(sec_limit, track):"
] |
[] |
[
"from setuptools import setup setup( name=\"pandas_helper_calc\", version=\"0.0.1\", packages=[\"pandas_helper_calc\"], license=\"MIT License\", long_description=open(\"README.md\").read(), long_description_content_type=\"text/markdown\", )"
] |
[
"isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d):",
"MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes,",
"from libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from",
"12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def",
"def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12])) def",
"nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return",
"0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif",
"nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight)",
"nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0)",
"import * from libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import",
"3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3],",
"import * from libs.models.msc import * def init_weights(model): for m in model.modules(): if",
"m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias,",
"* from libs.models.msc import * def init_weights(model): for m in model.modules(): if isinstance(m,",
"return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return",
"None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None:",
"23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23,",
"libs.models.resnet import * from libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus",
"not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None:",
"nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes,",
"model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif",
"is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3],",
"from libs.models.resnet import * from libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from",
"from libs.models.msc import * def init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d):",
"DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes):",
"if m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4,",
"libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from libs.models.msc import * def init_weights(model):",
"is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not",
"elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m,",
"12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6,",
"nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight,",
"3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6,",
"None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12,",
"* from libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import *",
"libs.models.msc import * def init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight)",
"not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not",
"DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes):",
"* from libs.models.deeplabv3plus import * from libs.models.msc import * def init_weights(model): for m",
"from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from libs.models.msc import * def",
"def init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is",
"n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3,",
"def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])) def",
"18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9,",
"return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes,",
"import * def init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if",
"for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None:",
"import * from libs.models.deeplabv3plus import * from libs.models.msc import * def init_weights(model): for",
"nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if",
"def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes):",
"DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return",
"1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24]))",
"pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6,",
"isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes):",
"init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not",
"24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12]))",
"if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias",
"nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight,",
"m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is",
"m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23,",
"4, 23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4,",
"isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear):",
"pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3,",
"nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1)",
"libs.models.deeplabv2 import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from libs.models.msc",
"libs.models.deeplabv3plus import * from libs.models.msc import * def init_weights(model): for m in model.modules():",
"23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4, 23, 3],",
"import * from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from libs.models.msc import",
"6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12,",
"from libs.models.deeplabv3plus import * from libs.models.msc import * def init_weights(model): for m in",
"MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3,",
"if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m,",
"9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18]))",
"MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes,",
"not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6,",
"n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3,",
"4, 23, 3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4,",
"elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight, 1) def",
"12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18]))",
"4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4, 23,",
"3], pyramids=[6, 12, 18, 24])) def DeepLabV2S_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3],",
"pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12,",
"* from libs.models.deeplabv3 import * from libs.models.deeplabv3plus import * from libs.models.msc import *",
"1) if m.bias is not None: nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3,",
"23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return MSC(DeepLabV3(n_classes=n_classes, n_blocks=[3, 4, 23,",
"None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias,",
"if m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if",
"is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is",
"in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias is not None: nn.init.constant(m.bias, 0)",
"<reponame>taesung89/deeplab-pytorch<filename>libs/models/__init__.py from libs.models.resnet import * from libs.models.deeplabv2 import * from libs.models.deeplabv3 import *",
"* def init_weights(model): for m in model.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal(m.weight) if m.bias",
"nn.init.constant(m.weight, 1) def DeepLabV2_ResNet101_MSC(n_classes): return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18,",
"return MSC(DeepLabV2(n_classes=n_classes, n_blocks=[3, 4, 23, 3], pyramids=[3, 6, 9, 12])) def DeepLabV3_ResNet101_MSC(n_classes): return",
"m.bias is not None: nn.init.constant(m.bias, 0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias",
"0) elif isinstance(m, nn.BatchNorm2d): nn.init.constant(m.weight, 1) if m.bias is not None: nn.init.constant(m.weight, 1)",
"n_blocks=[3, 4, 23, 3], pyramids=[6, 12, 18])) def DeepLabV3Plus_ResNet101_MSC(n_classes): return MSC(DeepLabV3Plus(n_classes=n_classes, n_blocks=[3, 4,"
] |
[
"string separated by '/' for a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts)",
"'' else: return parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query",
"host_name: str, path_parts: List[str] = None, query_parts: Dict[str, str] = None) -> str:",
"List[str]) -> str: \"\"\"Return a string separated by '/' for a url path.\"\"\"",
"'/'.join(parts) elif parts is None: return '' else: return parts def construct_query_parts(parts: Dict[str,",
"construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated by '/' for a url",
"else: return parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query string",
"\"\"\"Return a query string constrcuted from key value pairs\"\"\" if isinstance(parts, dict): return",
"-> str: \"\"\"Return a string separated by '/' for a url path.\"\"\" if",
"def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated by '/' for a",
"dict): return '&'.join(x + '=' + y for x, y in parts.items()) else:",
"parts.items()) else: return parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None,",
"= None, query_parts: Dict[str, str] = None) -> str: return urlparse.urlunsplit(( scheme, host_name,",
"for a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts is None:",
"query_parts: Dict[str, str] = None) -> str: return urlparse.urlunsplit(( scheme, host_name, construct_path_parts(path_parts), construct_query_parts(query_parts),",
"string constrcuted from key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '='",
"urllib.parse as urlparse from typing import List, Dict def construct_path_parts(parts: List[str]) -> str:",
"Dict[str, str] = None) -> str: return urlparse.urlunsplit(( scheme, host_name, construct_path_parts(path_parts), construct_query_parts(query_parts), None",
"parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query string constrcuted from",
"return '&'.join(x + '=' + y for x, y in parts.items()) else: return",
"by '/' for a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts",
"is None: return '' else: return parts def construct_query_parts(parts: Dict[str, str]) -> str:",
"'&'.join(x + '=' + y for x, y in parts.items()) else: return parts",
"None: return '' else: return parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return",
"urlparse from typing import List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a",
"str]) -> str: \"\"\"Return a query string constrcuted from key value pairs\"\"\" if",
"import List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated by",
"y for x, y in parts.items()) else: return parts def construct_api_url(scheme: str, host_name:",
"str: \"\"\"Return a string separated by '/' for a url path.\"\"\" if isinstance(parts,",
"parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None, query_parts: Dict[str, str]",
"str, path_parts: List[str] = None, query_parts: Dict[str, str] = None) -> str: return",
"Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated by '/' for",
"key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '=' + y for",
"list): return '/'.join(parts) elif parts is None: return '' else: return parts def",
"in parts.items()) else: return parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str] =",
"construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query string constrcuted from key value",
"a query string constrcuted from key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x",
"'=' + y for x, y in parts.items()) else: return parts def construct_api_url(scheme:",
"None, query_parts: Dict[str, str] = None) -> str: return urlparse.urlunsplit(( scheme, host_name, construct_path_parts(path_parts),",
"separated by '/' for a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif",
"return parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None, query_parts: Dict[str,",
"parts is None: return '' else: return parts def construct_query_parts(parts: Dict[str, str]) ->",
"List[str] = None, query_parts: Dict[str, str] = None) -> str: return urlparse.urlunsplit(( scheme,",
"\"\"\"Return a string separated by '/' for a url path.\"\"\" if isinstance(parts, list):",
"a string separated by '/' for a url path.\"\"\" if isinstance(parts, list): return",
"return '/'.join(parts) elif parts is None: return '' else: return parts def construct_query_parts(parts:",
"constrcuted from key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '=' +",
"from key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '=' + y",
"query string constrcuted from key value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x +",
"+ y for x, y in parts.items()) else: return parts def construct_api_url(scheme: str,",
"return parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query string constrcuted",
"isinstance(parts, dict): return '&'.join(x + '=' + y for x, y in parts.items())",
"path_parts: List[str] = None, query_parts: Dict[str, str] = None) -> str: return urlparse.urlunsplit((",
"isinstance(parts, list): return '/'.join(parts) elif parts is None: return '' else: return parts",
"else: return parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None, query_parts:",
"path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts is None: return '' else:",
"elif parts is None: return '' else: return parts def construct_query_parts(parts: Dict[str, str])",
"y in parts.items()) else: return parts def construct_api_url(scheme: str, host_name: str, path_parts: List[str]",
"construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None, query_parts: Dict[str, str] = None)",
"def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a query string constrcuted from key",
"str, host_name: str, path_parts: List[str] = None, query_parts: Dict[str, str] = None) ->",
"pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '=' + y for x, y",
"if isinstance(parts, dict): return '&'.join(x + '=' + y for x, y in",
"def construct_api_url(scheme: str, host_name: str, path_parts: List[str] = None, query_parts: Dict[str, str] =",
"str] = None) -> str: return urlparse.urlunsplit(( scheme, host_name, construct_path_parts(path_parts), construct_query_parts(query_parts), None ))",
"typing import List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated",
"a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts is None: return",
"for x, y in parts.items()) else: return parts def construct_api_url(scheme: str, host_name: str,",
"as urlparse from typing import List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return",
"-> str: \"\"\"Return a query string constrcuted from key value pairs\"\"\" if isinstance(parts,",
"url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts is None: return ''",
"+ '=' + y for x, y in parts.items()) else: return parts def",
"from typing import List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string",
"value pairs\"\"\" if isinstance(parts, dict): return '&'.join(x + '=' + y for x,",
"if isinstance(parts, list): return '/'.join(parts) elif parts is None: return '' else: return",
"str: \"\"\"Return a query string constrcuted from key value pairs\"\"\" if isinstance(parts, dict):",
"List, Dict def construct_path_parts(parts: List[str]) -> str: \"\"\"Return a string separated by '/'",
"import urllib.parse as urlparse from typing import List, Dict def construct_path_parts(parts: List[str]) ->",
"return '' else: return parts def construct_query_parts(parts: Dict[str, str]) -> str: \"\"\"Return a",
"'/' for a url path.\"\"\" if isinstance(parts, list): return '/'.join(parts) elif parts is",
"x, y in parts.items()) else: return parts def construct_api_url(scheme: str, host_name: str, path_parts:",
"Dict[str, str]) -> str: \"\"\"Return a query string constrcuted from key value pairs\"\"\""
] |
[
"r a = radiusm u = linspace(0, 10 * pi,1000) r = r_(u)",
"radiusm, figcolor): plt.clf() def r_(u): r = a * sqrt(u) return r a",
"* pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\")",
"= radiusm u = linspace(0, 10 * pi,1000) r = r_(u) ax =",
"linspace(0, 10 * pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor)",
"return r a = radiusm u = linspace(0, 10 * pi,1000) r =",
"name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u):",
"* from numpy import * from matplotlib.animation import * name = \"<NAME>\" def",
"grid, radiusm, figcolor): plt.clf() def r_(u): r = a * sqrt(u) return r",
"from numpy import * from matplotlib.animation import * name = \"<NAME>\" def shape(fig,",
"<gh_stars>1-10 import matplotlib.pyplot as plt from matplotlib import * from numpy import *",
"edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r = a * sqrt(u)",
"numpy import * from matplotlib.animation import * name = \"<NAME>\" def shape(fig, edge_c,",
"import * from matplotlib.animation import * name = \"<NAME>\" def shape(fig, edge_c, edge_w,",
"def r_(u): r = a * sqrt(u) return r a = radiusm u",
"= linspace(0, 10 * pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar') #",
"plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\") plt.axis(grid) plt.plot(u, r, color=edge_c, linewidth=edge_w)",
"a = radiusm u = linspace(0, 10 * pi,1000) r = r_(u) ax",
"def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r = a",
"= a * sqrt(u) return r a = radiusm u = linspace(0, 10",
"10 * pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\",",
"matplotlib.pyplot as plt from matplotlib import * from numpy import * from matplotlib.animation",
"radiusm u = linspace(0, 10 * pi,1000) r = r_(u) ax = plt.subplot(111,",
"from matplotlib.animation import * name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm,",
"\"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r =",
"= plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\") plt.axis(grid) plt.plot(u, r, color=edge_c,",
"r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\") plt.axis(grid) plt.plot(u,",
"a * sqrt(u) return r a = radiusm u = linspace(0, 10 *",
"* sqrt(u) return r a = radiusm u = linspace(0, 10 * pi,1000)",
"pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\",",
"* name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def",
"ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\") plt.axis(grid) plt.plot(u, r,",
"= \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r",
"matplotlib import * from numpy import * from matplotlib.animation import * name =",
"r_(u): r = a * sqrt(u) return r a = radiusm u =",
"as plt from matplotlib import * from numpy import * from matplotlib.animation import",
"r = a * sqrt(u) return r a = radiusm u = linspace(0,",
"shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r = a *",
"figcolor): plt.clf() def r_(u): r = a * sqrt(u) return r a =",
"* from matplotlib.animation import * name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid,",
"import * from numpy import * from matplotlib.animation import * name = \"<NAME>\"",
"from matplotlib import * from numpy import * from matplotlib.animation import * name",
"= r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\") plt.axis(grid)",
"edge_w, grid, radiusm, figcolor): plt.clf() def r_(u): r = a * sqrt(u) return",
"plt.clf() def r_(u): r = a * sqrt(u) return r a = radiusm",
"import matplotlib.pyplot as plt from matplotlib import * from numpy import * from",
"import * name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor): plt.clf()",
"sqrt(u) return r a = radiusm u = linspace(0, 10 * pi,1000) r",
"u = linspace(0, 10 * pi,1000) r = r_(u) ax = plt.subplot(111, projection='polar')",
"matplotlib.animation import * name = \"<NAME>\" def shape(fig, edge_c, edge_w, grid, radiusm, figcolor):",
"r = r_(u) ax = plt.subplot(111, projection='polar') # ax.patch.set_facecolor(figcolor) ax.xaxis.set_tick_params(color=\"white\", labelcolor=\"white\") ax.yaxis.set_tick_params(color=\"white\", labelcolor=\"white\")",
"plt from matplotlib import * from numpy import * from matplotlib.animation import *"
] |
[
"\"douphp\": return True, arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head,",
"== \"douphp\": return True, arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code,",
"arg): if service == \"douphp\": return True, arg def audit(arg): url = arg",
"True, arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl",
"audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if",
"assign(service, arg): if service == \"douphp\": return True, arg def audit(arg): url =",
"= curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:'",
"'1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\": return True, arg",
"traversal:' + url) if __name__ == '__main__': from dummy import * audit(assign('douphp', 'http://1172.16.31.10/douphp/')[1])",
"service == \"douphp\": return True, arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\"",
"python # -*- coding: utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service,",
"coding: utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service",
"http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\": return True, arg def audit(arg):",
"def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url)",
"if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url)",
"+ \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and",
"Directory traversal:' + url) if __name__ == '__main__': from dummy import * audit(assign('douphp',",
"#ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\": return True, arg def",
"arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1",
"and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url) if __name__ == '__main__':",
"!= -1: security_warning('find Directory traversal:' + url) if __name__ == '__main__': from dummy",
"= '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\": return True,",
"code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") !=",
"curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' +",
"if service == \"douphp\": return True, arg def audit(arg): url = arg +",
"res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url) if",
"#__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\": return",
"errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find Directory",
"= arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") !=",
"#!/usr/bin/env python # -*- coding: utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def",
"return True, arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res,",
"def assign(service, arg): if service == \"douphp\": return True, arg def audit(arg): url",
"head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1:",
"security_warning('find Directory traversal:' + url) if __name__ == '__main__': from dummy import *",
"res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url) if __name__ == '__main__': from",
"-*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service == \"douphp\":",
"-1: security_warning('find Directory traversal:' + url) if __name__ == '__main__': from dummy import",
"res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\") != -1: security_warning('find",
"-1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url) if __name__ ==",
"url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\")",
"!= -1 and res.find(\"file_list\") != -1: security_warning('find Directory traversal:' + url) if __name__",
"# -*- coding: utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg):",
"\"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl = curl.curl(url) if res.find(\"total_count\") != -1 and res.find(\"file_list\")",
"arg def audit(arg): url = arg + \"admin/include/kindeditor/php/file_manager_json.php?path=/&dir=image\" code, head, res, errcode,finalurl =",
"-*- coding: utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if",
"utf-8 -*- #__author__ = '1c3z' #ref http://www.wooyun.org/bugs/wooyun-2010-076974 def assign(service, arg): if service =="
] |
[
"& Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree",
"p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml):",
"for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2",
"\"\"\" Created on Sat May 18 23:47:15 2019 @author: <NAME> \"\"\" import glob",
"value.append(s_sku) count2 = count + count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2###############",
"pd from datetime import datetime import logging import time start_time = time.time() logging.basicConfig(filename='app.log',",
"[etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()]",
"= [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if",
"PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time()",
"count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools",
"{'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts",
"Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for",
"in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d =",
"s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s Nb item', count2)",
"- %(message)s') count2=0 value = [] try: #######Solution 1############### for p in Path('C:/RTC/Scripts",
"except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time = End_time - start_time",
"from datetime import datetime import logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w',",
"for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def",
"count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p",
"for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2",
"header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time = End_time -",
"len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count",
"pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools &",
"count + count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p))",
"etree import pandas as pd from datetime import datetime import logging import time",
"SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb",
"& Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count)",
"list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring",
"import etree import pandas as pd from datetime import datetime import logging import",
"export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None,",
"PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in",
"glob import os import os.path from pathlib import Path from lxml import etree",
"= datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU",
"level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0 value = [] try:",
"= pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools",
"value = [] try: #######Solution 1############### for p in Path('C:/RTC/Scripts & Tools &",
"in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p))",
"= [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in",
"def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for",
"p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku",
"nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION",
"datetime import datetime import logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG,",
"time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0 value",
"= df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True)",
"item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts &",
"utf-8 -*- \"\"\" Created on Sat May 18 23:47:15 2019 @author: <NAME> \"\"\"",
"Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku =",
"[] try: #######Solution 1############### for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU",
"print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel",
"& Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as",
"xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s Nb item',",
"[sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list))",
"1############### for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file():",
"p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text",
"if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list =",
"logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0 value =",
"= count + count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list =",
"Created on Sat May 18 23:47:15 2019 @author: <NAME> \"\"\" import glob import",
"xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku =",
"\"\"\" import glob import os import os.path from pathlib import Path from lxml",
"datetime import logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s -",
"= [] try: #######Solution 1############### for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT",
"-*- \"\"\" Created on Sat May 18 23:47:15 2019 @author: <NAME> \"\"\" import",
"' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index",
"Path from lxml import etree import pandas as pd from datetime import datetime",
"d = {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel =",
"import os import os.path from pathlib import Path from lxml import etree import",
"#######Solution 1############### for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if",
"for total in test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring =",
"find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku",
"Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as e: logging.exception(\"Exception occurred\")",
"SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time",
"start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')",
"%Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index =",
"os import os.path from pathlib import Path from lxml import etree import pandas",
"& Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree",
"Nb item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts",
"-*- coding: utf-8 -*- \"\"\" Created on Sat May 18 23:47:15 2019 @author:",
"Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for",
"SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')]",
"- %(levelname)s - %(message)s') count2=0 value = [] try: #######Solution 1############### for p",
"import os.path from pathlib import Path from lxml import etree import pandas as",
"import logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s",
"import Path from lxml import etree import pandas as pd from datetime import",
"count2 = count + count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list",
"logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s -",
"import pandas as pd from datetime import datetime import logging import time start_time",
"Sat May 18 23:47:15 2019 @author: <NAME> \"\"\" import glob import os import",
"Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in",
"pandas as pd from datetime import datetime import logging import time start_time =",
"Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count",
"2019 @author: <NAME> \"\"\" import glob import os import os.path from pathlib import",
"for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml",
"count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2",
"= None, header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time =",
"= time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0",
"value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d = {'SKU':value} df =",
"if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'):",
"Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time = End_time - start_time print(f\"{Execution_time},secs\")",
"import glob import os import os.path from pathlib import Path from lxml import",
"test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml')",
"print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools &",
"try: #######Solution 1############### for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'):",
"test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S')",
"index = None, header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time",
"df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except",
"#######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT",
"coding: utf-8 -*- \"\"\" Created on Sat May 18 23:47:15 2019 @author: <NAME>",
"nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s",
"= etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text",
"May 18 23:47:15 2019 @author: <NAME> \"\"\" import glob import os import os.path",
"%(levelname)s - %(message)s') count2=0 value = [] try: #######Solution 1############### for p in",
"return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d = {'SKU':value} df",
"= {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel",
"import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s",
"in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku",
"print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count +",
"list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in",
"as pd from datetime import datetime import logging import time start_time = time.time()",
"filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0 value = []",
"from pathlib import Path from lxml import etree import pandas as pd from",
"df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts &",
"lxml import etree import pandas as pd from datetime import datetime import logging",
"sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total",
"= list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d)",
"datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx',",
"Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as e:",
"= len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 =",
"etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\")) print(count) for nb in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku)",
"23:47:15 2019 @author: <NAME> \"\"\" import glob import os import os.path from pathlib",
"pathlib import Path from lxml import etree import pandas as pd from datetime",
"18 23:47:15 2019 @author: <NAME> \"\"\" import glob import os import os.path from",
"<NAME> \"\"\" import glob import os import os.path from pathlib import Path from",
"in xml.findall('.//PRODUCT'): s_sku = nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s Nb",
"# -*- coding: utf-8 -*- \"\"\" Created on Sat May 18 23:47:15 2019",
"2############### test_list = [etree.parse(str(p)) for p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU",
"(fr'C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception",
"list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d = {'SKU':value}",
"count2=0 value = [] try: #######Solution 1############### for p in Path('C:/RTC/Scripts & Tools",
"import datetime import logging import time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s",
"p in Path('C:/RTC/Scripts & Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml =",
"PY').glob('**/*.xml') if p.is_file()] def find_sku(xml): list_find_all_sku = [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list",
"None, header=True) except Exception as e: logging.exception(\"Exception occurred\") End_time =time.time() Execution_time = End_time",
"[sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list)",
"for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2))",
"format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') count2=0 value = [] try: #######Solution",
"= [sku_tree for sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku]",
"& Files/Python/COUNT SKU PY/export_NB_SKU_{datestring}.xlsx', index = None, header=True) except Exception as e: logging.exception(\"Exception",
"total in test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(),",
"logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for p in",
"& Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count =",
"sku_tree in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 =",
"xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for",
"- %(name)s - %(levelname)s - %(message)s') count2=0 value = [] try: #######Solution 1###############",
"@author: <NAME> \"\"\" import glob import os import os.path from pathlib import Path",
"= nb.find(\"A0001\").text value.append(s_sku) count2 = count + count2 logging.info('%s Nb item', count2) print(count2)",
"from lxml import etree import pandas as pd from datetime import datetime import",
"on Sat May 18 23:47:15 2019 @author: <NAME> \"\"\" import glob import os",
"%(name)s - %(levelname)s - %(message)s') count2=0 value = [] try: #######Solution 1############### for",
"%(message)s') count2=0 value = [] try: #######Solution 1############### for p in Path('C:/RTC/Scripts &",
"in xml.findall('.//PRODUCT')] sku_value_list = [sku.find(\"A0001\").text for sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total)",
"sku in list_find_all_sku] return(sku_value_list) value2 = list(chain.from_iterable(find_sku(total) for total in test_list)) print(len(value2)) d",
"time start_time = time.time() logging.basicConfig(filename='app.log', filemode='w', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s -",
"datestring = datetime.strftime(datetime.now(), ' %Y%m%d_%H%M%S') export_excel = df.to_excel (fr'C:/RTC/Scripts & Tools & Files/Python/COUNT",
"in test_list)) print(len(value2)) d = {'SKU':value} df = pd.DataFrame(d) datestring = datetime.strftime(datetime.now(), '",
"+ count2 logging.info('%s Nb item', count2) print(count2) #######SOLUTION 2############### test_list = [etree.parse(str(p)) for",
"os.path from pathlib import Path from lxml import etree import pandas as pd",
"Tools & Files/Python/COUNT SKU PY').glob('**/*.xml'): if p.is_file(): xml = etree.parse(str(p)) count = len(xml.findall(\".//*[A0001]\"))"
] |
[
"for i in range(n): r += step g += step b += step",
"= (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset =",
"def setVizType(self, type): self._vizType = type def vizType(self): return self._vizType def setRange(self, range):",
"while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if self._data is",
"None if self._vizType == 'grayscale': data = self.selectedData() # print('selected shape', data.shape) transformed",
"read import os import math from copy import copy from ._Base import _Base",
"0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized,",
"bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8)",
"label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range = (0.0, 1.0),",
"not None: self._dims = len(data.shape) else: self._dims = 0 if data is not",
"not None and len(data.shape) == 1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data,",
"else: return 0 def maxCurrentOffsetValue(self): if self._data is not None: data = self.selectedData()",
"float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType ==",
"transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb':",
"def dims(self): return self._dims def offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type):",
"return float(m) else: return 0 def data(self): return self._data def image(self): if self._data",
"heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data =",
"True: off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized =",
"= [min] off = min while True: off = math.ceil(off) + 0.5 if",
"bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base):",
"is not None and len(data.shape) == 1: data = np.expand_dims(data, axis=1) data =",
"data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data =",
"None and len(data.shape) == 1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2)",
"None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self): # print('selectedData',",
"axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) #",
"self._offset = (0, 0) self._plotAxes = (0, 1) self._offsetAxes = (2, 3) self._dims",
"return self._vizType def setRange(self, range): self._range = range def offsetLimits(self): if self._dims ==",
"isinstance(data, VizItem): self._marks = data.marks data = data.data if data is not None:",
"axis=2) data = np.expand_dims(data, axis=3) if data is not None and len(data.shape) ==",
"np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self): return self._data def image(self): if",
"os.path.exists(data): data = read(data) else: data = None elif isinstance(data, VizItem): self._marks =",
"bins = [min] off = min while True: off = math.ceil(off) + 0.5",
"is None: return None if self._vizType == 'grayscale': data = self.selectedData() # print('selected",
"else: return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data,",
"shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label':",
"int(0.5 * 256) g = int(0.5 * 256) b = int(0.5 * 256)",
"= list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if",
"None: return None if self._vizType == 'grayscale': data = self.selectedData() # print('selected shape',",
"if self._vizType == 'grayscale': data = self.selectedData() # print('selected shape', data.shape) transformed =",
"= None elif isinstance(data, VizItem): self._marks = data.marks data = data.data if data",
"2, 0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0]))",
"m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self): if self._data is",
"import toQPixmap import numpy as np from ikit.dataops import heat_map_viz from ikit import",
"= np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data =",
"= range def offsetLimits(self): if self._dims == 2: return [] if self._dims ==",
"/ n for i in range(n): r += step g += step b",
"2: return if isinstance(offset, int): offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset)",
"= np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data is not None and",
"Float(_Base): def __init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale'",
"self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self):",
"elif self._vizType == 'label': data = self.selectedData() # print('selected shape', data.shape) return labelViz(data[:,",
"np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self): transformed = (self._data -",
"dims(self): return self._dims def offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type): self._vizType",
"and len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data = data def dims(self):",
"self._data = data def dims(self): return self._dims def offsetDims(self): return min(0,self._dims - 2)",
"0 def maxValue(self): if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m)",
"None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def",
"str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data = None elif isinstance(data,",
"..Util import toQPixmap import numpy as np from ikit.dataops import heat_map_viz from ikit",
"is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self):",
"= int(r) % 256 g = int(g) % 256 b = int(b) %",
"= int(0.5 * 256) g = int(0.5 * 256) b = int(0.5 *",
"if data is not None and len(data.shape) == 1: data = np.expand_dims(data, axis=1)",
"VizItem def colors(n): ret = [] r = int(0.5 * 256) g =",
"- float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return",
"1) self._offsetAxes = (2, 3) self._dims = None self.setTo(data) def setTo(self, data): if",
"step g += step b += step r = int(r) % 256 g",
"transformed = (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0]",
"def setOffset(self, offset): if self._dims <= 2: return if isinstance(offset, int): offset =",
"[min] off = min while True: off = math.ceil(off) + 0.5 if off>=max:",
"(color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType",
"return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid viztype') def pixmap(self): return toQPixmap(self.image())",
"* 256) g = int(0.5 * 256) b = int(0.5 * 256) step",
"= (2, 3) self._dims = None self.setTo(data) def setTo(self, data): if isinstance(data, str):",
"== 1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data,",
"if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0)",
"data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data",
"+= step b += step r = int(r) % 256 g = int(g)",
"= np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes,",
"g += step b += step r = int(r) % 256 g =",
"data(self): return self._data def image(self): if self._data is None: return None if self._vizType",
"= math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins)",
"offset): if self._dims <= 2: return if isinstance(offset, int): offset = [offset, 0]",
"= [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set',",
"def colors(n): ret = [] r = int(0.5 * 256) g = int(0.5",
"def maxValue(self): if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else:",
"if self._data is not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m)",
"float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:,",
"#-*- coding: utf-8 -*- import ikit.io from ..Util import toQPixmap import numpy as",
"1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset = (0, 0)",
":], [1, 2, 0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1])",
"is not None: data = np.squeeze(data) if data is not None: self._dims =",
"marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset = (0, 0) self._plotAxes",
"len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data = data def dims(self): return",
"else: return 0 def maxValue(self): if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))])",
"256) b = int(0.5 * 256) step = 256 / n for i",
"(float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :]",
"self.selectedData3() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) -",
"= data.data if data is not None: data = np.squeeze(data) if data is",
"m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data is",
"range(n): r += step g += step b += step r = int(r)",
"= self.selectedData() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1])",
"np from ikit.dataops import heat_map_viz from ikit import read import os import math",
"axis=2) data = np.expand_dims(data, axis=3) elif data is not None and len(data.shape) ==",
"axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data is not",
"None and len(data.shape) == 0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1)",
"= int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data, min, max): from scipy",
"range self._offset = (0, 0) self._plotAxes = (0, 1) self._offsetAxes = (2, 3)",
"vizType(self): return self._vizType def setRange(self, range): self._range = range def offsetLimits(self): if self._dims",
"super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset = (0, 0) self._plotAxes =",
"256) g = int(0.5 * 256) b = int(0.5 * 256) step =",
"np.squeeze(data) if data is not None: self._dims = len(data.shape) else: self._dims = 0",
"heat_map_viz from ikit import read import os import math from copy import copy",
"if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0",
"return None if self._vizType == 'grayscale': data = self.selectedData() # print('selected shape', data.shape)",
"setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2)",
"return float(m) else: return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed",
"from scipy import ndimage from skimage.color import label2rgb bins = [min] off =",
"range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset",
"+ self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self): transformed",
"data is not None: self._dims = len(data.shape) else: self._dims = 0 if data",
"transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if",
"def minCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))])",
"np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 1: data =",
"i in range(n): r += step g += step b += step r",
"data = np.expand_dims(data, axis=3) self._data = data def dims(self): return self._dims def offsetDims(self):",
"type def vizType(self): return self._vizType def setRange(self, range): self._range = range def offsetLimits(self):",
"is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self):",
"copy from ._Base import _Base from .VizItem import VizItem def colors(n): ret =",
"if data is not None: self._dims = len(data.shape) else: self._dims = 0 if",
"while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims",
"setOffset(self, offset): if self._dims <= 2: return if isinstance(offset, int): offset = [offset,",
"(float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif",
"np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes)",
"import math from copy import copy from ._Base import _Base from .VizItem import",
"not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self): #",
"float(m) else: return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed =",
"len(data.shape) == 0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data =",
"/ (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :,",
"= int(0.5 * 256) b = int(0.5 * 256) step = 256 /",
"int(g) % 256 b = int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data,",
"from .VizItem import VizItem def colors(n): ret = [] r = int(0.5 *",
"not None: data = np.squeeze(data) if data is not None: self._dims = len(data.shape)",
"data = self.selectedData3() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) /",
"self._data is not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else:",
"self._vizType = 'grayscale' self._range = range self._offset = (0, 0) self._plotAxes = (0,",
"min(0,self._dims - 2) def setVizType(self, type): self._vizType = type def vizType(self): return self._vizType",
"#!/usr/bin/env python3 #-*- coding: utf-8 -*- import ikit.io from ..Util import toQPixmap import",
"# print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0]))",
"setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data",
"self._dims <= 2: return if isinstance(offset, int): offset = [offset, 0] self._offset =",
"0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData() #",
"None: self._dims = len(data.shape) else: self._dims = 0 if data is not None",
"bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range = (0.0, 1.0), marks=None):",
"- float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def",
"* 256) b = int(0.5 * 256) step = 256 / n for",
"= np.expand_dims(data, axis=3) elif data is not None and len(data.shape) == 3: data",
"b = int(0.5 * 256) step = 256 / n for i in",
"self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data)",
"setVizType(self, type): self._vizType = type def vizType(self): return self._vizType def setRange(self, range): self._range",
"% 256 b = int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data, min,",
"and len(data.shape) == 1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data",
"int): offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) #",
"is not None and len(data.shape) == 0: data = np.expand_dims(data, axis=0) data =",
"data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data is not None",
"data is not None and len(data.shape) == 0: data = np.expand_dims(data, axis=0) data",
"0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset) def",
"1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data =",
"import copy from ._Base import _Base from .VizItem import VizItem def colors(n): ret",
"else: return 0 def data(self): return self._data def image(self): if self._data is None:",
"float(m) else: return 0 def data(self): return self._data def image(self): if self._data is",
"data = np.squeeze(data) if data is not None: self._dims = len(data.shape) else: self._dims",
"offsetLimits(self): if self._dims == 2: return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1]",
"= range self._offset = (0, 0) self._plotAxes = (0, 1) self._offsetAxes = (2,",
"None self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data =",
"heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData() # print('selected shape', data.shape) return",
":, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1],",
"selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1,",
"np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 2: data =",
"setRange(self, range): self._range = range def offsetLimits(self): if self._dims == 2: return []",
"axis=3) if data is not None and len(data.shape) == 2: data = np.expand_dims(data,",
":] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :,",
"while True: off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized",
"[self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes):",
"def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes)",
"- float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType",
"+= step r = int(r) % 256 g = int(g) % 256 b",
"shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid viztype') def pixmap(self):",
"import numpy as np from ikit.dataops import heat_map_viz from ikit import read import",
"print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1]",
"'grayscale': data = self.selectedData() # print('selected shape', data.shape) transformed = (data - float(self._range[0]))",
"+ 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled =",
"= np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self,",
"transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3()",
"(0, 0) self._plotAxes = (0, 1) self._offsetAxes = (2, 3) self._dims = None",
"len(data.shape) == 1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data =",
"= axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset):",
"isinstance(offset, int): offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0)",
"'rgb': data = self.selectedData3() # print('selected shape', data.shape) transformed = (data - float(self._range[0]))",
"os import math from copy import copy from ._Base import _Base from .VizItem",
"self._dims = 0 if data is not None and len(data.shape) == 0: data",
"self._data is None: return None if self._vizType == 'grayscale': data = self.selectedData() #",
"if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes",
"def __init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range",
"= np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self): if self._data is not",
"axis=3) if data is not None and len(data.shape) == 1: data = np.expand_dims(data,",
"skimage.color import label2rgb bins = [min] off = min while True: off =",
"not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0",
"float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data is not None: data =",
"data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid viztype') def pixmap(self): return",
"(float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8)",
"(2, 3) self._dims = None self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data)",
"data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range",
"0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2)",
"print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1],",
"= 256 / n for i in range(n): r += step g +=",
"label2rgb bins = [min] off = min while True: off = math.ceil(off) +",
"self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self): return self._data",
"2: return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4:",
"= np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0])",
"= 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data",
"self._range = range self._offset = (0, 0) self._plotAxes = (0, 1) self._offsetAxes =",
"= axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes)",
"def offsetLimits(self): if self._dims == 2: return [] if self._dims == 3: return",
"transformed = (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes",
"np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None,",
"2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if self._data is not None:",
"+ self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes",
"# print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType",
"int(0.5 * 256) b = int(0.5 * 256) step = 256 / n",
"if self._dims <= 2: return if isinstance(offset, int): offset = [offset, 0] self._offset",
"self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes +",
"= 0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3() #",
"_Base from .VizItem import VizItem def colors(n): ret = [] r = int(0.5",
"def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed =",
"= len(data.shape) else: self._dims = 0 if data is not None and len(data.shape)",
"self._data def image(self): if self._data is None: return None if self._vizType == 'grayscale':",
"min, max): from scipy import ndimage from skimage.color import label2rgb bins = [min]",
"minValue(self): if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return",
"else: self._dims = 0 if data is not None and len(data.shape) == 0:",
"heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData() #",
"m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self): return self._data def",
"== 3: data = np.expand_dims(data, axis=3) self._data = data def dims(self): return self._dims",
"self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self): transformed =",
"self._offset) def minValue(self): if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m)",
"step r = int(r) % 256 g = int(g) % 256 b =",
"max): from scipy import ndimage from skimage.color import label2rgb bins = [min] off",
"= (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] =",
"from ..Util import toQPixmap import numpy as np from ikit.dataops import heat_map_viz from",
"= np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data is not",
"print('offsets set', self._offset) def minValue(self): if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))])",
"axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if",
"np.expand_dims(data, axis=3) elif data is not None and len(data.shape) == 3: data =",
"np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is",
"== 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return []",
"r = int(0.5 * 256) g = int(0.5 * 256) b = int(0.5",
"self._dims = len(data.shape) else: self._dims = 0 if data is not None and",
"3: data = np.expand_dims(data, axis=3) self._data = data def dims(self): return self._dims def",
"(0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range = range self._offset = (0,",
"np.expand_dims(data, axis=3) self._data = data def dims(self): return self._dims def offsetDims(self): return min(0,self._dims",
"def data(self): return self._data def image(self): if self._data is None: return None if",
"< 2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if self._data is not",
"transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is not None: data = self.selectedData()",
"elif self._vizType == 'rgb': data = self.selectedData3() # print('selected shape', data.shape) transformed =",
"data.marks data = data.data if data is not None: data = np.squeeze(data) if",
"(0, 1) self._offsetAxes = (2, 3) self._dims = None self.setTo(data) def setTo(self, data):",
"offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets",
"% 256 g = int(g) % 256 b = int(b) % 256 ret.append((r,g,b))",
"._Base import _Base from .VizItem import VizItem def colors(n): ret = [] r",
"- 2) def setVizType(self, type): self._vizType = type def vizType(self): return self._vizType def",
"len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <=",
"return heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData() # print('selected shape', data.shape)",
"if self._data is not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m)",
"3) self._dims = None self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if",
"transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self):",
"return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is not None: data =",
"= self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self): if",
"read(data) else: data = None elif isinstance(data, VizItem): self._marks = data.marks data =",
"self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data",
"'label': data = self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1])",
"off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return",
"- float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return",
"return self._dims def offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type): self._vizType =",
"(self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes)",
"toQPixmap import numpy as np from ikit.dataops import heat_map_viz from ikit import read",
"maxValue(self): if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return",
"data is not None: data = np.squeeze(data) if data is not None: self._dims",
"ikit.io from ..Util import toQPixmap import numpy as np from ikit.dataops import heat_map_viz",
"= (0, 1) self._offsetAxes = (2, 3) self._dims = None self.setTo(data) def setTo(self,",
"self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <= 2: return if",
"elif data is not None and len(data.shape) == 3: data = np.expand_dims(data, axis=3)",
"and len(data.shape) == 2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif",
":] def minCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m =",
"maxCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return",
"offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type): self._vizType = type def vizType(self):",
"+ self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is not None:",
"in range(n): r += step g += step b += step r =",
"np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data is not None and len(data.shape)",
"== 2: return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims ==",
"set', self._offset) def minValue(self): if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return",
"256 g = int(g) % 256 b = int(b) % 256 ret.append((r,g,b)) return",
"== 'heatmap': data = self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0],",
"float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType",
"elif self._vizType == 'heatmap': data = self.selectedData() # print('selected shape', data.shape) heatmap =",
"0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed",
"2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data is not",
"break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class",
"np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self): if self._data is not None:",
"None elif isinstance(data, VizItem): self._marks = data.marks data = data.data if data is",
"isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data = None elif",
"data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self):",
"ikit import read import os import math from copy import copy from ._Base",
"= 'grayscale' self._range = range self._offset = (0, 0) self._plotAxes = (0, 1)",
"def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else:",
"data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1",
"numpy as np from ikit.dataops import heat_map_viz from ikit import read import os",
"selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return",
"ret = [] r = int(0.5 * 256) g = int(0.5 * 256)",
"3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def",
"ikit.dataops import heat_map_viz from ikit import read import os import math from copy",
"def setRange(self, range): self._range = range def offsetLimits(self): if self._dims == 2: return",
"r = int(r) % 256 g = int(g) % 256 b = int(b)",
"if isinstance(offset, int): offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2):",
"from copy import copy from ._Base import _Base from .VizItem import VizItem def",
"if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0",
"data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if",
"0 if data is not None and len(data.shape) == 0: data = np.expand_dims(data,",
"is not None: self._dims = len(data.shape) else: self._dims = 0 if data is",
"= (0, 0) self._plotAxes = (0, 1) self._offsetAxes = (2, 3) self._dims =",
"labelViz(data, min, max): from scipy import ndimage from skimage.color import label2rgb bins =",
"return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks)",
"from ikit import read import os import math from copy import copy from",
"self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData() # print('selected shape',",
"elif isinstance(data, VizItem): self._marks = data.marks data = data.data if data is not",
"print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType ==",
"= (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes +",
"self._range = range def offsetLimits(self): if self._dims == 2: return [] if self._dims",
"(transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData() # print('selected shape',",
"if os.path.exists(data): data = read(data) else: data = None elif isinstance(data, VizItem): self._marks",
"return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData() # print('selected",
"/ (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :,",
"self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes,",
"data = read(data) else: data = None elif isinstance(data, VizItem): self._marks = data.marks",
"return ret def labelViz(data, min, max): from scipy import ndimage from skimage.color import",
"data is not None and len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data",
"== 'rgb': data = self.selectedData3() # print('selected shape', data.shape) transformed = (data -",
".VizItem import VizItem def colors(n): ret = [] r = int(0.5 * 256)",
"data = data.data if data is not None: data = np.squeeze(data) if data",
"self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData() # print('selected",
"not None and len(data.shape) == 0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data,",
"not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0",
"= [] r = int(0.5 * 256) g = int(0.5 * 256) b",
"self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes =",
"int(r) % 256 g = int(g) % 256 b = int(b) % 256",
"self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if self._data is not None: m",
"== 'label': data = self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :], self._range[0],",
"== 0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data,",
"int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data, min, max): from scipy import",
"% 256 ret.append((r,g,b)) return ret def labelViz(data, min, max): from scipy import ndimage",
"= data def dims(self): return self._dims def offsetDims(self): return min(0,self._dims - 2) def",
"if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1]",
"self._vizType = type def vizType(self): return self._vizType def setRange(self, range): self._range = range",
"transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType ==",
"from skimage.color import label2rgb bins = [min] off = min while True: off",
"else: data = None elif isinstance(data, VizItem): self._marks = data.marks data = data.data",
"import ikit.io from ..Util import toQPixmap import numpy as np from ikit.dataops import",
"[1, 2, 0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1]) -",
"= np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data",
"256 ret.append((r,g,b)) return ret def labelViz(data, min, max): from scipy import ndimage from",
"data = np.expand_dims(data, axis=3) elif data is not None and len(data.shape) == 3:",
"axis=3) self._data = data def dims(self): return self._dims def offsetDims(self): return min(0,self._dims -",
"self._offsetAxes = (2, 3) self._dims = None self.setTo(data) def setTo(self, data): if isinstance(data,",
"= data.marks data = data.data if data is not None: data = np.squeeze(data)",
"= int(g) % 256 b = int(b) % 256 ret.append((r,g,b)) return ret def",
"= None self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data",
"ndimage from skimage.color import label2rgb bins = [min] off = min while True:",
"transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return",
"return self._data def image(self): if self._data is None: return None if self._vizType ==",
"def maxCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))])",
"= self.selectedData3() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1])",
"self._vizType == 'heatmap': data = self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data,",
"data = self.selectedData() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) /",
"step b += step r = int(r) % 256 g = int(g) %",
"data = np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 2:",
"m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def selectedData(self): # print('selectedData', self._data.shape,",
"return [] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes)",
"np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data is",
"self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :,",
"data = self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return",
"== 2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data is",
"np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data is not None:",
"'heatmap': data = self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1])",
"b = int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data, min, max): from",
"(data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0",
"= self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self): return",
"# print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0],",
"0 def data(self): return self._data def image(self): if self._data is None: return None",
"- float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif",
"np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def",
"None and len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data = data def",
"1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data",
"n for i in range(n): r += step g += step b +=",
"import heat_map_viz from ikit import read import os import math from copy import",
"if data is not None: data = np.squeeze(data) if data is not None:",
"coding: utf-8 -*- import ikit.io from ..Util import toQPixmap import numpy as np",
"is not None and len(data.shape) == 2: data = np.expand_dims(data, axis=2) data =",
"float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self):",
"not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self): if",
"self._marks = data.marks data = data.data if data is not None: data =",
"256) step = 256 / n for i in range(n): r += step",
"axis=3) elif data is not None and len(data.shape) == 3: data = np.expand_dims(data,",
"is not None and len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data =",
"256 / n for i in range(n): r += step g += step",
"min while True: off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off)",
"<filename>python/iviz/Data/Float.py #!/usr/bin/env python3 #-*- coding: utf-8 -*- import ikit.io from ..Util import toQPixmap",
"[] r = int(0.5 * 256) g = int(0.5 * 256) b =",
"= np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 2: data",
"= label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range = (0.0,",
"def offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type): self._vizType = type def",
"return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes)",
"if self._data is None: return None if self._vizType == 'grayscale': data = self.selectedData()",
"[] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1,",
"from ._Base import _Base from .VizItem import VizItem def colors(n): ret = []",
"off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data,",
"int(0.5 * 256) step = 256 / n for i in range(n): r",
"axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3)",
"if self._dims == 2: return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if",
"= read(data) else: data = None elif isinstance(data, VizItem): self._marks = data.marks data",
"self._offsetAxes) def setOffset(self, offset): if self._dims <= 2: return if isinstance(offset, int): offset",
"import ndimage from skimage.color import label2rgb bins = [min] off = min while",
"'grayscale' self._range = range self._offset = (0, 0) self._plotAxes = (0, 1) self._offsetAxes",
"off = min while True: off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001)",
"return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes =",
"python3 #-*- coding: utf-8 -*- import ikit.io from ..Util import toQPixmap import numpy",
"2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <= 2: return",
"if data is not None and len(data.shape) == 2: data = np.expand_dims(data, axis=2)",
"g = int(g) % 256 b = int(b) % 256 ret.append((r,g,b)) return ret",
"is not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return",
"as np from ikit.dataops import heat_map_viz from ikit import read import os import",
"* 256) step = 256 / n for i in range(n): r +=",
"self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0]))",
"= self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8)",
"np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data is not None and len(data.shape)",
"data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def maxCurrentOffsetValue(self):",
"< 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <= 2:",
"self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def setOffset(self,",
"self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return",
"0) self._plotAxes = (0, 1) self._offsetAxes = (2, 3) self._dims = None self.setTo(data)",
"list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset) def minValue(self): if self._data",
"def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2:",
"shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] =",
"return float(m) else: return 0 def maxValue(self): if self._data is not None: m",
"self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def",
"256 b = int(b) % 256 ret.append((r,g,b)) return ret def labelViz(data, min, max):",
"= type def vizType(self): return self._vizType def setRange(self, range): self._range = range def",
"math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break bins.append(off) digitized = np.digitize(data, bins=bins) color_labeled",
"return min(0,self._dims - 2) def setVizType(self, type): self._vizType = type def vizType(self): return",
"self.selectedData() # print('selected shape', data.shape) transformed = (data - float(self._range[0])) / (float(self._range[1]) -",
"math from copy import copy from ._Base import _Base from .VizItem import VizItem",
"def vizType(self): return self._vizType def setRange(self, range): self._range = range def offsetLimits(self): if",
"bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range",
"data is not None and len(data.shape) == 2: data = np.expand_dims(data, axis=2) data",
"self._dims = None self.setTo(data) def setTo(self, data): if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data):",
"utf-8 -*- import ikit.io from ..Util import toQPixmap import numpy as np from",
"self._plotAxes = (0, 1) self._offsetAxes = (2, 3) self._dims = None self.setTo(data) def",
"-*- import ikit.io from ..Util import toQPixmap import numpy as np from ikit.dataops",
"data = np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 1:",
"self._vizType == 'rgb': data = self.selectedData3() # print('selected shape', data.shape) transformed = (data",
"return float(m) else: return 0 def maxCurrentOffsetValue(self): if self._data is not None: data",
"= np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed",
"type): self._vizType = type def vizType(self): return self._vizType def setRange(self, range): self._range =",
"return 0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes",
"def image(self): if self._data is None: return None if self._vizType == 'grayscale': data",
"= np.expand_dims(data, axis=3) if data is not None and len(data.shape) == 1: data",
"def labelViz(data, min, max): from scipy import ndimage from skimage.color import label2rgb bins",
"transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data =",
"data def dims(self): return self._dims def offsetDims(self): return min(0,self._dims - 2) def setVizType(self,",
"self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self):",
"ret.append((r,g,b)) return ret def labelViz(data, min, max): from scipy import ndimage from skimage.color",
"data is not None and len(data.shape) == 1: data = np.expand_dims(data, axis=1) data",
"self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def",
"is not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return float(m) else: return",
"digitized = np.digitize(data, bins=bins) color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def",
"transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2,",
"len(data.shape) else: self._dims = 0 if data is not None and len(data.shape) ==",
"self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is not",
"2) def setVizType(self, type): self._vizType = type def vizType(self): return self._vizType def setRange(self,",
"self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :]",
"self.selectedData() # print('selected shape', data.shape) heatmap = heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif",
"+= step g += step b += step r = int(r) % 256",
"0 def selectedData(self): # print('selectedData', self._data.shape, self._offsetAxes, self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes +",
"self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data,",
"None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def",
"None and len(data.shape) == 2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3)",
"== 'grayscale': data = self.selectedData() # print('selected shape', data.shape) transformed = (data -",
"[self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:]",
"b += step r = int(r) % 256 g = int(g) % 256",
"minCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m = np.min(data[np.logical_not(np.isnan(data))]) return",
"not None and len(data.shape) == 2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data,",
"1: data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3)",
"return if isinstance(offset, int): offset = [offset, 0] self._offset = list(copy(offset)) while(len(self._offset) <",
"print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <= 2: return if isinstance(offset, int):",
"return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return",
"= int(0.5 * 256) step = 256 / n for i in range(n):",
":, :], [1, 2, 0]) def scaledSelectedData(self): transformed = (self._data - float(self._range[0])) /",
"colors(n): ret = [] r = int(0.5 * 256) g = int(0.5 *",
"[offset, 0] self._offset = list(copy(offset)) while(len(self._offset) < 2): self._offset.append(0) # print('offsets set', self._offset)",
"import VizItem def colors(n): ret = [] r = int(0.5 * 256) g",
"None: data = np.squeeze(data) if data is not None: self._dims = len(data.shape) else:",
":]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData() # print('selected shape', data.shape) heatmap",
"import _Base from .VizItem import VizItem def colors(n): ret = [] r =",
"from ikit.dataops import heat_map_viz from ikit import read import os import math from",
"np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data = np.expand_dims(data,",
"ret def labelViz(data, min, max): from scipy import ndimage from skimage.color import label2rgb",
"self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while",
"self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data is not None: data",
"import label2rgb bins = [min] off = min while True: off = math.ceil(off)",
"np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def selectedData3(self): transposed =",
"# print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid viztype')",
"= 1 transformed[transformed<0] = 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap':",
"0 return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3() # print('selected",
"float(m) else: return 0 def maxValue(self): if self._data is not None: m =",
"range def offsetLimits(self): if self._dims == 2: return [] if self._dims == 3:",
"= min while True: off = math.ceil(off) + 0.5 if off>=max: bins.append(max+0.000001) break",
"self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data = None elif isinstance(data, VizItem):",
"return [self._data.shape[self._offsetAxes[0]]-1] if self._dims == 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self,",
":, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData() # print('selected shape', data.shape)",
"return 0 def maxValue(self): if self._data is not None: m = np.max(self._data[np.logical_not(np.isnan(self._data))]) return",
"g = int(0.5 * 256) b = int(0.5 * 256) step = 256",
"<= 2: return if isinstance(offset, int): offset = [offset, 0] self._offset = list(copy(offset))",
"4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes",
"if isinstance(data, str): self._tryReadMarks(data) if os.path.exists(data): data = read(data) else: data = None",
"r += step g += step b += step r = int(r) %",
"data = None elif isinstance(data, VizItem): self._marks = data.marks data = data.data if",
"float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset,",
"self._dims def offsetDims(self): return min(0,self._dims - 2) def setVizType(self, type): self._vizType = type",
"= self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise",
"class Float(_Base): def __init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType =",
"self._vizType == 'label': data = self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :],",
"self._offset[1], :, :] def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3,",
"= np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) if data is not None and",
"# print('offsets set', self._offset) def minValue(self): if self._data is not None: m =",
"data = self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else:",
"/ (float(self._range[1]) - float(self._range[0])) transformed[transformed>1] = 1 transformed[transformed<0] = 0 return (transformed[:, :]*255.0).astype(np.uint8)",
"scipy import ndimage from skimage.color import label2rgb bins = [min] off = min",
"= np.transpose(transformed, self._offsetAxes + self._plotAxes) return transposed[self._offset, :, :] def minCurrentOffsetValue(self): if self._data",
"self._vizType def setRange(self, range): self._range = range def offsetLimits(self): if self._dims == 2:",
"[] def setAxes(self, axes): self._plotAxes = axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) <",
"return 0 def data(self): return self._data def image(self): if self._data is None: return",
"import read import os import math from copy import copy from ._Base import",
"image(self): if self._data is None: return None if self._vizType == 'grayscale': data =",
"VizItem): self._marks = data.marks data = data.data if data is not None: data",
"import os import math from copy import copy from ._Base import _Base from",
"__init__(self, data=None, range = (0.0, 1.0), marks=None): super().__init__(marks) self._vizType = 'grayscale' self._range =",
"= 0 return (transformed[:, :, :]*255.0).astype(np.uint8) elif self._vizType == 'heatmap': data = self.selectedData()",
"0 def maxCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m =",
"= heat_map_viz(data, self._range[0], self._range[1]) return heatmap.astype(np.uint8) elif self._vizType == 'label': data = self.selectedData()",
"color_labeled = label2rgb(digitized, bg_label=0) return (color_labeled*255).astype(np.uint8) class Float(_Base): def __init__(self, data=None, range =",
"not None and len(data.shape) == 3: data = np.expand_dims(data, axis=3) self._data = data",
"len(data.shape) == 2: data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data",
"== 4: return [self._data.shape[self._offsetAxes[0]]-1, self._data.shape[self._offsetAxes[1]]-1] return [] def setAxes(self, axes): self._plotAxes = axes[0:2]",
"= np.expand_dims(data, axis=3) self._data = data def dims(self): return self._dims def offsetDims(self): return",
"data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data = np.expand_dims(data, axis=2) data",
":]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3() # print('selected shape', data.shape) transformed",
"= 0 if data is not None and len(data.shape) == 0: data =",
"self._dims == 2: return [] if self._dims == 3: return [self._data.shape[self._offsetAxes[0]]-1] if self._dims",
"self._vizType == 'grayscale': data = self.selectedData() # print('selected shape', data.shape) transformed = (data",
"return 0 def maxCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m",
"= np.squeeze(data) if data is not None: self._dims = len(data.shape) else: self._dims =",
"print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid viztype') def",
"and len(data.shape) == 0: data = np.expand_dims(data, axis=0) data = np.expand_dims(data, axis=1) data",
"def minValue(self): if self._data is not None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else:",
":, :] def minCurrentOffsetValue(self): if self._data is not None: data = self.selectedData() m",
"return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :], [1, 2, 0]) def scaledSelectedData(self): transformed = (self._data",
"return (transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3() # print('selected shape',",
"self._data is not None: data = self.selectedData() m = np.max(data[np.logical_not(np.isnan(data))]) return float(m) else:",
"# print(self._plotAxes, self._offsetAxes) def setOffset(self, offset): if self._dims <= 2: return if isinstance(offset,",
"None: m = np.min(self._data[np.logical_not(np.isnan(self._data))]) return float(m) else: return 0 def maxValue(self): if self._data",
"scaledSelectedData(self): transformed = (self._data - float(self._range[0])) / (float(self._range[1]) - float(self._range[0])) transposed = np.transpose(transformed,",
"self._plotAxes) transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return transposed[self._offset[0], self._offset[1], :, :] def",
"def selectedData3(self): transposed = np.transpose(self._data, self._offsetAxes + self._plotAxes) return np.transpose(transposed[self._offset[0]:self._offset[0]+3, self._offset[1], :, :],",
"= np.max(data[np.logical_not(np.isnan(data))]) return float(m) else: return 0 def data(self): return self._data def image(self):",
"if data is not None and len(data.shape) == 0: data = np.expand_dims(data, axis=0)",
"copy import copy from ._Base import _Base from .VizItem import VizItem def colors(n):",
"step = 256 / n for i in range(n): r += step g",
"data = np.expand_dims(data, axis=2) data = np.expand_dims(data, axis=3) elif data is not None",
"axes[0:2] self._offsetAxes = axes[2:] while len(self._offsetAxes) < 2: self._offsetAxes.append(len(self._offsetAxes)+2) # print(self._plotAxes, self._offsetAxes) def",
"self.selectedData() # print('selected shape', data.shape) return labelViz(data[:, :], self._range[0], self._range[1]) else: raise Exception('invalid",
"data.data if data is not None: data = np.squeeze(data) if data is not",
"(transformed[:, :]*255.0).astype(np.uint8) elif self._vizType == 'rgb': data = self.selectedData3() # print('selected shape', data.shape)",
"range): self._range = range def offsetLimits(self): if self._dims == 2: return [] if"
] |
[
"django.db import models class KokamaHistory(models.Model): history_title = models.CharField(max_length=50) history_text = models.TextField() def __str__(self):",
"import models class KokamaHistory(models.Model): history_title = models.CharField(max_length=50) history_text = models.TextField() def __str__(self): return",
"from django.db import models class KokamaHistory(models.Model): history_title = models.CharField(max_length=50) history_text = models.TextField() def",
"<filename>history/models.py from django.db import models class KokamaHistory(models.Model): history_title = models.CharField(max_length=50) history_text = models.TextField()",
"models class KokamaHistory(models.Model): history_title = models.CharField(max_length=50) history_text = models.TextField() def __str__(self): return self.history_title"
] |
[
"[ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on a",
"migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations",
"a category. This will\\n override the tags that you choose and will filter",
"blank=True, help_text=\"\\n Limit recent articles based on tags. This is the \\n first",
"are returned and will be overriden\\n if you also select a category.\\n \",",
"can filter the\\n articles more using the fields below\\n \", ), ), migrations.AlterField(",
"on 2020-11-11 08:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies",
"field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on a category. This will\\n override",
"will decide how many articles to return. By\\n default this plugin will return",
"on when they were created. You can filter the\\n articles more using the",
"\"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent",
"what articles are returned and will be overriden\\n if you also select a",
"be overriden\\n if you also select a category.\\n \", to=\"news.ArticleTag\", ), ), ]",
"operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based",
"Django 2.2 on 2020-11-11 08:09 from django.db import migrations, models import django.db.models.deletion class",
"based on a category. This will\\n override the tags that you choose and",
"based on tags. This is the \\n first priority in what articles are",
"and will filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ),",
"decide how many articles to return. By\\n default this plugin will return this",
"), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on tags.",
"this number articles\\n based on when they were created. You can filter the\\n",
"return. By\\n default this plugin will return this number articles\\n based on when",
"help_text=\"\\n Limit recent articles based on a category. This will\\n override the tags",
"category. This will\\n override the tags that you choose and will filter on",
"model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many articles to return.",
"that you choose and will filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL,",
"plugin will return this number articles\\n based on when they were created. You",
"return this number articles\\n based on when they were created. You can filter",
"when they were created. You can filter the\\n articles more using the fields",
"Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\",",
"using the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n",
"on tags. This is the \\n first priority in what articles are returned",
"will\\n override the tags that you choose and will filter on this category\\n",
"is the \\n first priority in what articles are returned and will be",
"articles\\n based on when they were created. You can filter the\\n articles more",
"name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many articles to return. By\\n",
"ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n",
"(\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit",
"This will decide how many articles to return. By\\n default this plugin will",
"# Generated by Django 2.2 on 2020-11-11 08:09 from django.db import migrations, models",
"below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles",
"this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField(",
"), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many articles",
"tags that you choose and will filter on this category\\n ONLY.\\n \", null=True,",
"= [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on",
"model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on a category. This",
"field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on tags. This is the \\n",
"blank=True, help_text=\"\\n Limit recent articles based on a category. This will\\n override the",
"override the tags that you choose and will filter on this category\\n ONLY.\\n",
"filter the\\n articles more using the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\",",
"articles based on tags. This is the \\n first priority in what articles",
"field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many articles to return. By\\n default",
"more using the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True,",
"), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many",
"to return. By\\n default this plugin will return this number articles\\n based on",
"Generated by Django 2.2 on 2020-11-11 08:09 from django.db import migrations, models import",
"2.2 on 2020-11-11 08:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):",
"class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\",",
"articles to return. By\\n default this plugin will return this number articles\\n based",
"this plugin will return this number articles\\n based on when they were created.",
"migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how many articles to",
"default this plugin will return this number articles\\n based on when they were",
"number articles\\n based on when they were created. You can filter the\\n articles",
"they were created. You can filter the\\n articles more using the fields below\\n",
"help_text=\"\\n Limit recent articles based on tags. This is the \\n first priority",
"django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"),",
"will filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField(",
"from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\",",
"This will\\n override the tags that you choose and will filter on this",
"category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3,",
"<filename>news/migrations/0006_auto_20201111_0809.py # Generated by Django 2.2 on 2020-11-11 08:09 from django.db import migrations,",
"in what articles are returned and will be overriden\\n if you also select",
"default=3, help_text=\"\\n This will decide how many articles to return. By\\n default this",
"how many articles to return. By\\n default this plugin will return this number",
"name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on tags. This is the",
"\", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This",
"the\\n articles more using the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\",",
"migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on tags. This",
"created. You can filter the\\n articles more using the fields below\\n \", ),",
"on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide",
"recent articles based on tags. This is the \\n first priority in what",
"By\\n default this plugin will return this number articles\\n based on when they",
"articles based on a category. This will\\n override the tags that you choose",
"returned and will be overriden\\n if you also select a category.\\n \", to=\"news.ArticleTag\",",
"on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\",",
"many articles to return. By\\n default this plugin will return this number articles\\n",
"and will be overriden\\n if you also select a category.\\n \", to=\"news.ArticleTag\", ),",
"dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey(",
"\", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based",
"Limit recent articles based on a category. This will\\n override the tags that",
"[ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n",
"), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on",
"import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [",
"null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will",
"08:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [",
"you choose and will filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\",",
"on a category. This will\\n override the tags that you choose and will",
"import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ]",
"recent articles based on a category. This will\\n override the tags that you",
"will return this number articles\\n based on when they were created. You can",
"choose and will filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ),",
"first priority in what articles are returned and will be overriden\\n if you",
"based on when they were created. You can filter the\\n articles more using",
"django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField(",
"were created. You can filter the\\n articles more using the fields below\\n \",",
"migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on a category.",
"the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit",
"articles are returned and will be overriden\\n if you also select a category.\\n",
"This is the \\n first priority in what articles are returned and will",
"filter on this category\\n ONLY.\\n \", null=True, on_delete=django.db.models.deletion.SET_NULL, to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\",",
"You can filter the\\n articles more using the fields below\\n \", ), ),",
"] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles",
"the tags that you choose and will filter on this category\\n ONLY.\\n \",",
"tags. This is the \\n first priority in what articles are returned and",
"models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations =",
"= [ (\"news\", \"0005_relatedarticlecardplugin_relatedarticleplugin\"), ] operations = [ migrations.AddField( model_name=\"relatedarticleplugin\", name=\"category\", field=models.ForeignKey( blank=True,",
"Limit recent articles based on tags. This is the \\n first priority in",
"will be overriden\\n if you also select a category.\\n \", to=\"news.ArticleTag\", ), ),",
"name=\"category\", field=models.ForeignKey( blank=True, help_text=\"\\n Limit recent articles based on a category. This will\\n",
"\\n first priority in what articles are returned and will be overriden\\n if",
"model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent articles based on tags. This is",
"2020-11-11 08:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies =",
"priority in what articles are returned and will be overriden\\n if you also",
"by Django 2.2 on 2020-11-11 08:09 from django.db import migrations, models import django.db.models.deletion",
"fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField( blank=True, help_text=\"\\n Limit recent",
"the \\n first priority in what articles are returned and will be overriden\\n",
"articles more using the fields below\\n \", ), ), migrations.AlterField( model_name=\"relatedarticleplugin\", name=\"tags\", field=models.ManyToManyField(",
"to=\"news.Category\", ), ), migrations.AddField( model_name=\"relatedarticleplugin\", name=\"num_articles\", field=models.PositiveIntegerField( default=3, help_text=\"\\n This will decide how",
"help_text=\"\\n This will decide how many articles to return. By\\n default this plugin"
] |
[
"= 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.')",
"+ '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json'",
"fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] ))",
"os import shutil import json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts')",
"'../../docs/news' news_posts = [] for fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath",
"def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for",
"frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname =",
"import shutil import json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath",
"fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict(",
"fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content']",
"json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts",
"if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for fname in",
"python import os import shutil import json import frontmatter def main(): if os.path.exists('news_posts'):",
"import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts =",
"= '../../docs/news' news_posts = [] for fname in os.listdir(newspath): if fname.endswith('.md'): fm =",
"'/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing",
"news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with",
"frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = []",
"print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.') if __name__",
"import json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news'",
"import os import shutil import json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts')",
"[] for fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' +",
"= frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname",
"+ fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to",
"{}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.') if __name__ == \"__main__\":",
"= [] for fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/'",
"os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for fname in os.listdir(newspath): if fname.endswith('.md'):",
"main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for fname",
"in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'],",
"author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as",
")) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts,",
"<reponame>flatironinstitute/spikeforest_old<gh_stars>1-10 #!/usr/bin/env python import os import shutil import json import frontmatter def main():",
"shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for fname in os.listdir(newspath): if",
"os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(),",
"os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath = '../../docs/news' news_posts = [] for fname in os.listdir(newspath):",
"shutil import json import frontmatter def main(): if os.path.exists('news_posts'): shutil.rmtree('news_posts') os.mkdir('news_posts') newspath =",
"if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'],",
"markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f:",
"out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f)",
"fname).to_dict() news_posts.append(dict( title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname))",
"date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w')",
"title=fm['title'], date=fm['date'].isoformat(), author=fm['author'], markdown=fm['content'] )) out_fname = 'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname,",
"'news_posts/NewsPosts.json' print('Writing to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.') if",
"news_posts = [] for fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath +",
"to {}'.format(out_fname)) with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.') if __name__ ==",
"with open(out_fname, 'w') as f: json.dump(news_posts, f) print('Done.') if __name__ == \"__main__\": main()",
"newspath = '../../docs/news' news_posts = [] for fname in os.listdir(newspath): if fname.endswith('.md'): fm",
"#!/usr/bin/env python import os import shutil import json import frontmatter def main(): if",
"for fname in os.listdir(newspath): if fname.endswith('.md'): fm = frontmatter.load(newspath + '/' + fname).to_dict()"
] |
[
"return None if img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type",
"[video_url], \"ext\": None, \"size\": None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if",
"= { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type): html =",
"def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if",
"r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data =",
"type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext,",
"random import re import urllib.parse from app.spider_store.common import ( match1, get_content, ) from",
"size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = { \"type\": type, \"title\":",
"= _type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024))",
"if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source =",
"return \"video\" download = ku6_download if __name__ == '__main__': url = \"https://www.ku6.com/video/detail?id=gRJ4Q0LnmBx7IzxAI019mjiDMMA.\" data",
"r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str,",
"\"size\": size, } return data def ku6_download(url): html = get_content(url) type = news_type(url)",
"src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url],",
"if source is None: return None if img_url is None: img_url = match1(html,",
"1024)) data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\":",
"source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)')",
"None, \"size\": None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url):",
"title is None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is",
"\"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None, } return data",
"None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\"",
"urllib.parse from app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers",
"random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id)",
"r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip()",
"img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html,",
"/ 1024 / 1024)) data = { \"type\": type, \"title\": title, \"source\": source,",
"[video_url], \"ext\": ext, \"size\": size, } return data def ku6_download(url): html = get_content(url)",
"None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None: return",
"video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title,",
"return data def ku6_download(url): html = get_content(url) type = news_type(url) title = match1(html,",
"import logging import random import re import urllib.parse from app.spider_store.common import ( match1,",
"r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url",
"title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html,",
"= match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html,",
"\"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None, }",
"None: return None if img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext =",
"float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = { \"type\": type, \"title\": title, \"source\":",
"get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title",
"import ( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent':",
"match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip()",
"= match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\":",
"news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if __name__",
"} return data def ku6_download(url): html = get_content(url) type = news_type(url) title =",
"= match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type)",
"dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url))",
"data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None,",
"FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type):",
"logging.debug(\"url is {}\".format(video_url)) if title is None: title = match1(html, r'&title=([^&]*)') title =",
"source is None: return None if img_url is None: img_url = match1(html, r'&video_img=([^&]*)')",
"_*_ import logging import random import re import urllib.parse from app.spider_store.common import (",
"source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src:",
"\"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\":",
"headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type): html",
"None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, } return data def ku6_download(url): html",
"return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download =",
"urllib.parse.unquote(title) if source is None: return None if img_url is None: img_url =",
"app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers = {",
"} return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download",
"size, } return data def ku6_download(url): html = get_content(url) type = news_type(url) title",
"int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = { \"type\":",
"match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type,",
"r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024",
"= { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\":",
"from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title,",
"match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) /",
"type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title =",
"match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data",
"\"ext\": None, \"size\": None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\",",
"= ku6_download if __name__ == '__main__': url = \"https://www.ku6.com/video/detail?id=gRJ4Q0LnmBx7IzxAI019mjiDMMA.\" data = download(url) print(data)",
"# _*_ codingLUTF-8 _*_ import logging import random import re import urllib.parse from",
"[img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None, } return data def",
"html = get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is",
"is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\")",
"img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = {",
"type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None,",
"def ku6_download(url): html = get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if",
"codingLUTF-8 _*_ import logging import random import re import urllib.parse from app.spider_store.common import",
"'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html,",
"\"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None, } return data def news_type(url):",
"data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download",
"download = ku6_download if __name__ == '__main__': url = \"https://www.ku6.com/video/detail?id=gRJ4Q0LnmBx7IzxAI019mjiDMMA.\" data = download(url)",
"= match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None: return None if",
"= 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is None: title",
"\"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, } return data def ku6_download(url):",
"= match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);')",
"from app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers =",
"vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is None: title = match1(html, r'&title=([^&]*)')",
"} def baomihua_download_by_id(_id, title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) )",
"is {}\".format(video_url)) if title is None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title)",
"r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source",
"ku6_download(url): html = get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title",
"title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None: return None",
"= news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html,",
"is None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None:",
"title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url =",
"data def ku6_download(url): html = get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\")",
"r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is",
"import random import re import urllib.parse from app.spider_store.common import ( match1, get_content, )",
"match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html,",
"size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data =",
"img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type",
"= match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title =",
"\"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\":",
"source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, } return",
"if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if __name__ == '__main__': url",
"( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT)",
"is None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)'))",
"baomihua_download_by_id(_id, title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host =",
"title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url =",
"r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\":",
"None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size",
"\"video_url\": [video_url], \"ext\": None, \"size\": None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg.",
"/ 1024)) data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url],",
"\"video\" download = ku6_download if __name__ == '__main__': url = \"https://www.ku6.com/video/detail?id=gRJ4Q0LnmBx7IzxAI019mjiDMMA.\" data =",
"import urllib.parse from app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT",
"_type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url",
"\"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, }",
"[img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, } return data def",
"title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size,",
"\"ext\": ext, \"size\": size, } return data def ku6_download(url): html = get_content(url) type",
"<reponame>lihaoABC/trans_api # _*_ codingLUTF-8 _*_ import logging import random import re import urllib.parse",
"app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source,",
"\"size\": None, } return data def news_type(url): # https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return",
"re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if __name__ == '__main__': url =",
"get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid",
"= match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size)",
"None if img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type size",
"get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def",
") from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id,",
"title = urllib.parse.unquote(title) if source is None: return None if img_url is None:",
"if title is None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source",
"\"video_url\": [video_url], \"ext\": ext, \"size\": size, } return data def ku6_download(url): html =",
"{ 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type): html = get_content(",
"'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype='",
"= int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = {",
"= match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if",
"[\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\":",
"r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\":",
"title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title",
"match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None: return None if img_url",
"r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is",
"url): return \"video\" download = ku6_download if __name__ == '__main__': url = \"https://www.ku6.com/video/detail?id=gRJ4Q0LnmBx7IzxAI019mjiDMMA.\"",
"= get_content(url) type = news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None:",
"html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type = match1(html,",
"import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) } def baomihua_download_by_id(_id, title, source, img_url,",
"\"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\":",
"ext, \"size\": size, } return data def ku6_download(url): html = get_content(url) type =",
"= float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = { \"type\": type, \"title\": title,",
"type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type =",
"title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None,",
"re import urllib.parse from app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs import",
"host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str",
"= match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title, \"source\":",
"match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"], src: [\\'|\"](.*?)[\\'|\"]}\\);') data = { \"type\": type, \"title\": title, \"source\": source,",
"= urllib.parse.unquote(title) if source is None: return None if img_url is None: img_url",
"dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is None: title = match1(html,",
"{ \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url],",
"= title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html,",
"source, \"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": None, \"size\": None, } return",
"news_type(url) title = match1(html, r\"\\$\\(['\\\"]#video-title['\\\"]\\)\\.text\\(['\\\"]([\\s\\S\\w\\W]+?)['\\\"]\\);\") if title is None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\")",
"def baomihua_download_by_id(_id, title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host",
"'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid =",
"img_url = match1(html, r'&video_img=([^&]*)') ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size =",
"match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:')",
"title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url = match1(html, r'[\\'|\"]poster[\\'|\"]:\\s*[\\'|\"](.*?)[\\'|\"],\\s*[\\'|\"]controls[\\'|\"]:') video_url = match1(html, r'this\\.src\\(\\{type:\\s*[\\'|\"]video/mp4[\\'|\"],",
"video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is None:",
"match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title",
"'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url is {}\".format(video_url)) if title is None: title =",
"match1, get_content, ) from app.spider_store.configs import FAKE_USER_AGENT headers = { 'user-agent': random.choice(FAKE_USER_AGENT) }",
"= get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)')",
"is None: return None if img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext",
"= match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url =",
"None: title = match1(html, r\"document\\.title\\s*=\\s*['\\\"]([\\s\\S\\w\\W]+?)['\\\"];\") title = title.strip() source = match1(html, r\"\\$\\(['\\\"]#video-author['\\\"]\\)\\.text\\(['\\\"](.*?)['\\\"]\\);\") img_url",
"None, \"video_url\": [video_url], \"ext\": None, \"size\": None, } return data def news_type(url): #",
") host = match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)')",
"if img_url is None: img_url = match1(html, r'&video_img=([^&]*)') ext = _type size =",
"_type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data",
"match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host,",
"match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid, _type) logging.debug(\"url",
"title, source, img_url, type): html = get_content( 'http://play.baomihua.com/getvideourl.aspx?flvid={}&devicetype=' 'phone_app'.format(_id) ) host = match1(html,",
"import re import urllib.parse from app.spider_store.common import ( match1, get_content, ) from app.spider_store.configs",
"= match1(html, r'host=([^&]*)') _type = match1(html, r'videofiletype=([^&]*)') vid = match1(html, r'&stream_name=([^&]*)') dir_str =",
"{}\".format(video_url)) if title is None: title = match1(html, r'&title=([^&]*)') title = urllib.parse.unquote(title) if",
"ext = _type size = int(match1(html, r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 /",
"1024 / 1024)) data = { \"type\": type, \"title\": title, \"source\": source, \"thumbnail_urls\":",
"\"thumbnail_urls\": [img_url], \"image_urls\": None, \"video_url\": [video_url], \"ext\": ext, \"size\": size, } return data",
"https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if __name__ == '__main__':",
"r'&title=([^&]*)') title = urllib.parse.unquote(title) if source is None: return None if img_url is",
"r'&videofilesize=([^&]*)')) size = float(\"{:.2f}\".format(int(size) / 1024 / 1024)) data = { \"type\": type,",
"_*_ codingLUTF-8 _*_ import logging import random import re import urllib.parse from app.spider_store.common",
"logging import random import re import urllib.parse from app.spider_store.common import ( match1, get_content,",
"_type) logging.debug(\"url is {}\".format(video_url)) if title is None: title = match1(html, r'&title=([^&]*)') title",
"vid = match1(html, r'&stream_name=([^&]*)') dir_str = match1(html, r'&dir=([^&]*)').strip() video_url = 'http://{}/{}/{}.{}'.format(host, dir_str, vid,",
"# https://www.ku6.com/video/detail?id=4Oqd5_XQsCDtJU7HMjHRD4nrgAg. if re.search(r\"http[s]?://www\\.ku6\\.com/video/detail\\?id=.*?$\", url): return \"video\" download = ku6_download if __name__ =="
] |
[
"(linear kernel) by returning the index with highest kernel output (confidence). \"\"\" class",
"by returning the index with highest kernel output (confidence). \"\"\" class NLPSearch: def",
"a substring, search an array of strings by cosine simularity (linear kernel) by",
"\"\"\" class NLPSearch: def __init__(self): pass def process_data(self): pass def create_model(self): pass def",
"returning the index with highest kernel output (confidence). \"\"\" class NLPSearch: def __init__(self):",
"substring, search an array of strings by cosine simularity (linear kernel) by returning",
"index with highest kernel output (confidence). \"\"\" class NLPSearch: def __init__(self): pass def",
"output (confidence). \"\"\" class NLPSearch: def __init__(self): pass def process_data(self): pass def create_model(self):",
"cosine simularity (linear kernel) by returning the index with highest kernel output (confidence).",
"the index with highest kernel output (confidence). \"\"\" class NLPSearch: def __init__(self): pass",
"simularity (linear kernel) by returning the index with highest kernel output (confidence). \"\"\"",
"Given a substring, search an array of strings by cosine simularity (linear kernel)",
"of strings by cosine simularity (linear kernel) by returning the index with highest",
"an array of strings by cosine simularity (linear kernel) by returning the index",
"by cosine simularity (linear kernel) by returning the index with highest kernel output",
"NLPSearch: def __init__(self): pass def process_data(self): pass def create_model(self): pass def train_model(self): pass",
"process_data(self): pass def create_model(self): pass def train_model(self): pass def prompt(self, prompt): pass if",
"def train_model(self): pass def prompt(self, prompt): pass if __name__ == \"__main__\": search =",
"(confidence). \"\"\" class NLPSearch: def __init__(self): pass def process_data(self): pass def create_model(self): pass",
"search an array of strings by cosine simularity (linear kernel) by returning the",
"def create_model(self): pass def train_model(self): pass def prompt(self, prompt): pass if __name__ ==",
"create_model(self): pass def train_model(self): pass def prompt(self, prompt): pass if __name__ == \"__main__\":",
"class NLPSearch: def __init__(self): pass def process_data(self): pass def create_model(self): pass def train_model(self):",
"pass def create_model(self): pass def train_model(self): pass def prompt(self, prompt): pass if __name__",
"with highest kernel output (confidence). \"\"\" class NLPSearch: def __init__(self): pass def process_data(self):",
"highest kernel output (confidence). \"\"\" class NLPSearch: def __init__(self): pass def process_data(self): pass",
"train_model(self): pass def prompt(self, prompt): pass if __name__ == \"__main__\": search = NLPSearch()",
"def __init__(self): pass def process_data(self): pass def create_model(self): pass def train_model(self): pass def",
"strings by cosine simularity (linear kernel) by returning the index with highest kernel",
"pass def process_data(self): pass def create_model(self): pass def train_model(self): pass def prompt(self, prompt):",
"pass def train_model(self): pass def prompt(self, prompt): pass if __name__ == \"__main__\": search",
"\"\"\" Given a substring, search an array of strings by cosine simularity (linear",
"kernel output (confidence). \"\"\" class NLPSearch: def __init__(self): pass def process_data(self): pass def",
"__init__(self): pass def process_data(self): pass def create_model(self): pass def train_model(self): pass def prompt(self,",
"def process_data(self): pass def create_model(self): pass def train_model(self): pass def prompt(self, prompt): pass",
"kernel) by returning the index with highest kernel output (confidence). \"\"\" class NLPSearch:",
"array of strings by cosine simularity (linear kernel) by returning the index with"
] |
[
"time traveling Europe and around the city. Combine with my study in the",
"that I enjoy learning. Similarly, by taking part in the engineering \" def",
"ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] # The text to analyze text",
"client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] # The",
"in the spring of 2018 and Tokyo, Japan in the summer of 2017.",
"of 2017. While taking classes offered at both TU Dresden and Tokyo tech,",
"to quickly adapt to changes in the environment and apply my ability in",
"Similarly, by taking part in the engineering \" def gapiAnalysisText(text): document = types.Document(",
"While taking classes offered at both TU Dresden and Tokyo tech, I spent",
"apply my ability in a different context. My passion for electronics and computers",
"language from google.cloud.language import enums from google.cloud.language import types # Instantiates a client",
"traveling was what prompted me to take part in the study aboard program",
"and computers is also what prompts me to join the High-Performance Computing (HPC)",
"Dresden and Tokyo tech, I spent most of my off time traveling Europe",
"passion for electronics and computers is also what prompts me to join the",
"for electronics and computers is also what prompts me to join the High-Performance",
"and continue to be an active member of the university maker space. My",
"take part in the leadership role of the BUHPC contained more than my",
"work, my passion for traveling was what prompted me to take part in",
"types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through",
"# Imports the Google Cloud client library from google.cloud import language from google.cloud.language",
"from the API key_words=list() for entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE):",
"the States, I believe that it is these experiences that taught me how",
"Computing (HPC) club and continue to be an active member of the university",
"content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites",
"from google.cloud.language import enums from google.cloud.language import types # Instantiates a client client",
"the engineering \" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8",
"a subject that I enjoy learning. Similarly, by taking part in the engineering",
"wish to inspire others learning about HPC by sharing a subject that I",
"I wish to inspire others learning about HPC by sharing a subject that",
"returned from the API key_words=list() for entity in response.entities: if (entity.type not in",
"traveling Europe and around the city. Combine with my study in the States,",
"of the BUHPC contained more than my interest in the subject matter; I",
"take part in the study aboard program in Dresden, Germany, in the spring",
"9, 10, 11, 12] # The text to analyze text = \"Aside from",
"spring of 2018 and Tokyo, Japan in the summer of 2017. While taking",
"space. My decision to take part in the leadership role of the BUHPC",
"changes in the environment and apply my ability in a different context. My",
"(HPC) club and continue to be an active member of the university maker",
"active member of the university maker space. My decision to take part in",
"to analyze text = \"Aside from course work, my passion for traveling was",
"summer of 2017. While taking classes offered at both TU Dresden and Tokyo",
"of my off time traveling Europe and around the city. Combine with my",
"in the States, I believe that it is these experiences that taught me",
"join the High-Performance Computing (HPC) club and continue to be an active member",
"the summer of 2017. While taking classes offered at both TU Dresden and",
"the leadership role of the BUHPC contained more than my interest in the",
"sharing a subject that I enjoy learning. Similarly, by taking part in the",
"in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort() return \",\".join(map(str,key_words)) char_str=",
"and Tokyo, Japan in the summer of 2017. While taking classes offered at",
"BUHPC contained more than my interest in the subject matter; I wish to",
"prompts me to join the High-Performance Computing (HPC) club and continue to be",
"of the university maker space. My decision to take part in the leadership",
"it is these experiences that taught me how to quickly adapt to changes",
"what prompts me to join the High-Performance Computing (HPC) club and continue to",
"2018 and Tokyo, Japan in the summer of 2017. While taking classes offered",
"environment and apply my ability in a different context. My passion for electronics",
"to be an active member of the university maker space. My decision to",
"google.cloud.language import types # Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8,",
"HPC by sharing a subject that I enjoy learning. Similarly, by taking part",
"subject that I enjoy learning. Similarly, by taking part in the engineering \"",
"role of the BUHPC contained more than my interest in the subject matter;",
"Dresden, Germany, in the spring of 2018 and Tokyo, Japan in the summer",
"12] # The text to analyze text = \"Aside from course work, my",
"for traveling was what prompted me to take part in the study aboard",
"what prompted me to take part in the study aboard program in Dresden,",
"in Dresden, Germany, in the spring of 2018 and Tokyo, Japan in the",
"adapt to changes in the environment and apply my ability in a different",
"is also what prompts me to join the High-Performance Computing (HPC) club and",
"prompted me to take part in the study aboard program in Dresden, Germany,",
"from course work, my passion for traveling was what prompted me to take",
"believe that it is these experiences that taught me how to quickly adapt",
"of 2018 and Tokyo, Japan in the summer of 2017. While taking classes",
"be an active member of the university maker space. My decision to take",
"in the subject matter; I wish to inspire others learning about HPC by",
"most of my off time traveling Europe and around the city. Combine with",
"enjoy learning. Similarly, by taking part in the engineering \" def gapiAnalysisText(text): document",
"in the engineering \" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type =",
"I enjoy learning. Similarly, by taking part in the engineering \" def gapiAnalysisText(text):",
"10, 11, 12] # The text to analyze text = \"Aside from course",
"in the leadership role of the BUHPC contained more than my interest in",
"type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned",
"aboard program in Dresden, Germany, in the spring of 2018 and Tokyo, Japan",
"a different context. My passion for electronics and computers is also what prompts",
"the subject matter; I wish to inspire others learning about HPC by sharing",
"than my interest in the subject matter; I wish to inspire others learning",
"# Loop through entitites returned from the API key_words=list() for entity in response.entities:",
"ability in a different context. My passion for electronics and computers is also",
"= language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] # The text to",
"experiences that taught me how to quickly adapt to changes in the environment",
"taught me how to quickly adapt to changes in the environment and apply",
"Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12]",
"with my study in the States, I believe that it is these experiences",
"to take part in the study aboard program in Dresden, Germany, in the",
"High-Performance Computing (HPC) club and continue to be an active member of the",
"\"Aside from course work, my passion for traveling was what prompted me to",
"and Tokyo tech, I spent most of my off time traveling Europe and",
"My passion for electronics and computers is also what prompts me to join",
"and apply my ability in a different context. My passion for electronics and",
"entitites returned from the API key_words=list() for entity in response.entities: if (entity.type not",
"for entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort() return",
"2017. While taking classes offered at both TU Dresden and Tokyo tech, I",
"my interest in the subject matter; I wish to inspire others learning about",
"more than my interest in the subject matter; I wish to inspire others",
"the High-Performance Computing (HPC) club and continue to be an active member of",
"decision to take part in the leadership role of the BUHPC contained more",
"me to take part in the study aboard program in Dresden, Germany, in",
"the BUHPC contained more than my interest in the subject matter; I wish",
"language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] # The text to analyze",
"leadership role of the BUHPC contained more than my interest in the subject",
"quickly adapt to changes in the environment and apply my ability in a",
"the environment and apply my ability in a different context. My passion for",
"interest in the subject matter; I wish to inspire others learning about HPC",
"also what prompts me to join the High-Performance Computing (HPC) club and continue",
"context. My passion for electronics and computers is also what prompts me to",
"computers is also what prompts me to join the High-Performance Computing (HPC) club",
"client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] # The text",
"around the city. Combine with my study in the States, I believe that",
"import enums from google.cloud.language import types # Instantiates a client client = language.LanguageServiceClient()",
"the university maker space. My decision to take part in the leadership role",
"response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from the API key_words=list()",
"library from google.cloud import language from google.cloud.language import enums from google.cloud.language import types",
"study in the States, I believe that it is these experiences that taught",
"my study in the States, I believe that it is these experiences that",
"document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) #",
"a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11, 12] #",
"= types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop",
"offered at both TU Dresden and Tokyo tech, I spent most of my",
"from google.cloud import language from google.cloud.language import enums from google.cloud.language import types #",
"The text to analyze text = \"Aside from course work, my passion for",
"google.cloud import language from google.cloud.language import enums from google.cloud.language import types # Instantiates",
"I believe that it is these experiences that taught me how to quickly",
"text to analyze text = \"Aside from course work, my passion for traveling",
"university maker space. My decision to take part in the leadership role of",
"passion for traveling was what prompted me to take part in the study",
"maker space. My decision to take part in the leadership role of the",
"to inspire others learning about HPC by sharing a subject that I enjoy",
"= enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from the",
"is these experiences that taught me how to quickly adapt to changes in",
"me how to quickly adapt to changes in the environment and apply my",
"taking classes offered at both TU Dresden and Tokyo tech, I spent most",
"to take part in the leadership role of the BUHPC contained more than",
"classes offered at both TU Dresden and Tokyo tech, I spent most of",
"google.cloud.language import enums from google.cloud.language import types # Instantiates a client client =",
"to join the High-Performance Computing (HPC) club and continue to be an active",
"the Google Cloud client library from google.cloud import language from google.cloud.language import enums",
"in the environment and apply my ability in a different context. My passion",
"learning about HPC by sharing a subject that I enjoy learning. Similarly, by",
"contained more than my interest in the subject matter; I wish to inspire",
"# The text to analyze text = \"Aside from course work, my passion",
"about HPC by sharing a subject that I enjoy learning. Similarly, by taking",
"Europe and around the city. Combine with my study in the States, I",
"My decision to take part in the leadership role of the BUHPC contained",
"course work, my passion for traveling was what prompted me to take part",
"entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort() return \",\".join(map(str,key_words))",
"[8, 9, 10, 11, 12] # The text to analyze text = \"Aside",
"electronics and computers is also what prompts me to join the High-Performance Computing",
"= \"Aside from course work, my passion for traveling was what prompted me",
"an active member of the university maker space. My decision to take part",
"= [8, 9, 10, 11, 12] # The text to analyze text =",
"# Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10, 11,",
"matter; I wish to inspire others learning about HPC by sharing a subject",
"by taking part in the engineering \" def gapiAnalysisText(text): document = types.Document( content=text,",
"me to join the High-Performance Computing (HPC) club and continue to be an",
"def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document,",
"part in the leadership role of the BUHPC contained more than my interest",
"the city. Combine with my study in the States, I believe that it",
"enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from the API",
"club and continue to be an active member of the university maker space.",
"client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from the API key_words=list() for entity",
"both TU Dresden and Tokyo tech, I spent most of my off time",
"my off time traveling Europe and around the city. Combine with my study",
"= client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from the API key_words=list() for",
"Germany, in the spring of 2018 and Tokyo, Japan in the summer of",
"and around the city. Combine with my study in the States, I believe",
"States, I believe that it is these experiences that taught me how to",
"learning. Similarly, by taking part in the engineering \" def gapiAnalysisText(text): document =",
"was what prompted me to take part in the study aboard program in",
"by sharing a subject that I enjoy learning. Similarly, by taking part in",
"encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type) # Loop through entitites returned from",
"key_words=list() for entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort()",
"text = \"Aside from course work, my passion for traveling was what prompted",
"different context. My passion for electronics and computers is also what prompts me",
"others learning about HPC by sharing a subject that I enjoy learning. Similarly,",
"Loop through entitites returned from the API key_words=list() for entity in response.entities: if",
"city. Combine with my study in the States, I believe that it is",
"from google.cloud.language import types # Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE =",
"part in the engineering \" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type",
"through entitites returned from the API key_words=list() for entity in response.entities: if (entity.type",
"that taught me how to quickly adapt to changes in the environment and",
"Combine with my study in the States, I believe that it is these",
"my passion for traveling was what prompted me to take part in the",
"types # Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9, 10,",
"the spring of 2018 and Tokyo, Japan in the summer of 2017. While",
"Tokyo tech, I spent most of my off time traveling Europe and around",
"inspire others learning about HPC by sharing a subject that I enjoy learning.",
"\" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response =",
"import types # Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE = [8, 9,",
"how to quickly adapt to changes in the environment and apply my ability",
"my ability in a different context. My passion for electronics and computers is",
"taking part in the engineering \" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT)",
"member of the university maker space. My decision to take part in the",
"continue to be an active member of the university maker space. My decision",
"encoding_type=encoding_type) # Loop through entitites returned from the API key_words=list() for entity in",
"API key_words=list() for entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words))",
"client library from google.cloud import language from google.cloud.language import enums from google.cloud.language import",
"part in the study aboard program in Dresden, Germany, in the spring of",
"study aboard program in Dresden, Germany, in the spring of 2018 and Tokyo,",
"program in Dresden, Germany, in the spring of 2018 and Tokyo, Japan in",
"at both TU Dresden and Tokyo tech, I spent most of my off",
"in the study aboard program in Dresden, Germany, in the spring of 2018",
"Google Cloud client library from google.cloud import language from google.cloud.language import enums from",
"Japan in the summer of 2017. While taking classes offered at both TU",
"to changes in the environment and apply my ability in a different context.",
"import language from google.cloud.language import enums from google.cloud.language import types # Instantiates a",
"enums from google.cloud.language import types # Instantiates a client client = language.LanguageServiceClient() ENTITY_TYPE_TO_IGNORE",
"Imports the Google Cloud client library from google.cloud import language from google.cloud.language import",
"in the summer of 2017. While taking classes offered at both TU Dresden",
"response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort() return \",\".join(map(str,key_words)) char_str= gapiAnalysisText(text)",
"in a different context. My passion for electronics and computers is also what",
"that it is these experiences that taught me how to quickly adapt to",
"I spent most of my off time traveling Europe and around the city.",
"tech, I spent most of my off time traveling Europe and around the",
"off time traveling Europe and around the city. Combine with my study in",
"these experiences that taught me how to quickly adapt to changes in the",
"spent most of my off time traveling Europe and around the city. Combine",
"the API key_words=list() for entity in response.entities: if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name)",
"engineering \" def gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response",
"subject matter; I wish to inspire others learning about HPC by sharing a",
"if (entity.type not in ENTITY_TYPE_TO_IGNORE): key_words.append(entity.name) key_words=list(dict.fromkeys(key_words)) key_words.sort() return \",\".join(map(str,key_words)) char_str= gapiAnalysisText(text) print(char_str)",
"11, 12] # The text to analyze text = \"Aside from course work,",
"Tokyo, Japan in the summer of 2017. While taking classes offered at both",
"gapiAnalysisText(text): document = types.Document( content=text, type=enums.Document.Type.PLAIN_TEXT) encoding_type = enums.EncodingType.UTF8 response = client.analyze_entities(document, encoding_type=encoding_type)",
"TU Dresden and Tokyo tech, I spent most of my off time traveling",
"the study aboard program in Dresden, Germany, in the spring of 2018 and",
"analyze text = \"Aside from course work, my passion for traveling was what",
"Cloud client library from google.cloud import language from google.cloud.language import enums from google.cloud.language"
] |
[
"\\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess from",
"\\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess from causal_world.metrics.mean_last_integrated_fractional_success import \\ MeanLastIntegratedFractionalSuccess",
"from causal_world.metrics.metric_base import BaseMetric from causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import",
"causal_world.metrics.metric_base import BaseMetric from causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess",
"BaseMetric from causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success",
"import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess",
"from causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import",
"from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess from causal_world.metrics.mean_last_integrated_fractional_success import",
"causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess from causal_world.metrics.mean_last_integrated_fractional_success import \\",
"MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\ MeanLastFractionalSuccess from causal_world.metrics.mean_last_integrated_fractional_success",
"causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from causal_world.metrics.mean_last_fractional_success import \\",
"import BaseMetric from causal_world.metrics.mean_accumulated_reward_metric import \\ MeanAccumulatedRewardMetric from causal_world.metrics.mean_full_integrated_fractional_success \\ import MeanFullIntegratedFractionalSuccess from"
] |
[
"exp1, exp2, coef): # Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0)",
"= decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation",
"formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para estrutura",
"from utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio para criação formatação das",
"chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus',",
"# # Utilizado como apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa #",
"# Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH",
"AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q)",
"de apoio para estrutura das chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e,",
"# bibloteca de apoio para estrutura das chaves # https://github.com/etingof/pyasn1 # # #",
"para estrutura das chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key",
"# def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key)",
"asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d,",
"BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key structure",
"asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) #",
"reconstruct SSH key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def",
"# # # bibloteca de apoio para estrutura das chaves # https://github.com/etingof/pyasn1 #",
"decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct",
"serialisation, reconstruct SSH key structure private_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPrivateKey()) return private_key",
"decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct",
"# Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH",
"import encode from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import",
"estrutura das chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key =",
"asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return",
"https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent',",
"0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1)",
"der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key structure private_key, rest_of_input",
"import AsnSchemaPublicKey # # Utilizado como apoio para criação formatação das chaves #",
"chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para estrutura das chaves",
"https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para estrutura das chaves # https://github.com/etingof/pyasn1",
"return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo",
"criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para",
"encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER",
"encode(asn_key) def generate_private_key(e, n, d, p, q, exp1, exp2, coef): # Create the",
"Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key",
"das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para estrutura das",
"<reponame>oswagner/rsa-implementation from base64 import b64decode from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode",
"from base64 import b64decode from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from",
"from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from",
"= AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d, p,",
"Undo DER serialisation, reconstruct SSH key structure private_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPrivateKey())",
"der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key structure public_key, rest_of_input",
"the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent',",
"der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded)",
"serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key structure private_key,",
"= b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key structure private_key, rest_of_input =",
"def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def",
"= b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key structure public_key, rest_of_input =",
"bibloteca de apoio para estrutura das chaves # https://github.com/etingof/pyasn1 # # # def",
"q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo",
"serialisation, reconstruct SSH key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key",
"SSH key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded):",
"modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d, p, q, exp1, exp2,",
"q, exp1, exp2, coef): # Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version',",
"p, q, exp1, exp2, coef): # Create the ASN object asn_key = AsnSchemaPrivateKey()",
"asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation",
"base64 import b64decode from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from utils.private_key",
"object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1',",
"# Undo DER serialisation, reconstruct SSH key structure public_key, rest_of_input = decode( der_serialisation,",
"apoio para estrutura das chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus):",
"pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key",
"from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio",
"n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2)",
"decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation =",
"utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio para criação formatação das chaves",
"BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key structure",
"asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): #",
"key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): #",
"modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n,",
"d, p, q, exp1, exp2, coef): # Create the ASN object asn_key =",
"Undo DER serialisation, reconstruct SSH key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey())",
"d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key)",
"import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado",
"def generate_private_key(e, n, d, p, q, exp1, exp2, coef): # Create the ASN",
"AsnSchemaPublicKey # # Utilizado como apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa",
"decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado como",
"p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded):",
"apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de",
"DER serialisation, reconstruct SSH key structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return",
"public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64",
"import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio para criação",
"asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def",
"return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo",
"import b64decode from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from utils.private_key import",
"def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation,",
"exp2, coef): # Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus',",
"structure public_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo",
"Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key",
"encode from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey",
"# Utilizado como apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # #",
"das chaves # https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey()",
"pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # #",
"coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded) #",
"asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p)",
"b64decode(private_key_encoded) # Undo DER serialisation, reconstruct SSH key structure private_key, rest_of_input = decode(",
"e) return encode(asn_key) def generate_private_key(e, n, d, p, q, exp1, exp2, coef): #",
"generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e,",
"coef): # Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n)",
"asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64",
"AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d, p, q,",
"asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient',",
"serialisation der_serialisation = b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key structure public_key,",
"asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2',",
"from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey #",
"Utilizado como apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # #",
"como apoio para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca",
"Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e)",
"# https://github.com/etingof/pyasn1 # # # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus)",
"public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER",
"# https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio para estrutura das chaves #",
"b64decode(public_key_encoded) # Undo DER serialisation, reconstruct SSH key structure public_key, rest_of_input = decode(",
"para criação formatação das chaves # https://github.com/sybrenstuvel/python-rsa # # # bibloteca de apoio",
"# # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return",
"exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation",
"generate_private_key(e, n, d, p, q, exp1, exp2, coef): # Create the ASN object",
"e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1', exp1) asn_key.setComponentByName('exponent2', exp2) asn_key.setComponentByName('coefficient', coef)",
"= AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2',",
"b64decode from pyasn1.codec.der.encoder import encode from pyasn1.codec.der.decoder import decode from utils.private_key import AsnSchemaPrivateKey",
"return encode(asn_key) def generate_private_key(e, n, d, p, q, exp1, exp2, coef): # Create",
"# # bibloteca de apoio para estrutura das chaves # https://github.com/etingof/pyasn1 # #",
"asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d, p, q, exp1, exp2, coef):",
"asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e) return encode(asn_key) def generate_private_key(e, n, d, p, q, exp1,",
"asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d) asn_key.setComponentByName('prime1', p) asn_key.setComponentByName('prime2', q) asn_key.setComponentByName('exponent1',",
"n, d, p, q, exp1, exp2, coef): # Create the ASN object asn_key",
"AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio para criação formatação",
"# Create the ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent',",
"ASN object asn_key = AsnSchemaPrivateKey() asn_key.setComponentByName('version', 0) asn_key.setComponentByName('modulus', n) asn_key.setComponentByName('publicExponent', e) asn_key.setComponentByName('privateExponent', d)",
"# Undo DER serialisation, reconstruct SSH key structure private_key, rest_of_input = decode( der_serialisation,",
"rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPublicKey()) return public_key def decode_private_key(private_key_encoded): # Undo BASE64 serialisation",
"utils.private_key import AsnSchemaPrivateKey from utils.public_key import AsnSchemaPublicKey # # Utilizado como apoio para",
"DER serialisation, reconstruct SSH key structure private_key, rest_of_input = decode( der_serialisation, asn1Spec=AsnSchemaPrivateKey()) return",
"asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(public_key_encoded)",
"# # # def generate_public_key(e, modulus): asn_key = AsnSchemaPublicKey() asn_key.setComponentByName('modulus', modulus) asn_key.setComponentByName('publicExponent', e)",
"exp2) asn_key.setComponentByName('coefficient', coef) return encode(asn_key) def decode_public_key(public_key_encoded): # Undo BASE64 serialisation der_serialisation =",
"def decode_private_key(private_key_encoded): # Undo BASE64 serialisation der_serialisation = b64decode(private_key_encoded) # Undo DER serialisation,"
] |
[
"import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source)",
"self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is",
"\"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" ) if __name__",
"Article,Source from unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\")",
"cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" )",
"<filename>tests/test_models.py from app.models import Article,Source from unittest import TestCase class TestSource(TestCase): def setUp(self):",
"is a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self):",
"is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a",
"from app.models import Article,Source from unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed",
"self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" ) if",
") def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" ) if __name__ ==",
"cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def",
"def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\"",
"setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" )",
"test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article(",
"test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" ) if __name__ == '__main__': unittest.main()",
"unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self):",
"def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def setUp(self):",
"self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" )",
"TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description,",
"class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self):",
"test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase):",
"def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\") self.assertEqual(self.article.description, \"description\" ) if __name__ == '__main__':",
"a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article)",
"a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\"",
"import Article,Source from unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a",
"class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self): self.assertEqual(self.article.title,\"title\")",
"from unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def",
"def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description,",
") class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def test_instance(self): self.assertIsInstance(self.article,Article) def test_create(self):",
"TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def",
"app.models import Article,Source from unittest import TestCase class TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is",
"\"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\" ) def",
"TestSource(TestCase): def setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\")",
"self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def setUp(self): self.article=Article( \"title\",\"urlToImage\",\"description\",\"url\",\"author\"",
"setUp(self): self.source=Source(\"BuzzFeed\",\"BuzzFeed is a cross-platform\") def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed",
"self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class TestArticle(TestCase): def",
"def test_instance(self): self.assertIsInstance(self.source,Source) def test_create(self): self.assertEqual(self.source.name,\"BuzzFeed\") self.assertEqual(self.source.description, \"BuzzFeed is a cross-platform\" ) class"
] |
[
"- 32) * 5 / 9 def ctof(c): return c * (9 /",
"5) + 32 print(\"Celsius degree 55 is equal to Fahrenheit degree \" +",
"is equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal",
"#!/usr/bin/env python def ftoc(f): return (f - 32) * 5 / 9 def",
"def ctof(c): return c * (9 / 5) + 32 print(\"Celsius degree 55",
"32) * 5 / 9 def ctof(c): return c * (9 / 5)",
"print(\"Celsius degree 55 is equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree",
"55 is equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is",
"(9 / 5) + 32 print(\"Celsius degree 55 is equal to Fahrenheit degree",
"* (9 / 5) + 32 print(\"Celsius degree 55 is equal to Fahrenheit",
"32 print(\"Celsius degree 55 is equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit",
"9 def ctof(c): return c * (9 / 5) + 32 print(\"Celsius degree",
"equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal to",
"ftoc(f): return (f - 32) * 5 / 9 def ctof(c): return c",
"/ 9 def ctof(c): return c * (9 / 5) + 32 print(\"Celsius",
"+ 32 print(\"Celsius degree 55 is equal to Fahrenheit degree \" + str(ctof(55)));",
"(f - 32) * 5 / 9 def ctof(c): return c * (9",
"to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal to Celsius",
"degree 55 is equal to Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55",
"degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal to Celsius degree \"",
"+ str(ctof(55))); print(\"Fahrenheit degree 55 is equal to Celsius degree \" + str(ftoc(55)));",
"Fahrenheit degree \" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal to Celsius degree",
"c * (9 / 5) + 32 print(\"Celsius degree 55 is equal to",
"5 / 9 def ctof(c): return c * (9 / 5) + 32",
"ctof(c): return c * (9 / 5) + 32 print(\"Celsius degree 55 is",
"return c * (9 / 5) + 32 print(\"Celsius degree 55 is equal",
"/ 5) + 32 print(\"Celsius degree 55 is equal to Fahrenheit degree \"",
"def ftoc(f): return (f - 32) * 5 / 9 def ctof(c): return",
"return (f - 32) * 5 / 9 def ctof(c): return c *",
"\" + str(ctof(55))); print(\"Fahrenheit degree 55 is equal to Celsius degree \" +",
"* 5 / 9 def ctof(c): return c * (9 / 5) +",
"python def ftoc(f): return (f - 32) * 5 / 9 def ctof(c):"
] |
[
"import pytest from pathlib import Path STUB = False if STUB: from pytest_stub.toolbox",
"<gh_stars>10-100 import pytest from pathlib import Path STUB = False if STUB: from",
"stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath def",
"from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request):",
"'[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath def static_path_(fname): return",
"stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath",
"from pathlib import Path STUB = False if STUB: from pytest_stub.toolbox import stub_global",
"'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent",
"def static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent / 'static' / fname",
"import Path STUB = False if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2':",
"'[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent /",
"STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def",
"'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path = request.fspath def static_path_(fname):",
"pathlib import Path STUB = False if STUB: from pytest_stub.toolbox import stub_global stub_global({",
"import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path =",
"Path STUB = False if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]',",
"pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture def static_path(request): path",
"static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent / 'static' / fname return",
"@pytest.fixture def static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent / 'static' /",
"if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', }) @pytest.fixture",
"path = request.fspath def static_path_(fname): return Path(str(path)).parent / 'static' / fname return static_path_",
"pytest from pathlib import Path STUB = False if STUB: from pytest_stub.toolbox import",
"STUB = False if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy':",
"False if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]', })",
"= False if STUB: from pytest_stub.toolbox import stub_global stub_global({ 'cv2': '[mock_persist]', 'numpy': '[mock_persist]',",
"}) @pytest.fixture def static_path(request): path = request.fspath def static_path_(fname): return Path(str(path)).parent / 'static'"
] |
[
"return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex",
"Unless required by applicable law or agreed to in writing, software # distributed",
"str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = {",
"= EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type':",
"| MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False):",
"EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment",
"(8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag",
"1]) offset += 1 # ip address if ip_addr_len != 0: route['ip'] =",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"the License. You may obtain # a copy of the License at #",
"offset + 1]) offset += 1 value = value[offset:] # The IP Prefix",
"= esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex =",
"return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for nlri in nlri_list:",
"= b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00'",
"yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN",
"= b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr,",
"(4 octets) | +---------------------------------------+ | IP Prefix Length (1 octet) | +---------------------------------------+ |",
"with the License. You may obtain # a copy of the License at",
"IP Address Length (1 octet) | +---------------------------------------+ | IP Address (0, 4, or",
"esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets) | +---------------------------------------+",
"2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type",
"if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod",
"| Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Prefix Length (1",
"ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4",
"\"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod",
"= b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) *",
"IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment",
"\"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5],",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big')",
"!= 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset",
"xiaopeng163) for other rd type process rd = str(rd_value) return rd @classmethod def",
"Length (1 octet) | +---------------------------------------+ | Originating Router's IP Address | | (4",
"elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value':",
"} elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9],",
"attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi'))",
"str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return route @classmethod def construct(cls, value,",
"esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I',",
"\"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]),",
"InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex",
"offset + 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0]",
"struct import binascii import netaddr from yabgp.common import afn from yabgp.common import safn",
"yabgp.common import safn from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = {",
"ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class",
"you may # not use this file except in compliance with the License.",
"value['esi']) # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex",
"= str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return route @classmethod def construct(cls,",
"+= 4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip",
"\"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() offset = 8 route['rd']",
"% (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an =",
"= str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an)",
"+ ip_hex else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01",
"def parse(cls, value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8",
"= b'' for nlri in nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY:",
"+= 10 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip",
"octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID",
"value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed value_hex +=",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"= { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5:",
"(3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict()",
"4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): # rd",
"rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for other rd type process",
"fixme(by xiaopeng163) for other rd type process data = data.split(':') if '.' in",
"+ struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address",
"value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip address len and",
"= b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex +=",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') }",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"xiaopeng163) for other rd type process data = data.split(':') if '.' in data[0]:",
"if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec in",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"mac_hex # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex",
"nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] ==",
"nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation",
"+ ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority =",
"esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type,",
"b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' +",
"b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) #",
"data): # fixme(by xiaopeng163) for other rd type process data = data.split(':') if",
"// 8]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex",
"i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip",
"byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls,",
"elif len(value) == 35: # ipv6 offset = 16 route['prefix'] = '%s/%s' %",
"struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex",
"ip_addr_len / 8)]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd",
"str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' %",
"esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes",
"and between 0 and 128 for ipv6. # The IP Prefix will be",
"{} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1:",
"offset + 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def",
"Cisco: The BGP route distinguisher can be derived automatically from the VNI and",
"or 16 octets) | +---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+ |",
"ID (4 octets) | +---------------------------------------+ | IP Prefix Length (1 octet) | +---------------------------------------+",
"struct.pack('!H', int(data[1])) else: data = [int(x) for x in data] if data[0] <=",
"= str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len /",
"address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]),",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16)))",
"rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in",
"Address Length (1 octet) | +---------------------------------------+ | Originating Router's IP Address | |",
"route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6 ip_addr_len = ord(value[offset:",
"value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment",
"octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def",
"6 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip address",
"= struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an =",
"(10 octets)| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | Originating",
"for nlri in nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex =",
"ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif esi_type",
"16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex = b''",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big')",
"struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex",
"evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY)",
"offset + ip_addr_len // 8]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False):",
"str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return route @classmethod def construct(cls, value,",
"esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len and address",
"value, iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] =",
"octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP Address Length",
"Route Type (1 octet) | +-----------------------------------+ | Length (1 octet) | +-----------------------------------+ |",
"+ ip_addr_len / 8)]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): #",
"'%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an",
"nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict):",
"agreed to in writing, software # distributed under the License is distributed on",
"class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet",
"in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return",
"{ \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value",
"ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route = {} if route_type ==",
"@classmethod def parse(cls, value, iswithdraw=False): route = dict() offset = 8 route['rd'] =",
":param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type",
"as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex",
"ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+",
"EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B',",
"elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s' %",
"nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex =",
"esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05'",
"route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset:",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i",
"route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False): value_hex = b''",
"int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\":",
"to in writing, software # distributed under the License is distributed on an",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif",
"| RD (8 octets) | +---------------------------------------+ | Ethernet Tag ID (4 octets) |",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif",
"offset += 10 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 #",
"= cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len",
"= int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))),",
"of the VTEP switch :param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value",
"or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route =",
"Tag ID (4 octets) | +---------------------------------------+ | IP Prefix Length (1 octet) |",
"as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex",
"address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6 ip_addr_len =",
"== bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif",
"str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6 ip_addr_len = ord(value[offset: offset +",
"ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"],",
"+= 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset",
"route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] =",
"sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big')",
"route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type ==",
"evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec",
"construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex +=",
"limitations # under the License. from __future__ import division import struct import binascii",
"if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes",
"= cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet tag id route['eth_tag_id']",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') }",
"\"License\"); you may # not use this file except in compliance with the",
"Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type ==",
"MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10",
"cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex = b''",
"!= 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return route",
"NLRI is as follows: +-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+ |",
"16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' +",
"address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex)",
"Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route =",
"be set to a value between 0 and 32 # (bits) for ipv4",
"data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data =",
"offset += 4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 #",
"byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\":",
"return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def",
"not use this file except in compliance with the License. You may obtain",
"else: data = [int(x) for x in data] if data[0] <= 0xffff: return",
"else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ |",
"len(value) == 11: # ipv4 offset = 4 elif len(value) == 35: #",
"== bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) +",
"value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len and address if",
"+---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value",
"+---------------------------------------+ | MAC Address Length (1 octet) | +---------------------------------------+ | MAC Address (6",
"nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label",
"== ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls,",
"# ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset +",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4,",
"int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod def",
"format of the EVPN NLRI is as follows: +-----------------------------------+ | Route Type (1",
"'.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else:",
"data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H',",
"(10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MAC",
"| +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP Address Length (1",
"= b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex",
"octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | Originating",
"RD (8 octets) | +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+",
"offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value =",
"10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len =",
"| +---------------------------------------+ | MAC Address Length (1 octet) | +---------------------------------------+ | MAC Address",
"value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len and address",
"return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"],",
"route distinguisher can be derived automatically from the VNI and BGP router ID",
"community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay",
"= b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"+---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() # rd offset",
"cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+",
"struct.pack('!d', value['esi']) # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed",
"= IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data = nlri_data[offset",
"(int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01'",
"route = dict() # rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi",
"netaddr from yabgp.common import afn from yabgp.common import safn from yabgp.common import constants",
"int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'),",
"16 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod",
"esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len = ord(value[offset:",
"= { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4:",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+",
"value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex",
"ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len /",
"# ip address if len(value) == 11: # ipv4 offset = 4 elif",
"== 11: # ipv4 offset = 4 elif len(value) == 35: # ipv6",
"if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route =",
"offset += 1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(",
"rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd =",
"# ipv4 offset = 4 elif len(value) == 35: # ipv6 offset =",
"an = struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an) elif rd_type ==",
"+ b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex =",
"ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len //",
"| MAC Address (6 octets) | +---------------------------------------+ | IP Address Length (1 octet)",
"tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len and address mac_hex =",
"= esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr,",
"rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif rd_type",
"MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex",
"and 32 # (bits) for ipv4 and between 0 and 128 for ipv6.",
"octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Prefix",
"octet) | +---------------------------------------+ | Originating Router's IP Address | | (4 or 16",
"cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len",
"rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex",
"if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]),",
"= ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route =",
"'%s:%s' % (asn, an) else: # fixme(by xiaopeng163) for other rd type process",
"set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False}",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type",
"IP Address (4 or 16 octets) | +---------------------------------------+ | MPLS Label (3 octets)",
"in data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return",
"+= cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address",
"import safn from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from",
"# ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len",
"b'' for nlri in nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex",
"if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1]))",
"value between 0 and 32 # (bits) for ipv4 and between 0 and",
"else: # fixme(by xiaopeng163) for other rd type process rd = str(rd_value) return",
"Label1 (3 octets) | +---------------------------------------+ | MPLS Label2 (0 or 3 octets) |",
"+= struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip address len and address",
"8]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex =",
"value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I',",
"value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return",
"= data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\",
"ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type",
"| +---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+ | IP Address Length",
"express or implied. See the # License for the specific language governing permissions",
"if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s' %",
"= struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return",
"in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex",
"1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset +",
"import binascii import netaddr from yabgp.common import afn from yabgp.common import safn from",
"route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route",
"ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return",
"len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN):",
"and 128 for ipv6. # The IP Prefix will be a 32 or",
"b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets)",
"nlri_list_hex = b'' for nlri in nlri_list: nlri_hex = b'' if nlri['type'] ==",
"/ 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value,",
"elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route =",
"RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet",
"value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8",
"route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset +=",
"+---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | Originating Router's IP",
"byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\":",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"(4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"iswithdraw=False): route = dict() # rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) #",
"return route @classmethod def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd'])",
"router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big')",
"16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:]",
"{\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"]",
"+---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\",",
"offset + int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len / 8) # label",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value =",
"The IP Prefix Length can be set to a value between 0 and",
"5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset +=",
"= EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG:",
"import netaddr from yabgp.common import afn from yabgp.common import safn from yabgp.common import",
"either express or implied. See the # License for the specific language governing",
"value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' return",
"| +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID (4",
"# rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset:",
"| +---------------------------------------+ | GW IP Address (4 or 16 octets) | +---------------------------------------+ |",
"if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True",
"yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format of the EVPN NLRI is",
"Address Length (1 octet) | +---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+",
"= struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len = ord(value[offset: offset",
"offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value =",
"0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod",
"type process data = data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) +",
"attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if",
"(1 octet) | +---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+ | IP",
"i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex +",
"parse(cls, value, iswithdraw=False): route = dict() # rd offset = 8 route['rd'] =",
"= InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX:",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif",
"RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP",
"esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex",
"= tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN):",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"ID of the VTEP switch :param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0]",
"Ethernet Tag ID (4 octets) | +---------------------------------------+ | MPLS Label (3 octets) |",
"data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH',",
"| MPLS Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls,",
"int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco: The BGP route",
"rd = '%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I',",
"value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets)",
"| +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls,",
"str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = {",
"(6 octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ |",
"<= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1])",
"esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type ==",
"b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex",
"sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex",
"+ 1]) offset += 1 # ip address if ip_addr_len != 0: route['ip']",
"has the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\"",
"byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif esi_type ==",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ |",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+",
"= ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif",
"int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'),",
"nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value =",
"35: # ipv6 offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))),",
"+= 4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 value =",
"ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return",
"4, or 16 octets) | +---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+",
"in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex",
"ipv4 offset = 4 elif len(value) == 35: # ipv6 offset = 16",
"from __future__ import division import struct import binascii import netaddr from yabgp.common import",
"+ \\ struct.pack('!H', int(data[1])) else: data = [int(x) for x in data] if",
"if route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data = nlri_data[offset + 2:]",
"= b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"]",
"ip address if len(value) == 11: # ipv4 offset = 4 elif len(value)",
"# under the License. from __future__ import division import struct import binascii import",
"| +-----------------------------------+ | Length (1 octet) | +-----------------------------------+ | Route Type specific (variable)",
"# All rights reserved. # # Licensed under the Apache License, Version 2.0",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data",
"} return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value =",
"if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2,",
"byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\":",
"rd type process rd = str(rd_value) return rd @classmethod def construct_rd(cls, data): #",
"= struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an) else: # fixme(by xiaopeng163)",
"struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip address len and address if",
"@staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation EC",
"return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and",
"class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier",
"dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset +",
"\\ struct.pack('!H', int(data[1])) else: data = [int(x) for x in data] if data[0]",
"between 0 and 32 # (bits) for ipv4 and between 0 and 128",
"# ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex +=",
"cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex +=",
"== bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if",
"== bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if",
"8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet tag",
"value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex +=",
"# rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00'",
"Length (1 octet) | +---------------------------------------+ | IP Prefix (4 or 16 octets) |",
"ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label']",
"b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value",
"# Copyright 2016 Cisco Systems, Inc. # All rights reserved. # # Licensed",
"else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8",
"b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4,",
"| IP Address (0, 4, or 16 octets) | +---------------------------------------+ | MPLS Label1",
"= rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"ord(value[offset: offset + 1]) offset += 1 # ip address if ip_addr_len !=",
"| +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() offset =",
"following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value",
"rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex +",
"ID (4 octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+",
"16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value,",
"bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type",
"+= b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1]))",
"+= cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) |",
"route_value = nlri_data[2: offset + 2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY:",
"address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len /",
"+ 1]) offset += 1 value = value[offset:] # The IP Prefix Length",
"= 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:]",
"esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2,",
"and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8)",
"route }) nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls, nlri_list):",
"offset += 1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset:",
"evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco: The",
"+ ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex =",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex +=",
"route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset:",
"if EVPN and encapsulation EC set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay",
"int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type,",
"\"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value =",
"10]) offset += 10 ip_addr_len = ord(value[offset: offset + 1]) offset += 1",
"+ netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data = [int(x) for x in",
"value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip address len",
"IP Prefix will be a 32 or 128-bit field (ipv4 or ipv6). #",
"or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route =",
"8) + ip_hex else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" #",
"== bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif",
"ipv6 offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value",
"rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn,",
"| +---------------------------------------+ | MPLS Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod",
"+ b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex =",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset",
"\"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext =",
"address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B',",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type",
"= cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len = ord(value[offset: offset +",
"+ ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex",
"(1 octet) | +-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod",
"value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d',",
"byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id,",
"offset += 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16)))",
"rd = str(rd_value) return rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for",
"+= struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' if value.get('label'):",
"applicable law or agreed to in writing, software # distributed under the License",
"+---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+",
"the VNI and BGP router ID of the VTEP switch :param data: :return:",
"def construct_rd(cls, data): # fixme(by xiaopeng163) for other rd type process data =",
"All rights reserved. # # Licensed under the Apache License, Version 2.0 (the",
"Cisco Systems, Inc. # All rights reserved. # # Licensed under the Apache",
"T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {}",
"# esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif",
"ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1])",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))),",
"= esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex =",
":return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0:",
"+= cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) |",
"tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn']",
"mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex)",
"the EVPN NLRI is as follows: +-----------------------------------+ | Route Type (1 octet) |",
"4])[0] offset += 4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1",
"rd_value) rd = '%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip =",
"+---------------------------------------+ | IP Prefix Length (1 octet) | +---------------------------------------+ | IP Prefix (4",
"import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format of the",
"octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MAC Address",
"route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data =",
"== bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route })",
"esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B',",
"class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ | Ethernet Tag",
"ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type",
"(10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MPLS",
"def construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) #",
"octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() offset",
"# esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id'] =",
"Length (1 octet) | +---------------------------------------+ | IP Address (0, 4, or 16 octets)",
"\"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex =",
"128 for ipv6. # The IP Prefix will be a 32 or 128-bit",
"(int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) +",
"offset += int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod",
"\"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset",
"address if len(value) == 11: # ipv4 offset = 4 elif len(value) ==",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4,",
"Length (1 octet) | +-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+ \"\"\"",
"b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type",
"+ 10]) offset += 10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset:",
"The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value |",
"} elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:],",
"+---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8])",
"| (4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False):",
"+= 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): #",
"cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset +",
"(ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd =",
"Identifier (10 octets)| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ |",
"The IP Prefix will be a 32 or 128-bit field (ipv4 or ipv6).",
"| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Address",
"type process rd = str(rd_value) return rd @classmethod def construct_rd(cls, data): # fixme(by",
"language governing permissions and limitations # under the License. from __future__ import division",
"ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 5",
"= struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2:",
"# Unless required by applicable law or agreed to in writing, software #",
"route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex",
"address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) +",
"+ ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher",
"by applicable law or agreed to in writing, software # distributed under the",
"parse(cls, value, iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id']",
"len(value) == 35: # ipv6 offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0:",
"int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len / 8) # label route['label'] =",
"= InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX:",
"ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex",
"ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex",
"# mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6",
"dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset",
"= ord(value[offset: offset + 1]) offset += 1 # ip address if ip_addr_len",
"route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4",
"a 32 or 128-bit field (ipv4 or ipv6). # # ip address if",
"0 and 32 # (bits) for ipv4 and between 0 and 128 for",
"(3 octets) | +---------------------------------------+ | MPLS Label2 (0 or 3 octets) | +---------------------------------------+",
"@classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for other rd type process data",
"esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type ==",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The",
"16))) offset += int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route",
"ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data):",
"evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\"",
"ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex",
"| +---------------------------------------+ | Originating Router's IP Address | | (4 or 16 octets)",
"InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ | Ethernet Tag ID",
":param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try:",
"IP Address | | (4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def",
"16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' +",
"process rd = str(rd_value) return rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163)",
"id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 route['label'] =",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"for ipv4 and between 0 and 128 for ipv6. # The IP Prefix",
"process data = data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed",
"esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3,",
"ip_addr_len // 8]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd",
"esi): \"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI",
"field (ipv4 or ipv6). # # ip address if len(value) == 11: #",
"# not use this file except in compliance with the License. You may",
"data): \"\"\" For Cisco: The BGP route distinguisher can be derived automatically from",
"other rd type process rd = str(rd_value) return rd @classmethod def construct_rd(cls, data):",
"construct_rd(cls, data): # fixme(by xiaopeng163) for other rd type process data = data.split(':')",
"value, iswithdraw=False): route = dict() # rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset])",
"offset + 1]) offset += 1 # ip address if ip_addr_len != 0:",
"value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed value_hex += cls.construct_mpls_label_stack(value['label'])",
"= struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif",
"(1 octet) | +---------------------------------------+ | IP Address (0, 4, or 16 octets) |",
"+---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Prefix Length",
"1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset",
"| +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type",
"esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type ==",
"+ sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"]",
"| +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() # rd",
"an) else: # fixme(by xiaopeng163) for other rd type process rd = str(rd_value)",
"!= 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return route",
"+= struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed value_hex += cls.construct_mpls_label_stack(value['label']) return",
"tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 5 #",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type']",
"ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B',",
"+= b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8",
"struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an) else: # fixme(by xiaopeng163) for",
"a value between 0 and 32 # (bits) for ipv4 and between 0",
"value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+",
"octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | IP",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data = [int(x) for x",
"attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi",
"= b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num,",
"+= b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+",
"\"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier",
"= cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset",
"= ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route = {} if route_type",
"\"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn,",
"MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route",
"struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed",
"len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) *",
"Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False):",
"| +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() route['rd'] =",
"value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets)",
"(8 octets) | +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ |",
"class EVPN(NLRI): \"\"\" The format of the EVPN NLRI is as follows: +-----------------------------------+",
"+ rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value =",
"route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({",
"\"\"\" For Cisco: The BGP route distinguisher can be derived automatically from the",
"# ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len and address",
"+= 1 value = value[offset:] # The IP Prefix Length can be set",
"ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex",
"OF ANY KIND, either express or implied. See the # License for the",
"== bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an)",
"esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3:",
"Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ |",
"+= 1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset:",
"| MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS Label2 (0 or 3",
"+ rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"]",
"Inc. # All rights reserved. # # Licensed under the Apache License, Version",
"router ID of the VTEP switch :param data: :return: \"\"\" rd_type = struct.unpack('!H',",
"+---------------------------------------+ | MPLS Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def",
"(1 octet) | +---------------------------------------+ | Originating Router's IP Address | | (4 or",
"16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex",
"route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value)",
"byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex +",
"dict() # rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] =",
"route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset",
"value['eth_tag_id']) # mac address len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for",
"8)]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex =",
"+= b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) |",
"True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco:",
"the VTEP switch :param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value =",
"4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value,",
"| IP Prefix Length (1 octet) | +---------------------------------------+ | IP Prefix (4 or",
"= netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex +=",
"\"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)|",
"esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2,",
"router_id_hex + ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"],",
"offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls,",
"data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0],",
"value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id'])",
"\"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() # rd offset =",
"6]), 16))) offset += 6 ip_addr_len = ord(value[offset: offset + 1]) offset +=",
"return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data = [int(x)",
"Length can be set to a value between 0 and 32 # (bits)",
"= struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1:",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') }",
"struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI',",
"esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1:",
"mac address len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in",
"byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex +",
"= b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT:",
"nlri_data[2: offset + 2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route =",
"byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type ==",
"nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type']",
"Length (1 octet) | +---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+ |",
"def parse(cls, value, iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset])",
"esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I',",
"router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex",
"ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len and address mac_hex",
"esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big')",
"cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len",
"afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN,",
"an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s'",
"== bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an)",
"esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') }",
"if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16)))",
"esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex =",
"Originating Router's IP Address | | (4 or 16 octets) | +---------------------------------------+ \"\"\"",
"offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0]",
"offset + 6]), 16))) offset += 6 ip_addr_len = ord(value[offset: offset + 1])",
"b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac",
"= struct.unpack('!I', value[offset: offset + 4])[0] offset += 5 # mac address route['mac']",
"nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value'])",
"rights reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type",
"value = value[offset:] # The IP Prefix Length can be set to a",
"= IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex",
"NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format of the EVPN",
"def construct(cls, nlri_list): nlri_list_hex = b'' for nlri in nlri_list: nlri_hex = b''",
"id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 5 # mac",
"dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext",
"len(mac_hex) * 8) + mac_hex # ip address len and address if value.get('ip'):",
"MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS Label2 (0 or 3 octets)",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"+= b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len and address if value.get('ip'):",
"value[offset:] # The IP Prefix Length can be set to a value between",
"(4 octets) | +---------------------------------------+ | MAC Address Length (1 octet) | +---------------------------------------+ |",
"while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset +",
"between 0 and 128 for ipv6. # The IP Prefix will be a",
"construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type ==",
"octets) | +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP",
"offset += 1 value = value[offset:] # The IP Prefix Length can be",
"str(rd_value) return rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for other rd",
"octet) | +-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def",
"value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id'])",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big')",
"= cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex =",
"rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00'",
"[int(x) for x in data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0],",
"compliance with the License. You may obtain # a copy of the License",
"byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9],",
"% (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16)))",
"elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'],",
"b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B',",
"nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return",
"Tag ID (4 octets) | +---------------------------------------+ | IP Address Length (1 octet) |",
"to a value between 0 and 32 # (bits) for ipv4 and between",
"= '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0:",
"in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data",
"route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] =",
"constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI):",
"+-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data):",
"may # not use this file except in compliance with the License. You",
"IP Address Length (1 octet) | +---------------------------------------+ | Originating Router's IP Address |",
"| RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ |",
"= cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex",
"route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset",
"encapsulation EC set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False,",
"= attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True",
"esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0:",
"= cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10",
"for x in data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1])",
"(afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation']",
"\"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data):",
"\"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation EC set :param attr_dict:",
"nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex))",
"bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex",
"(4 or 16 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+",
"tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 route['label']",
"@classmethod def parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1]) offset",
"ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex",
"set to a value between 0 and 32 # (bits) for ipv4 and",
"VNI and BGP router ID of the VTEP switch :param data: :return: \"\"\"",
"in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex # ip address",
"esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b''",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i,",
"{ \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value",
"can be set to a value between 0 and 32 # (bits) for",
"route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value)",
"for other rd type process rd = str(rd_value) return rd @classmethod def construct_rd(cls,",
"+ router_id_hex + ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value =",
"offset += 6 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 #",
"asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an) else: #",
"\"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5],",
"= [int(x) for x in data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0,",
"+ esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex =",
"VTEP switch :param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8]",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif",
"ID (4 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\"",
"= as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex +",
"octet) | +-----------------------------------+ | Length (1 octet) | +-----------------------------------+ | Route Type specific",
"iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset:",
"follows: +-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+ | Length (1 octet)",
"def parse(cls, value, iswithdraw=False): route = dict() # rd offset = 8 route['rd']",
"elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex =",
"\"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier",
"= MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT:",
"The BGP route distinguisher can be derived automatically from the VNI and BGP",
"octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() #",
"specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list = [] while",
"}) nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex",
"8) + ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex",
"= [] while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2:",
"from yabgp.common import afn from yabgp.common import safn from yabgp.common import constants as",
"rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big')",
"8) + ip_hex else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+",
"# fixme(by xiaopeng163) for other rd type process rd = str(rd_value) return rd",
"return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for",
"| ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if",
"value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets)",
"BGP router ID of the VTEP switch :param data: :return: \"\"\" rd_type =",
"16))) offset += 6 ip_addr_len = ord(value[offset: offset + 1]) offset += 1",
"(0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route",
"rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' +",
"use this file except in compliance with the License. You may obtain #",
"+= struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10",
"value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8",
"offset + 10]) offset += 10 ip_addr_len = ord(value[offset: offset + 1]) offset",
"IP Prefix (4 or 16 octets) | +---------------------------------------+ | GW IP Address (4",
"* 8) + ip_hex else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\"",
"3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict()",
"octet) | +---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+ | IP Address",
"4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip address",
"Address (0, 4, or 16 octets) | +---------------------------------------+ | MPLS Label1 (3 octets)",
"<filename>yabgp/message/attribute/nlri/evpn.py # Copyright 2016 Cisco Systems, Inc. # All rights reserved. # #",
"= str(rd_value) return rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for other",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big')",
"offset = 8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 #",
"# ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len",
"from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format of the EVPN NLRI",
"def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation EC set",
"Address (4 or 16 octets) | +---------------------------------------+ | MPLS Label (3 octets) |",
"rd = '%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an =",
"# ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class",
"ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip,",
"iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I',",
"KIND, either express or implied. See the # License for the specific language",
"EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type,",
"import struct import binascii import netaddr from yabgp.common import afn from yabgp.common import",
"file except in compliance with the License. You may obtain # a copy",
"class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier",
"route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len = ord(value[offset: offset",
"EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route",
"for ipv6. # The IP Prefix will be a 32 or 128-bit field",
"11: # ipv4 offset = 4 elif len(value) == 35: # ipv6 offset",
"esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type ==",
"esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2:",
"10]) offset += 10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset",
"= nlri_data[2: offset + 2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route",
"yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format of",
"the # License for the specific language governing permissions and limitations # under",
"octet) | +---------------------------------------+ | IP Prefix (4 or 16 octets) | +---------------------------------------+ |",
"@classmethod def parse_rd(cls, data): \"\"\" For Cisco: The BGP route distinguisher can be",
"route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type ==",
"\"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value =",
"* 8) + ip_hex else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\"",
"| Originating Router's IP Address | | (4 or 16 octets) | +---------------------------------------+",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i,",
"rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")])",
"b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ |",
"data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value)",
"+= struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ |",
"struct.pack('!I', value['eth_tag_id']) # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed",
"nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] ==",
"esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5:",
"esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type ==",
"Segment Identifier (10 octets)| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+",
"or agreed to in writing, software # distributed under the License is distributed",
"ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in",
"| Ethernet Tag ID (4 octets) | +---------------------------------------+ | MPLS Label (3 octets)",
"| Length (1 octet) | +-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return",
"if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD",
"len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex",
"+ 2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif",
"MPLSVPN class EVPN(NLRI): \"\"\" The format of the EVPN NLRI is as follows:",
"# http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10",
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"@classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for nlri in nlri_list: nlri_hex =",
"route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:])",
"Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Prefix Length (1 octet)",
"b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex =",
"\"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]),",
"+ int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len / 8) # label route['label']",
"construct(cls, value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' +",
"label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): # rd",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i",
"ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex + b'\\x00'",
"route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route",
"== (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec in community_ext: if",
"+---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS Label2 (0 or",
"MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route",
"data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type ==",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec in community_ext:",
"+---------------------------------------+ | IP Prefix (4 or 16 octets) | +---------------------------------------+ | GW IP",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"(str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value",
"parse(cls, value, iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) #",
"data = [int(x) for x in data] if data[0] <= 0xffff: return struct.pack('!HHI',",
"data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI has the following format:",
"= value[offset:] # The IP Prefix Length can be set to a value",
"0 and 128 for ipv6. # The IP Prefix will be a 32",
"* 8) + mac_hex # ip address len and address if value.get('ip'): ip_hex",
"int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))),",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"\"\"\" The format of the EVPN NLRI is as follows: +-----------------------------------+ | Route",
"mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6 ip_addr_len",
"# (bits) for ipv4 and between 0 and 128 for ipv6. # The",
"for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex",
"tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\"",
"esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04'",
"(int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02'",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an) elif",
"esi_data_hex = b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"],",
"iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex +=",
"route @classmethod def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex",
"under the License. from __future__ import division import struct import binascii import netaddr",
"netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00'",
"# mac address len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i",
"octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() route['rd']",
"def parse_rd(cls, data): \"\"\" For Cisco: The BGP route distinguisher can be derived",
"rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"],",
"in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex",
"4 elif len(value) == 35: # ipv6 offset = 16 route['prefix'] = '%s/%s'",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big')",
"nlri in nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value'])",
"len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding",
"+ mac_hex # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed",
"+-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type =",
"import division import struct import binascii import netaddr from yabgp.common import afn from",
"| | (4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value,",
"+= cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag",
"elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route =",
"= 8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet",
"= 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset",
"route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex +=",
"parse_rd(cls, data): \"\"\" For Cisco: The BGP route distinguisher can be derived automatically",
"except in compliance with the License. You may obtain # a copy of",
"+ b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8",
"b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8)",
"draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation EC set :param attr_dict: bgp",
"IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod",
"derived automatically from the VNI and BGP router ID of the VTEP switch",
"(asn, an) else: # fixme(by xiaopeng163) for other rd type process rd =",
"+ struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex +=",
"= b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value =",
"MAC Address Length (1 octet) | +---------------------------------------+ | MAC Address (6 octets) |",
"value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len and",
"rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an",
"= b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi'])",
"= esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex",
"byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type ==",
"= { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\":",
"ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len",
"16 octets) | +---------------------------------------+ | GW IP Address (4 or 16 octets) |",
"return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) |",
"MPLS Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value,",
"parse(cls, value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi']",
"x in data] if data[0] <= 0xffff: return struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else:",
"route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route",
"rd_value = data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd",
"ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD)",
"| GW IP Address (4 or 16 octets) | +---------------------------------------+ | MPLS Label",
"# rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) #",
"fixme(by xiaopeng163) for other rd type process rd = str(rd_value) return rd @classmethod",
"route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len = ord(value[offset:",
"struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes",
"'%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]),",
"cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex",
"= str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod",
"== 35: # ipv6 offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]),",
"value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len and address if value.get('ip'): ip_hex",
"Address (6 octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+",
"| Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Address Length (1",
"byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\":",
"route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len",
"| +---------------------------------------+ | IP Address (0, 4, or 16 octets) | +---------------------------------------+ |",
"struct.pack('!I', value['eth_tag_id']) # mac address len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16)))",
"= EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG:",
"struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route",
"| +---------------------------------------+ | IP Prefix (4 or 16 octets) | +---------------------------------------+ | GW",
"| IP Address Length (1 octet) | +---------------------------------------+ | IP Address (0, 4,",
"+-----------------------------------+ | Length (1 octet) | +-----------------------------------+ | Route Type specific (variable) |",
"License for the specific language governing permissions and limitations # under the License.",
"import afn from yabgp.common import safn from yabgp.common import constants as bgp_cons from",
"rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an",
"struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len",
"= dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset +",
"parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2])",
"EVPN(NLRI): \"\"\" The format of the EVPN NLRI is as follows: +-----------------------------------+ |",
"+---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP Address Length (1 octet)",
"netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data = [int(x) for x in data]",
"iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi']",
"or ipv6). # # ip address if len(value) == 11: # ipv4 offset",
"= {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT:",
"= b'\\x02' + rb_mac_hex + rb_priority_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr,",
"0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return route @classmethod",
"bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route = IPRoutePrefix.parse(route_value) if route:",
"from the VNI and BGP router ID of the VTEP switch :param data:",
"IPRoutePrefix.parse(route_value) if route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data = nlri_data[offset +",
"ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type",
"as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\"",
"return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet",
"evpn_overlay['evpn'] = True if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]:",
"return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for",
"| +---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS Label2 (0",
"| Ethernet Tag ID (4 octets) | +---------------------------------------+ | MAC Address Length (1",
"# fixme(by xiaopeng163) for other rd type process data = data.split(':') if '.'",
"is as follows: +-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+ | Length",
"8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False):",
"elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd",
"str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len / 8)",
"EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10",
"|Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) |",
"Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Address Length (1 octet)",
"data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s'",
"http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)|",
"\"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ | Ethernet Tag ID (4",
"16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\":",
"'value': route }) nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls,",
"struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len = ord(value[offset: offset +",
"construct(cls, nlri_list): nlri_list_hex = b'' for nlri in nlri_list: nlri_hex = b'' if",
"License. You may obtain # a copy of the License at # #",
"% (asn, an) else: # fixme(by xiaopeng163) for other rd type process rd",
"return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco: The BGP route distinguisher",
"return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets) |",
"b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex +=",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16)))",
"from yabgp.common import safn from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import",
"+ 10]) offset += 10 ip_addr_len = ord(value[offset: offset + 1]) offset +=",
"value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d',",
"+---------------------------------------+ | Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10",
"= dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset:",
"@classmethod def parse_esi(cls, esi): \"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ |",
"2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for nlri in",
"+---------------------------------------+ | IP Address (0, 4, or 16 octets) | +---------------------------------------+ | MPLS",
"bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The",
"ANY KIND, either express or implied. See the # License for the specific",
"signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN and encapsulation EC set :param",
"route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 5 # mac address",
"== bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif",
"rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip",
"iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi'])",
"be derived automatically from the VNI and BGP router ID of the VTEP",
"+---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value,",
"safn from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn",
"ip_addr_len = ord(value[offset: offset + 1]) offset += 1 value = value[offset:] #",
"value, iswithdraw=False): route = dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi",
"ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex +",
"struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD",
"= True if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec']",
"+---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP Address Length",
"for i in value['mac'].split(\"-\")]) value_hex += struct.pack('!B', len(mac_hex) * 8) + mac_hex #",
"+---------------------------------------+ | RD (8 octets) | +---------------------------------------+ | Ethernet Tag ID (4 octets)",
"value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address",
"octet) | +---------------------------------------+ | IP Address (0, 4, or 16 octets) | +---------------------------------------+",
"elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex =",
"| Route Type (1 octet) | +-----------------------------------+ | Length (1 octet) | +-----------------------------------+",
"an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif rd_type ==",
"offset = 4 elif len(value) == 35: # ipv6 offset = 16 route['prefix']",
"bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type",
"= b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len",
"nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if EVPN",
"= esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9,",
"+ 2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for nlri",
"@classmethod def parse(cls, value, iswithdraw=False): route = dict() # rd offset = 8",
"specific language governing permissions and limitations # under the License. from __future__ import",
"b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route Distinguisher (RD) (8 octets)",
"esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' +",
"See the # License for the specific language governing permissions and limitations #",
"bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec': False} try: afi_safi =",
"ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in sys_mac_addr.split(\"-\")])",
"16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' +",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex =",
"law or agreed to in writing, software # distributed under the License is",
"b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex =",
"{ \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value",
"| +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0:",
"(8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP Address",
"== bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif",
"Systems, Inc. # All rights reserved. # # Licensed under the Apache License,",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"division import struct import binascii import netaddr from yabgp.common import afn from yabgp.common",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type",
"value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] =",
"\"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value =",
"+ ip_hex else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ |",
"16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict()",
"value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else:",
"as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big')",
"value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' if",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type,",
"esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet tag",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\":",
"Ethernet Tag ID (4 octets) | +---------------------------------------+ | MAC Address Length (1 octet)",
"octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MPLS Label",
"| MAC Address Length (1 octet) | +---------------------------------------+ | MAC Address (6 octets)",
"= esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4,",
"automatically from the VNI and BGP router ID of the VTEP switch :param",
"= EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex +=",
"rd type process data = data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1)",
"value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False):",
"EVPN NLRI is as follows: +-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+",
"byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class",
"if nlri_hex: nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def",
"b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"],",
"+= int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def",
"= dict() offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset",
"bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type']",
"value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD",
"cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex +=",
"this file except in compliance with the License. You may obtain # a",
"nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value'])",
"import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class",
"or implied. See the # License for the specific language governing permissions and",
"route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type ==",
"struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' return value_hex class",
"+= 1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset",
"dict() route['rd'] = cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset + 10])",
"+ b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex =",
"Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+",
"= { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3:",
"Type (1 octet) | +-----------------------------------+ | Length (1 octet) | +-----------------------------------+ | Route",
"8) + mac_hex # ip address len and address if value.get('ip'): ip_hex =",
"10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset +=",
"parse_esi(cls, esi): \"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T |",
"data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\"",
"@classmethod def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex +=",
"16 octets) | +---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS",
"value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex",
"= 4 elif len(value) == 35: # ipv6 offset = 16 route['prefix'] =",
"+---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | IP Address (0,",
"rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn,",
"IP Prefix Length can be set to a value between 0 and 32",
"= cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset +=",
"rd_value) rd = '%s:%s' % (asn, an) else: # fixme(by xiaopeng163) for other",
"byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key =",
"IP Address (0, 4, or 16 octets) | +---------------------------------------+ | MPLS Label1 (3",
"struct.pack('!HHI', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls,",
"Tag ID (4 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+",
"EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex",
"ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip address if",
"if len(value) == 11: # ipv4 offset = 4 elif len(value) == 35:",
"value[offset: offset + 4])[0] offset += 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset:",
"(ipv4 or ipv6). # # ip address if len(value) == 11: # ipv4",
"value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+",
"ip_hex else: value_hex += b'\\x00' return value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD",
"octets) | +---------------------------------------+ | MPLS Label2 (0 or 3 octets) | +---------------------------------------+ \"\"\"",
"octets) | +---------------------------------------+ | IP Prefix Length (1 octet) | +---------------------------------------+ | IP",
"b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len and address if value.get('ip'): ip_hex",
"else: value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN):",
"struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip",
"esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN):",
"'%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value)",
"nlri_list.append({ 'type': route_type, 'value': route }) nlri_data = nlri_data[offset + 2:] return nlri_list",
"binascii import netaddr from yabgp.common import afn from yabgp.common import safn from yabgp.common",
"router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex",
"encoding if EVPN and encapsulation EC set :param attr_dict: bgp attribute dictionary \"\"\"",
"construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi",
"= str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]), 16))) offset += 6 ip_addr_len = ord(value[offset: offset",
"1]) offset += 1 value = value[offset:] # The IP Prefix Length can",
"32 or 128-bit field (ipv4 or ipv6). # # ip address if len(value)",
"Address Length (1 octet) | +---------------------------------------+ | IP Address (0, 4, or 16",
"| IP Prefix (4 or 16 octets) | +---------------------------------------+ | GW IP Address",
"data = data.split(':') if '.' in data[0]: return struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed +",
"{ \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } return {\"type\": esi_type, \"value\": esi_value}",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI has the following",
"| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | Originating Router's",
"(0, 4, or 16 octets) | +---------------------------------------+ | MPLS Label1 (3 octets) |",
"permissions and limitations # under the License. from __future__ import division import struct",
"The format of the EVPN NLRI is as follows: +-----------------------------------+ | Route Type",
"= nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b''",
"int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset += int(ip_addr_len / 8) #",
"\"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value =",
"__future__ import division import struct import binascii import netaddr from yabgp.common import afn",
"128-bit field (ipv4 or ipv6). # # ip address if len(value) == 11:",
"= { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2:",
"| IP Address Length (1 octet) | +---------------------------------------+ | Originating Router's IP Address",
"offset + 4])[0] offset += 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset",
"= True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For",
"ID (4 octets) | +---------------------------------------+ | MAC Address Length (1 octet) | +---------------------------------------+",
"(4 or 16 octets) | +---------------------------------------+ | GW IP Address (4 or 16",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"Copyright 2016 Cisco Systems, Inc. # All rights reserved. # # Licensed under",
"/ 8)]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): # rd value_hex",
"+= 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len",
"Prefix will be a 32 or 128-bit field (ipv4 or ipv6). # #",
"implied. See the # License for the specific language governing permissions and limitations",
"def parse_esi(cls, esi): \"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex",
"cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet tag id route['eth_tag_id'] =",
"= ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type ==",
"+---------------------------------------+ | MAC Address (6 octets) | +---------------------------------------+ | IP Address Length (1",
"| Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list",
"sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in",
"False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi",
"elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex =",
"esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes =",
"ord(value[offset: offset + 1]) offset += 1 value = value[offset:] # The IP",
"route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type ==",
"+= cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex",
"+---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MAC Address Length",
"8 route['rd'] = cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset +=",
"Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list = []",
"the License. from __future__ import division import struct import binascii import netaddr from",
"nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value'])",
"cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 #",
"value[offset: offset + 4])[0] offset += 4 ip_addr_len = ord(value[offset: offset + 1])",
"cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len and address if value.get('ip'):",
"nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2]",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"= router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex +",
"@classmethod def construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd'])",
"+= 6 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip",
"+ 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls,",
"afn from yabgp.common import safn from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri",
"esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key",
"cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len = ord(value[offset: offset + 1])",
"@classmethod def parse(cls, value, iswithdraw=False): route = dict() route['rd'] = cls.parse_rd(value[0:8]) offset =",
"= ord(value[offset: offset + 1]) offset += 1 value = value[offset:] # The",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i",
"required by applicable law or agreed to in writing, software # distributed under",
"int(data[1])) else: data = [int(x) for x in data] if data[0] <= 0xffff:",
"16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\":",
"ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")])",
"for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex",
"yabgp.common import afn from yabgp.common import safn from yabgp.common import constants as bgp_cons",
"b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+",
"esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' +",
"struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI has the",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big')",
"octets) | +---------------------------------------+ | MPLS Label1 (3 octets) | +---------------------------------------+ | MPLS Label2",
"in compliance with the License. You may obtain # a copy of the",
"+-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+ | Length (1 octet) |",
"ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16)))",
"8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset",
"of the EVPN NLRI is as follows: +-----------------------------------+ | Route Type (1 octet)",
"if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16)))",
"[] while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset",
"def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type",
"try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi ==",
"|Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | IP Address Length (1 octet) |",
"+---------------------------------------+ | GW IP Address (4 or 16 octets) | +---------------------------------------+ | MPLS",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16)))",
"value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B',",
"Tag ID (4 octets) | +---------------------------------------+ | MAC Address Length (1 octet) |",
"{} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route",
"True if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] =",
"/ 8)]), 16))) offset += int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:])",
"or 16 octets) | +---------------------------------------+ | GW IP Address (4 or 16 octets)",
"1 value = value[offset:] # The IP Prefix Length can be set to",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex =",
"data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+",
"esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big')",
"# esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip address len and",
"for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex",
"esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: router_id, ld_value",
"for other rd type process data = data.split(':') if '.' in data[0]: return",
"octets) | +---------------------------------------+ | MAC Address Length (1 octet) | +---------------------------------------+ | MAC",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big')",
"class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet",
"BGP route distinguisher can be derived automatically from the VNI and BGP router",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"(bits) for ipv4 and between 0 and 128 for ipv6. # The IP",
"return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: sys_mac_addr, ld_value = esi_value[\"sys_mac_addr\"], esi_value[\"ld_value\"] sys_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for",
"(asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H',",
"+ 10]) offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset",
"Address | | (4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod def parse(cls,",
"except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext:",
"for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] =",
"= '%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH',",
"+= struct.pack('!I', value['eth_tag_id']) # ip address len and address if value.get('ip'): ip_hex =",
"route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value)",
"MAC Address (6 octets) | +---------------------------------------+ | IP Address Length (1 octet) |",
"len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN):",
"switch :param data: :return: \"\"\" rd_type = struct.unpack('!H', data[0:2])[0] rd_value = data[2:8] if",
"ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route = {}",
"* 8) + ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label'])",
"+= b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) #",
"cls.parse_rd(value[0:8]) offset = 8 route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10",
"} elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9],",
"changes label encoding if EVPN and encapsulation EC set :param attr_dict: bgp attribute",
"return rd @classmethod def construct_rd(cls, data): # fixme(by xiaopeng163) for other rd type",
"| Route Distinguisher (RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)|",
"nlri_list_hex += struct.pack('!2B', nlri['type'], len(nlri_hex)) + nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\"",
"offset += 10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset +",
"(1 octet) | +---------------------------------------+ | IP Prefix (4 or 16 octets) | +---------------------------------------+",
"= b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex",
"value[offset: offset + 4])[0] offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod",
"4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 value = value[offset:]",
"+= cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len and address if",
"+---------------------------------------+ | Originating Router's IP Address | | (4 or 16 octets) |",
"esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:],",
"@classmethod def construct_esi(cls, esi_data): esi_type, esi_value = esi_data[\"type\"], esi_data[\"value\"] esi_data_hex = b'' if",
"struct.unpack(\"!B\", esi[:1])[0], {} if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type",
"+= struct.pack('!B', len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' return value_hex",
"b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value",
"or 128-bit field (ipv4 or ipv6). # # ip address if len(value) ==",
"bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type",
"+ 4])[0] offset += 4 ip_addr_len = ord(value[offset: offset + 1]) offset +=",
"cls.parse_rd(value[0:offset]) route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4 ip_addr_len =",
"= b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\"",
"esi_data_hex = b'' if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex =",
"distinguisher can be derived automatically from the VNI and BGP router ID of",
"governing permissions and limitations # under the License. from __future__ import division import",
"# esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 ip_addr_len =",
"struct.pack('!H', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1) + netaddr.IPAddress(data[0]).packed + \\ struct.pack('!H', int(data[1])) else: data = [int(x) for",
"b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority",
"struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return",
"Prefix Length can be set to a value between 0 and 32 #",
"| T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value = struct.unpack(\"!B\", esi[:1])[0],",
"+ as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ |",
"'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if",
"if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex =",
"(4 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\" @classmethod",
"safn.SAFNUM_EVPN): evpn_overlay['evpn'] = True if community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] ==",
"# License for the specific language governing permissions and limitations # under the",
"== bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for",
"= data[2:8] if rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0: asn, an = struct.unpack('!HI', rd_value) rd =",
"= dict() # rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi']",
"value['eth_tag_id']) # ip address len and address if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex",
"| +---------------------------------------+ | IP Prefix Length (1 octet) | +---------------------------------------+ | IP Prefix",
"offset += 4 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 value",
"(4 octets) | +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ |",
"be a 32 or 128-bit field (ipv4 or ipv6). # # ip address",
"offset += 4 route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False):",
"i in rb_mac_addr.split(\"-\")]) rb_priority_hex = rb_priority.to_bytes(2, byteorder='big') esi_data_hex = b'\\x02' + rb_mac_hex +",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"# # ip address if len(value) == 11: # ipv4 offset = 4",
"in writing, software # distributed under the License is distributed on an \"AS",
"route: nlri_list.append({ 'type': route_type, 'value': route }) nlri_data = nlri_data[offset + 2:] return",
"and BGP router ID of the VTEP switch :param data: :return: \"\"\" rd_type",
"= str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return route @classmethod def construct(cls,",
"ip_hex else: value_hex += b'\\x00' return value_hex class IPRoutePrefix(EVPN): \"\"\" # http://tools.ietf.org/html/draft-ietf-bess-evpn-prefix-advertisement-01 +---------------------------------------+",
"| +-----------------------------------+ | Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls,",
"== bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif",
"License. from __future__ import division import struct import binascii import netaddr from yabgp.common",
"value_hex class EthernetSegment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ |Ethernet Segment",
"InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: route",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"2016 Cisco Systems, Inc. # All rights reserved. # # Licensed under the",
"IP Prefix Length (1 octet) | +---------------------------------------+ | IP Prefix (4 or 16",
"GW IP Address (4 or 16 octets) | +---------------------------------------+ | MPLS Label (3",
"value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False): value_hex =",
"rd = '%s:%s' % (asn, an) else: # fixme(by xiaopeng163) for other rd",
"For Cisco: The BGP route distinguisher can be derived automatically from the VNI",
"b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B',",
"8)]), 16))) offset += int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return",
"cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+",
"bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value'] = int(ec[1]) return evpn_overlay @classmethod def",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_0, data[0], data[1]) else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi):",
"address len and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")])",
"iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id'])",
"nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for nlri in nlri_list: nlri_hex",
"int(offset + ip_addr_len / 8)]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False):",
"} elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = { \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9],",
"route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return route @classmethod def",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\":",
"nlri_data): nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1]) offset = ord(nlri_data[1:2]) route_value",
"from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import MPLSVPN class EVPN(NLRI): \"\"\" The format",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"{'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return",
"int(ip_addr_len / 8) # label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls,",
"return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI has",
"bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type']",
"asn, an = struct.unpack('!HI', rd_value) rd = '%s:%s' % (asn, an) elif rd_type",
"i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex +",
"else: return struct.pack('!HIH', bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2, data[0], data[1]) @classmethod def parse_esi(cls, esi): \"\"\" The ESI",
"value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet",
"+ struct.pack('!d', value['esi']) # ip address len and address if value.get('ip'): ip_hex =",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"] as_num_hex = as_num.to_bytes(4, byteorder='big')",
"nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] ==",
"16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\":",
"0: route['ip'] = str(netaddr.IPAddress( int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16))) offset +=",
"esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = { \"as_num\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') }",
"nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex: nlri_list_hex",
"(the \"License\"); you may # not use this file except in compliance with",
"+---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets)",
"= MacIPAdvertisment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT:",
"+ 4])[0] offset += 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset +",
"route_type, 'value': route }) nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod def",
"sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif",
"# # Unless required by applicable law or agreed to in writing, software",
"16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len) value = value[offset:] route['gateway']",
"32 # (bits) for ipv4 and between 0 and 128 for ipv6. #",
"+ ld_value_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: as_num, ld_value = esi_value[\"as_num\"], esi_value[\"ld_value\"]",
"+= 1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset",
"\"\"\" @classmethod def parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1])",
"+---------------------------------------+ \"\"\" @classmethod def parse(cls, value, iswithdraw=False): route = dict() offset = 8",
"nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value'])",
"ld_value = esi_value[\"router_id\"], esi_value[\"ld_value\"] router_id_hex = router_id.to_bytes(4, byteorder='big') ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex",
"value_hex += cls.construct_rd(value['rd']) # esi value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) # ip",
"+ 6]), 16))) offset += 6 ip_addr_len = ord(value[offset: offset + 1]) offset",
"= '%s:%s' % (asn, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0]))",
"1 # ip address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset +",
"+= struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed",
"0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]), 16))) return route @classmethod",
"(1 octet) | +-----------------------------------+ | Length (1 octet) | +-----------------------------------+ | Route Type",
"def construct(cls, value, iswithdraw=False): value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00'",
"ipv6. # The IP Prefix will be a 32 or 128-bit field (ipv4",
"+ ip_addr_len // 8]), 16))) return route @classmethod def construct(cls, value, iswithdraw=False): #",
"\"\"\" The ESI has the following format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value",
"= esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex",
"and limitations # under the License. from __future__ import division import struct import",
"== bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s'",
"b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex =",
"+= b'\\x00\\x00' + struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex",
"(variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list = [] while nlri_data:",
"str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def",
"b'' value_hex += cls.construct_rd(value['rd']) value_hex += b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I',",
"ipv4 and between 0 and 128 for ipv6. # The IP Prefix will",
"an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_1: ip = str(netaddr.IPAddress(struct.unpack('!I', rd_value[0:4])[0])) an = struct.unpack('!H', rd_value[4:6])[0]",
"esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"] rb_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in rb_mac_addr.split(\"-\")]) rb_priority_hex =",
"route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route = InclusiveMulticastEthernetTag.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: route = EthernetSegment.parse(route_value)",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"# label route['label'] = cls.parse_mpls_label_stack(value[offset:]) return route @classmethod def construct(cls, value, iswithdraw=False): #",
"can be derived automatically from the VNI and BGP router ID of the",
"in nlri_list: nlri_hex = b'' if nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif",
"(RD) (8 octets) | +---------------------------------------+ |Ethernet Segment Identifier (10 octets)| +---------------------------------------+ | Ethernet",
"EVPN and encapsulation EC set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay =",
"byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4: esi_value = { \"router_id\": int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\":",
"Route Type specific (variable) | +-----------------------------------+ \"\"\" @classmethod def parse(cls, nlri_data): nlri_list =",
"= 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10])",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value = { \"sys_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ld_value\": int.from_bytes(esi[7:], byteorder='big') } elif esi_type",
"and address mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in value['mac'].split(\"-\")]) value_hex +=",
"value_hex += b'\\x00' if value.get('label'): value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\"",
"community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay if afi_safi == (afn.AFNUM_L2VPN, safn.SAFNUM_EVPN): evpn_overlay['evpn'] =",
"+ ce_port_hex + b'\\x00' elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: rb_mac_addr, rb_priority = esi_value[\"rb_mac_addr\"], esi_value[\"rb_priority\"]",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"or 16 octets) | +---------------------------------------+ | MPLS Label (3 octets) | +---------------------------------------+ \"\"\"",
"as follows: +-----------------------------------+ | Route Type (1 octet) | +-----------------------------------+ | Length (1",
"{ \"rb_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"rb_priority\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_3: esi_value",
"+= struct.pack('!I', value['eth_tag_id']) # mac address len and address mac_hex = b''.join([struct.pack('!B', (int(i,",
"offset = ord(nlri_data[1:2]) route_value = nlri_data[2: offset + 2] route = {} if",
"(int(i, 16))) for i in sys_mac_addr.split(\"-\")]) ld_value_hex = ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03'",
"# The IP Prefix Length can be set to a value between 0",
"= value[offset:] route['label'] = cls.parse_mpls_label_stack(value) return route @classmethod def construct(cls, value, iswithdraw=False): value_hex",
"ce_port_hex = ce_port_key.to_bytes(2, byteorder='big') esi_data_hex = b'\\x01' + ce_mac_hex + ce_port_hex + b'\\x00'",
"= int(ec[1]) return evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco: The BGP",
"elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: ce_mac_addr, ce_port_key = esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i,",
"10 ip_addr_len = ord(value[offset: offset + 1]) offset += 1 # ip address",
"struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex += netaddr.IPAddress(value['gateway']).packed value_hex",
"\"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value =",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"if value.get('ip'): ip_hex = netaddr.IPAddress(value['ip']).packed value_hex += struct.pack('!B', len(ip_hex) * 8) + ip_hex",
"Prefix (4 or 16 octets) | +---------------------------------------+ | GW IP Address (4 or",
"nlri_list): nlri_list_hex = b'' for nlri in nlri_list: nlri_hex = b'' if nlri['type']",
"value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex += netaddr.IPAddress(value['prefix'].split('/')[0]).packed value_hex",
"if esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value",
"4])[0] offset += 5 # mac address route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset + 6]),",
"value_hex class InclusiveMulticastEthernetTag(EVPN): \"\"\" +---------------------------------------+ | RD (8 octets) | +---------------------------------------+ | Ethernet",
"Router's IP Address | | (4 or 16 octets) | +---------------------------------------+ \"\"\" @classmethod",
"and encapsulation EC set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn':",
"def construct(cls, value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) value_hex",
"route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 # ethernet tag id",
"address if ip_addr_len != 0: route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: offset + ip_addr_len // 8]),",
"bgp_cons.ESI_BGPNLRI_EVPN_TYPE_0: esi_bytes = esi_value.to_bytes(9, byteorder='big') esi_data_hex = b'\\x00' + esi_bytes elif esi_type ==",
"byteorder='big') } return {\"type\": esi_type, \"value\": esi_value} @classmethod def construct_esi(cls, esi_data): esi_type, esi_value",
"+ nlri_hex return nlri_list_hex @staticmethod def signal_evpn_overlay(attr_dict): \"\"\" draft-ietf-bess-evpn-overlay-10 changes label encoding if",
"ipv6). # # ip address if len(value) == 11: # ipv4 offset =",
"struct.unpack('!H', rd_value[4:6])[0] rd = '%s:%s' % (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn,",
"esi_value[\"ce_mac_addr\"], esi_value[\"ce_port_key\"] ce_mac_hex = b''.join([struct.pack('!B', (int(i, 16))) for i in ce_mac_addr.split(\"-\")]) ce_port_hex =",
"will be a 32 or 128-bit field (ipv4 or ipv6). # # ip",
"EC set :param attr_dict: bgp attribute dictionary \"\"\" evpn_overlay = {'evpn': False, 'encap_ec':",
"route['ip'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[offset: int(offset + ip_addr_len / 8)]), 16))) return route @classmethod def",
"def parse(cls, nlri_data): nlri_list = [] while nlri_data: route_type = ord(nlri_data[0:1]) offset =",
"= value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] = cls.parse_mpls_label_stack(value)",
"value, iswithdraw=False): # rd value_hex = b'' value_hex += cls.construct_rd(value['rd']) # esi value_hex",
"import MPLSVPN class EVPN(NLRI): \"\"\" The format of the EVPN NLRI is as",
"b'' value_hex += cls.construct_rd(value['rd']) value_hex += struct.pack('!I', value['eth_tag_id']) # ip address len and",
"b'\\x00\\x00' + struct.pack('!d', value['esi']) value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += struct.pack('!B', int(value['prefix'].split('/')[1])) value_hex",
"= '%s:%s' % (asn, an) else: # fixme(by xiaopeng163) for other rd type",
"bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an) else:",
"= ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex + b'\\x00' elif",
"other rd type process data = data.split(':') if '.' in data[0]: return struct.pack('!H',",
"ld_value.to_bytes(3, byteorder='big') esi_data_hex = b'\\x03' + sys_mac_hex + ld_value_hex elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_4:",
"ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label']) return value_hex class MacIPAdvertisment(EVPN):",
"False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except: return evpn_overlay",
"= ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x05' + as_num_hex + ld_value_hex + b'\\x00' return",
"evpn_overlay @classmethod def parse_rd(cls, data): \"\"\" For Cisco: The BGP route distinguisher can",
"the specific language governing permissions and limitations # under the License. from __future__",
"label encoding if EVPN and encapsulation EC set :param attr_dict: bgp attribute dictionary",
"octets)| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | Originating Router's",
"int.from_bytes(esi[1:5], byteorder='big'), \"ld_value\": int.from_bytes(esi[5:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_5: esi_value = {",
"cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset + 10]) offset += 10 route['eth_tag_id']",
"for the specific language governing permissions and limitations # under the License. from",
"'type': route_type, 'value': route }) nlri_data = nlri_data[offset + 2:] return nlri_list @classmethod",
"len(ip_hex) * 8) + ip_hex else: value_hex += b'\\x00' if value.get('label'): value_hex +=",
"nlri_data[offset + 2:] return nlri_list @classmethod def construct(cls, nlri_list): nlri_list_hex = b'' for",
"% (ip, an) elif rd_type == bgp_cons.BGP_ROUTE_DISTINGUISHER_TYPE_2: asn, an = struct.unpack('!IH', rd_value) rd",
"octets) | +---------------------------------------+ | GW IP Address (4 or 16 octets) | +---------------------------------------+",
"offset += 10 route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset += 4",
"format: +---+---+---+---+---+---+---+---+---+---+ | T | ESI Value | +---+---+---+---+---+---+---+---+---+---+ \"\"\" esi_type, esi_value =",
"elif route_type == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: route = MacIPAdvertisment.parse(route_value) elif route_type == bgp_cons.BGPNLRI_EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG: route =",
"= {'evpn': False, 'encap_ec': False} try: afi_safi = tuple(attr_dict.get(bgp_cons.BGPTYPE_MP_REACH_NLRI).get('afi_safi')) community_ext = attr_dict.get(bgp_cons.BGPTYPE_EXTENDED_COMMUNITY) except:",
"rd offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset",
"bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_IP_ROUTE_PREFIX: nlri_hex = IPRoutePrefix.construct(value=nlri['value']) if nlri_hex:",
"# The IP Prefix will be a 32 or 128-bit field (ipv4 or",
"+---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | MPLS Label (3",
"value_hex += struct.pack('!I', value['eth_tag_id']) # mac address len and address mac_hex = b''.join([struct.pack('!B',",
"Prefix Length (1 octet) | +---------------------------------------+ | IP Prefix (4 or 16 octets)",
"nlri_hex = InclusiveMulticastEthernetTag.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_ETHERNET_SEGMENT: nlri_hex = EthernetSegment.construct(value=nlri['value']) elif nlri['type'] ==",
"offset + 10]) offset += 10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I',",
"+= 10 # ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0]",
"community_ext: for ec in community_ext: if bgp_cons.BGP_EXT_COM_DICT['encapsulation'] == ec[0]: evpn_overlay['encap_ec'] = True evpn_overlay['encap_value']",
"| +---------------------------------------+ | IP Address Length (1 octet) | +---------------------------------------+ | IP Address",
"# ethernet tag id route['eth_tag_id'] = struct.unpack('!I', value[offset: offset + 4])[0] offset +=",
"(10 octets)| +---------------------------------------+ | Ethernet Tag ID (4 octets) | +---------------------------------------+ | IP",
"an = struct.unpack('!IH', rd_value) rd = '%s:%s' % (asn, an) else: # fixme(by",
"from yabgp.common import constants as bgp_cons from yabgp.message.attribute.nlri import NLRI from yabgp.message.attribute.nlri.mpls_vpn import",
"offset + 4])[0] offset += 4 ip_addr_len = ord(value[offset: offset + 1]) offset",
"str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]), 16))), \"ce_port_key\": int.from_bytes(esi[7:9], byteorder='big') } elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_2: esi_value = {",
"as_num_hex + ld_value_hex + b'\\x00' return esi_data_hex class EthernetAutoDiscovery(EVPN): \"\"\" +---------------------------------------+ | Route",
"# ipv6 offset = 16 route['prefix'] = '%s/%s' % (str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))), ip_addr_len)",
"offset = 8 route['rd'] = cls.parse_rd(value[0:offset]) # esi route['esi'] = cls.parse_esi(value[offset: offset +",
"value = value[offset:] route['gateway'] = str(netaddr.IPAddress(int(binascii.b2a_hex(value[0: offset]), 16))) value = value[offset:] route['label'] =",
"offset + 2] route = {} if route_type == bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: route = EthernetAutoDiscovery.parse(route_value)",
"== bgp_cons.BGPNLRI_EVPN_ETHERNET_AUTO_DISCOVERY: nlri_hex = EthernetAutoDiscovery.construct(value=nlri['value']) elif nlri['type'] == bgp_cons.BGPNLRI_EVPN_MAC_IP_ADVERTISEMENT: nlri_hex = MacIPAdvertisment.construct(value=nlri['value']) elif",
"esi_value = int.from_bytes(esi[1:], byteorder='big') elif esi_type == bgp_cons.ESI_BGPNLRI_EVPN_TYPE_1: esi_value = { \"ce_mac_addr\": str(netaddr.EUI(int(binascii.b2a_hex(esi[1:7]),",
"+ struct.pack('!d', value['esi']) # ethernet tag value_hex += struct.pack('!I', value['eth_tag_id']) value_hex += cls.construct_mpls_label_stack(value['label'])",
"ld_value_hex = ld_value.to_bytes(4, byteorder='big') esi_data_hex = b'\\x04' + router_id_hex + ld_value_hex + b'\\x00'",
"struct.unpack('!I', value[offset: offset + 4])[0] offset += 5 # mac address route['mac'] ="
] |
[
"self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox()",
"\"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\":",
"element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try:",
"PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\")",
"NoSuchElementException import time, math class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY =",
"self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element, keys):",
"ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self,",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\")",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def",
"self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3)",
"self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self,",
"0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4",
"AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"),",
"print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\")",
"self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"),",
"self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet",
"WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage",
"self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self):",
"None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\",",
"def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS =",
"Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click()",
"self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"),",
") ) def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self,",
"= 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement =",
"self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"),",
"expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" +",
"pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def",
"self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\")",
"2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6",
"self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert()",
"Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3)",
"self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\")",
"alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click()",
"Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing",
"good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\")",
"print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"),",
"print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments",
"\"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory",
"selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions",
"def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click()",
"self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\")",
"0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser",
"apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click()",
"alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing",
"\"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and",
"= self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing",
"False return True except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet",
"+ self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length):",
"self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets",
"print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3)",
"SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id)",
"Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"),",
"= self.GetElementById(id) if(value == False): return False return True except NoSuchElementException: print(\"NO PAGE\")",
"def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners",
"\"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\")",
"= pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click()",
"self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert =",
"self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status]",
"def IfExistById(self, id): try: value = self.GetElementById(id) if(value == False): return False return",
"Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"),",
"self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert()",
"Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\")",
"None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics",
"print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"),",
"self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length)",
"= self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments",
"import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import",
"from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from",
"def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value",
"self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\")",
"tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click()",
"self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\")",
"id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self,",
"[ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\":",
"value = self.GetElementById(id) if(value == False): return False return True except NoSuchElementException: print(\"NO",
"math class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS =",
"self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"),",
"alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details",
"return False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing",
"NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser,",
"self.GetElementById(id) if(value == False): return False return True except NoSuchElementException: print(\"NO PAGE\") return",
"Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"),",
"\"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click()",
"def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"),",
"3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None",
"Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click()",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails()",
"Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes",
"self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing",
"\"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"),",
"import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import",
"self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners",
"PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click()",
") def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element):",
"self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\")",
"import NoSuchElementException import time, math class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY",
"self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert",
"self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\"",
"self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def",
"1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5",
"element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self,",
"self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click()",
"\"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys)",
"5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement = None self.Pages = [",
"self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement",
"self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\")",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\")",
"id) ) ) def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def",
"= self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing",
"= self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert",
"= None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\",",
"selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet: def",
"False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet",
"selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support",
"False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located(",
"\"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"),",
"self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\")",
"Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"),",
"= 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement = None self.Pages =",
"self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert()",
"(By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage])",
"self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS",
"element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id):",
"ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value =",
"Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails()",
"Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\")",
"self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self):",
"+= 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return",
"Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\")",
"self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement = None self.Pages",
"print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\")",
"\"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\": 0,",
"\"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\")",
"By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException",
"Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click()",
"id): try: value = self.GetElementById(id) if(value == False): return False return True except",
"== False): return False return True except NoSuchElementException: print(\"NO PAGE\") return False def",
"= None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ]",
"= [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = {",
"def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"),",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets()",
"try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element,",
"from selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet: def __init__(self): self.PET_OWNERS =",
"from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import",
"import expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet: def __init__(self):",
"Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"),",
"self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory()",
"VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"),",
"\"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\": 0, \"max\":",
"alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\")",
"self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails()",
"0, \"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands()",
"Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\")",
"alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments",
"self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id):",
"WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage = pageID",
"self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet",
"def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1",
"yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click()",
"= self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address)",
"and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"),",
"self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self,",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"),",
"print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click()",
"\"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0,",
"\"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners",
"self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross",
"if(value == False): return False return True except NoSuchElementException: print(\"NO PAGE\") return False",
"self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details",
"self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId):",
"selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet: def __init__(self): self.PET_OWNERS = 0",
"Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert =",
"PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS",
"self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete --\") print(\"---------------------------\") pgs =",
"0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self,",
"\"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing",
"UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement",
"alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"\"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert =",
"status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement =",
"\"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\")",
"self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id) if(value",
"self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"--",
"def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID,",
"self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self):",
"Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert",
"self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS)",
"address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] +=",
"Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def",
"self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\")",
"self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing",
"= self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory",
"time, math class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS",
"= 0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS =",
"Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id) if(value == False):",
"alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details",
"self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\")",
"self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\")",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\")",
"self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click()",
"self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets",
"self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details",
"3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\"",
"SwitchToPage(self, pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def",
"NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"),",
"= webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def",
"def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing",
"self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert()",
"+= 1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException:",
"self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click()",
"import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math",
"Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self):",
"= self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing",
"self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"),",
"id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID): self.CurrentPage =",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert =",
"alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert()",
"= self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\")",
"import time, math class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1",
"\"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\")",
"def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False",
"element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) )",
"self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete --\") print(\"---------------------------\") pgs = PageGetSet()",
"print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\")",
"Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments()",
"def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click()",
"self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert",
"self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert =",
"def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def SwitchToPage(self, pageID):",
"self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\")",
"{ \"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" +",
"Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing",
"selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time,",
"Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing",
"= 1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS =",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert()",
"self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete --\")",
"from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet:",
"print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS)",
"self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser",
"self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good",
"\"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address):",
"self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self,",
"webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions",
"Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\")",
"\"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click()",
"4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement = None",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def",
"self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] +=",
"1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return",
"alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing",
"Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert",
"print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click()",
"Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50",
"= 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS = 6 self.Browser =",
"are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click()",
"self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert =",
"\"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\": 0, \"max\": 0",
"self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\")",
"pageID): self.CurrentPage = pageID self.Browser.get(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) def ClickElement(self, element): element.click() def ClickElementById(self,",
"InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"]",
"\"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def",
"\"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert =",
"length): time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id) if(value == False): return",
"Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments",
"self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except",
"alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\")",
"alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self):",
"cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"),",
"Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"),",
"\"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click()",
"Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY) self.SendKeysToElement(self.GetElementById(\"txtName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\")",
"__init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS = 3",
"self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert",
"RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests",
"1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement",
"self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click()",
"\"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept()",
"Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\")",
"self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click()",
"ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\")",
"= { \"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\"",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3)",
"\"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"50\") self.SendKeysToElement(self.GetElementById(\"txtCost\"), \"2.0\") self.SendKeysToElement(self.GetElementById(\"txtPrice\"), \"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"),",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\")",
"\"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\": 0, \"max\": 0 }",
"IfExistById(self, id): try: value = self.GetElementById(id) if(value == False): return False return True",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def",
"alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert()",
"Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"),",
"WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math class",
"self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are",
"Finish\") self.Sleep(3) def Appointments(self): print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def",
"\"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\")",
"True except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners Start\")",
"6 self.Browser = None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\",",
"self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click()",
"+ self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status):",
"\"2.0\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3)",
"GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def",
"def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All",
"self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete",
"def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try:",
"webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self,",
"self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchPet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchVet\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"),",
"def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\")",
"except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS)",
"self.Inventory() self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete --\") print(\"---------------------------\")",
"from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from",
"self.Statistics = { \"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS",
"] self.Statistics = { \"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage =",
"self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3) def Appointments(self):",
"Pet Owners Start\") self.SwitchToPage(self.PET_OWNERS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def",
"self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\") self.Sleep(3)",
"self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"),",
"alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\") self.SwitchToPage(self.INVENTORY)",
"print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\")",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS)",
"self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"),",
"self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"),",
"} self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def InitializeBrowser(self, address): self.Browser =",
"\"AppointmentDetails.aspx\" ] self.Statistics = { \"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage",
"time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id) if(value == False): return False",
"Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click()",
"self.Vets() self.VetsDetails() self.Appointments() self.AppointmentsDetails() self.Appointments() print(\"---------------------------\") print(\"-- All Tests Complete --\") print(\"---------------------------\") pgs",
"\"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage]) self.RunCommands() def",
"elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id)",
"self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnAddAvailability']\").click() alert = self.Browser.switch_to_alert() alert.accept() print(\"Testing Vets Details Finish\")",
"alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtPetName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtPetDOB\"), \"02/01/2023\") self.SendKeysToElement(self.GetElementById(\"txtPetType\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtPetBreed\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddPet']\").click()",
"self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty",
"self.Statistics[status] += 1 self.Statistics[\"max\"] += 1 def GetElementById(self, id): try: self.WorkElement = self.Browser.find_element_by_id(id)",
"= self.Browser.find_element_by_id(id) return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear()",
"print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners() self.PetOwnersDetails() self.Inventory() self.Vets() self.VetsDetails() self.Appointments()",
"print(\"Testing Appointments Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details",
"return True except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing Pet Owners",
"Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets",
"print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtAppointmentDate\"), \"02/01/2023\") self.Browser.find_element_by_xpath(\"//select[@id='DropDownListHour']\").click() self.Browser.find_element_by_xpath(\"//option[@value='07']\").click() self.Browser.find_element_by_xpath(\"//select[@id='DropDownListMinute']\").click() self.Browser.find_element_by_xpath(\"//option[@value='45']\").click() self.SendKeysToElement(self.GetElementById(\"txtPaid\"), \"Cakes\")",
"return self.WorkElement except NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchVet']\").click() self.SendKeysToElement(self.GetElementById(\"txtSearchInventory\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearchInventory']\").click() print(\"Testing Appointments Details Finish\") self.Sleep(3) def RunCommands(self): self.PetOwners()",
"def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3)",
"except NoSuchElementException: return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id):",
"class PageGetSet: def __init__(self): self.PET_OWNERS = 0 self.INVENTORY = 1 self.VETS = 2",
"keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) )",
"self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\", \"Appointments.aspx\", \"PetOwnerDetails.aspx\", \"AppointmentDetails.aspx\" ] self.Statistics =",
"Details Start\") self.SwitchToPage(self.PET_OWNER_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstname\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastname\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobile\"), \"424-288-2000\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.Browser.find_element_by_xpath(\"//input[@id='chkID']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click()",
"Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\") self.SendKeysToElement(self.GetElementById(\"txtMobileNo\"), \"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple",
"expected_conditions from selenium.common.exceptions import NoSuchElementException import time, math class PageGetSet: def __init__(self): self.PET_OWNERS",
"return False def SendKeysToElement(self, element, keys): element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until(",
"self.Browser.switch_to_alert() alert.accept() print(\"Testing Pet Owners Details Finish\") self.Sleep(3) def Inventory(self): print(\"Testing Inventory Start\")",
"print(\"Testing Vets Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self):",
"element.clear() element.send_keys(keys) def WaitForElementToExist(self, id): WebDriverWait(self.Browser, 3).until( expected_conditions.visibility_of_element_located( (By.ID, id) ) ) def",
"\"success\": 0, \"fail\": 0, \"max\": 0 } self.CurrentPage = self.PET_OWNERS self.InitializeBrowser(\"http://localhost:50452/\" + self.Pages[self.CurrentPage])",
"self.Browser = None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\", \"Vets.aspx\", \"VetDetails.aspx\",",
"\"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Pet Owners Finish\") self.Sleep(3) def PetOwnersDetails(self): print(\"Testing Pet Owners Details",
"self.APPOINTMENT_DETAILS = 6 self.Browser = None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\",",
"False): return False return True except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self):",
"= 6 self.Browser = None self.WorkElement = None self.Pages = [ \"PetOwners.aspx\", \"Inventory.aspx\",",
"self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Inventory Finish\") self.Sleep(3) def Vets(self): print(\"Testing Vets Start\") self.SwitchToPage(self.VETS)",
"def Sleep(self, length): time.sleep(length) def IfExistById(self, id): try: value = self.GetElementById(id) if(value ==",
"def ClickElement(self, element): element.click() def ClickElementById(self, elementId): self.GetElementById(elementId).click() def Sleep(self, length): time.sleep(length) def",
"try: value = self.GetElementById(id) if(value == False): return False return True except NoSuchElementException:",
"self.Browser = webdriver.Firefox() self.Browser.get(address) def UpdateStatistics(self, status): self.Statistics[status] += 1 self.Statistics[\"max\"] += 1",
"self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//div[@id='Panel1']//div//div//tbody//tr[4]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='txtQuantity']\").click() self.SendKeysToElement(self.GetElementById(\"txtQuantity\"), \"2\") self.Browser.find_element_by_xpath(\"//input[@id='btnAddMedication']\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.SendKeysToElement(self.GetElementById(\"txtSearchPet\"),",
"Start\") self.SwitchToPage(self.VETS) self.SendKeysToElement(self.GetElementById(\"txtSearch\"), \"Arnold\") self.Browser.find_element_by_xpath(\"//input[@id='btnSearch']\").click() print(\"Testing Vets Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets",
"= 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS = 5 self.APPOINTMENT_DETAILS =",
"Start\") self.SwitchToPage(self.APPOINTMENTS) print(\"Testing Appointments Finish\") self.Sleep(3) def AppointmentsDetails(self): print(\"Testing Appointments Details Start\") self.SwitchToPage(self.APPOINTMENT_DETAILS)",
"self.INVENTORY = 1 self.VETS = 2 self.VETS_DETAILS = 3 self.APPOINTMENTS = 4 self.PET_OWNER_DETAILS",
"\"Cakes\") self.Browser.find_element_by_xpath(\"//input[@id='chkPaid']\").click() self.SendKeysToElement(self.GetElementById(\"txtComments\"), \"Cakes are tasty and good yis\") self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewPets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//div//div//div//table[@id='GridViewVets']//tbody//tr[2]//td[1]//input[1]\").click() self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert",
"\"56675675\") self.SendKeysToElement(self.GetElementById(\"txtEmail\"), \"<EMAIL>\") self.SendKeysToElement(self.GetElementById(\"txtAddress\"), \"50 apple cross ave\") self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click()",
"self.SendKeysToElement(self.GetElementById(\"txtPostcode\"), \"6023\") self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='btnSave']\").click() alert = self.Browser.switch_to_alert() alert.accept() self.Browser.find_element_by_xpath(\"//option[@value='Feb']\").click() self.SendKeysToElement(self.GetElementById(\"txtSkills\"), \"BodyBuilder\") self.Browser.find_element_by_xpath(\"//input[@id='chkTue']\").click()",
"return False return True except NoSuchElementException: print(\"NO PAGE\") return False def PetOwners(self): print(\"Testing",
"Finish\") self.Sleep(3) def VetsDetails(self): print(\"Testing Vets Details Start\") self.SwitchToPage(self.VETS_DETAILS) self.SendKeysToElement(self.GetElementById(\"txtFirstName\"), \"Arnold\") self.SendKeysToElement(self.GetElementById(\"txtLastName\"), \"Schwarzenegger\")"
] |
[
"path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/',",
"path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company',",
"BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/',",
"path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/',",
"account_views from django.urls import path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView,",
"import path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView,",
"name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"),",
"path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/',",
"name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'),",
"path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/',",
"path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/',",
"name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect, name=\"connect\"),",
"path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect, name=\"connect\"), path('dashboard/my-account/',",
"import views as account_views from django.urls import path, reverse from .views import (AboutPageView,",
"name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(),",
"path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect,",
"DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'),",
"path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(),",
"name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'),",
"name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect, name=\"connect\"), path('dashboard/my-account/', account_views.AccountDetailView.as_view(), name='my-account'),",
"[ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'),",
"import name from accounts import views as account_views from django.urls import path, reverse",
"path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView,",
"name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'),",
"StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'),",
"path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(),",
"name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(),",
"views as account_views from django.urls import path, reverse from .views import (AboutPageView, AuctionCreateView,",
"AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'),",
"StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(),",
"HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(),",
"AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(),",
"HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(),",
"from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView)",
"from accounts import views as account_views from django.urls import path, reverse from .views",
"AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(),",
"from unicodedata import name from accounts import views as account_views from django.urls import",
"import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns =",
"AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name=",
"accounts import views as account_views from django.urls import path, reverse from .views import",
"AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(),",
"'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'),",
"BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(),",
"account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect, name=\"connect\"), path('dashboard/my-account/', account_views.AccountDetailView.as_view(),",
"DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name=",
"as account_views from django.urls import path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView,",
"BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(),",
"DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/',",
"name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'),",
"path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/', account_views.connect, name=\"connect\"), path('dashboard/my-account/', account_views.AccountDetailView.as_view(), name='my-account'), ]",
".views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns",
"name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'),",
"AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [ path('',",
"name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'),",
"'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/',",
"django.urls import path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView,",
"name from accounts import views as account_views from django.urls import path, reverse from",
"(AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView, StripeConnectionView,MyAuctionDetailView,AuctionUpdateView) urlpatterns = [",
"unicodedata import name from accounts import views as account_views from django.urls import path,",
"urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/',",
"MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'), path('dashboard/connect/',",
"name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(), name= 'auction-create'), path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'),",
"reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView, BidDetailView, DashboardPageView, DatasourceView, HomePageView,",
"path('bids/create/',BidCreateView.as_view(), name= 'bid-create'), path('bid-detail/<int:pk>/', BidDetailView.as_view(), name='bid-detail'), path('stripe-connection/', StripeConnectionView.as_view(), name='stripe-connection'), path('data-source/',DatasourceView.as_view(), name='data-source'), path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'),",
"path('dashboard/my-auction/', MyAuctionDetailView.as_view(),name='my-auction'), path('auction-update/<int:pk>/',AuctionUpdateView.as_view(), name='auction-update'), path('dashboard/company/my-company', account_views.MyCompanyDetailView.as_view(), name='my-company'), path('dashboard/company/<int:pk>/', account_views.CompanyUpdateView.as_view(), name=\"company-update\"), path('dashboard/company/create/', account_views.CompanyCreateView.as_view(), name='company-create'),",
"= [ path('', HomePageView.as_view(), name='home'), path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(),",
"path('about/', AboutPageView.as_view(), name='about'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('auctions/', AuctionListView.as_view(), name='auctions'), path('auction-detail/<int:pk>/', AuctionDetailView.as_view(), name='auction-detail'), path('auctions/create/',AuctionCreateView.as_view(),",
"from django.urls import path, reverse from .views import (AboutPageView, AuctionCreateView, AuctionDetailView, AuctionListView, BidCreateView,"
] |
[
"\"PASSWORD\" # If using oauth, set OAUTH = True, set USERNAME = \"CLIENT_ID\"",
"set OAUTH = True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False",
"# To check against mutiple specified projects: ex: [15, 17] # Use the",
"= False # Input / Output settings filter_id = 165 # Project's to",
"otherwise set to None filter_project_id = None # Enter the location for the",
"JAMA_CONNECT_URL = \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth,",
"= [] # if your filter is set to use 'Current Project' then",
"# Input / Output settings filter_id = 165 # Project's to check sync",
"to use 'Current Project' then you must supply a project_id. otherwise set to",
"PASSWORD = \"PASSWORD\" # If using oauth, set OAUTH = True, set USERNAME",
"character string to separate values. delimiter = ',' # Logging date time format",
"to separate values. delimiter = ',' # Logging date time format log_date_time_format =",
"specified projects: ex: [15, 17] # Use the empty list to check all",
"empty list to check all against all projects ex: [] project_list = []",
"value should be a list ex: [14] # To check against mutiple specified",
"values. delimiter = ',' # Logging date time format log_date_time_format = \"%Y-%m-%d %H_%M_%S\"",
"# Use the empty list to check all against all projects ex: []",
"to True or False csv_header = True # A one character string to",
"# if your filter is set to use 'Current Project' then you must",
"check against mutiple specified projects: ex: [15, 17] # Use the empty list",
"17] # Use the empty list to check all against all projects ex:",
"False csv_header = True # A one character string to separate values. delimiter",
"csv_header = True # A one character string to separate values. delimiter =",
"projects: ex: [15, 17] # Use the empty list to check all against",
"check all against all projects ex: [] project_list = [] # if your",
"or False csv_header = True # A one character string to separate values.",
"To check against mutiple specified projects: ex: [15, 17] # Use the empty",
"If using oauth, set OAUTH = True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\"",
"settings filter_id = 165 # Project's to check sync status against. # This",
"\"./sync_status.csv\" # CSV Settings # Output header row in CSV. Must be set",
"and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output settings filter_id = 165",
"False # Input / Output settings filter_id = 165 # Project's to check",
"Project's to check sync status against. # This value should be a list",
"Settings JAMA_CONNECT_URL = \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If using",
"projects ex: [] project_list = [] # if your filter is set to",
"Settings # Output header row in CSV. Must be set to True or",
"output. output_location = \"./sync_status.csv\" # CSV Settings # Output header row in CSV.",
"= None # Enter the location for the output. output_location = \"./sync_status.csv\" #",
"then you must supply a project_id. otherwise set to None filter_project_id = None",
"against mutiple specified projects: ex: [15, 17] # Use the empty list to",
"Use the empty list to check all against all projects ex: [] project_list",
"you must supply a project_id. otherwise set to None filter_project_id = None #",
"PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output settings filter_id = 165 #",
"use 'Current Project' then you must supply a project_id. otherwise set to None",
"[15, 17] # Use the empty list to check all against all projects",
"= \"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth, set OAUTH = True,",
"header row in CSV. Must be set to True or False csv_header =",
"supply a project_id. otherwise set to None filter_project_id = None # Enter the",
"set to None filter_project_id = None # Enter the location for the output.",
"= 165 # Project's to check sync status against. # This value should",
"to check all against all projects ex: [] project_list = [] # if",
"= \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth, set",
"# Enter the location for the output. output_location = \"./sync_status.csv\" # CSV Settings",
"True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input /",
"= \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output settings filter_id",
"/ Output settings filter_id = 165 # Project's to check sync status against.",
"USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output settings",
"= \"PASSWORD\" # If using oauth, set OAUTH = True, set USERNAME =",
"set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output",
"the empty list to check all against all projects ex: [] project_list =",
"\"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth, set OAUTH = True, set",
"set to use 'Current Project' then you must supply a project_id. otherwise set",
"location for the output. output_location = \"./sync_status.csv\" # CSV Settings # Output header",
"CSV Settings # Output header row in CSV. Must be set to True",
"filter_project_id = None # Enter the location for the output. output_location = \"./sync_status.csv\"",
"project_id. otherwise set to None filter_project_id = None # Enter the location for",
"be a list ex: [14] # To check against mutiple specified projects: ex:",
"if your filter is set to use 'Current Project' then you must supply",
"ex: [] project_list = [] # if your filter is set to use",
"set to True or False csv_header = True # A one character string",
"must supply a project_id. otherwise set to None filter_project_id = None # Enter",
"None filter_project_id = None # Enter the location for the output. output_location =",
"ex: [14] # To check against mutiple specified projects: ex: [15, 17] #",
"[] project_list = [] # if your filter is set to use 'Current",
"Output header row in CSV. Must be set to True or False csv_header",
"Output settings filter_id = 165 # Project's to check sync status against. #",
"Enter the location for the output. output_location = \"./sync_status.csv\" # CSV Settings #",
"\"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input / Output settings filter_id =",
"one character string to separate values. delimiter = ',' # Logging date time",
"list ex: [14] # To check against mutiple specified projects: ex: [15, 17]",
"in CSV. Must be set to True or False csv_header = True #",
"Must be set to True or False csv_header = True # A one",
"be set to True or False csv_header = True # A one character",
"= \"./sync_status.csv\" # CSV Settings # Output header row in CSV. Must be",
"# A one character string to separate values. delimiter = ',' # Logging",
"to check sync status against. # This value should be a list ex:",
"ex: [15, 17] # Use the empty list to check all against all",
"project_list = [] # if your filter is set to use 'Current Project'",
"<filename>config.py # Connection Settings JAMA_CONNECT_URL = \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\"",
"should be a list ex: [14] # To check against mutiple specified projects:",
"the location for the output. output_location = \"./sync_status.csv\" # CSV Settings # Output",
"CSV. Must be set to True or False csv_header = True # A",
"[] # if your filter is set to use 'Current Project' then you",
"using oauth, set OAUTH = True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH",
"= True # A one character string to separate values. delimiter = ','",
"# Project's to check sync status against. # This value should be a",
"your filter is set to use 'Current Project' then you must supply a",
"status against. # This value should be a list ex: [14] # To",
"all projects ex: [] project_list = [] # if your filter is set",
"filter is set to use 'Current Project' then you must supply a project_id.",
"oauth, set OAUTH = True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH =",
"row in CSV. Must be set to True or False csv_header = True",
"# CSV Settings # Output header row in CSV. Must be set to",
"None # Enter the location for the output. output_location = \"./sync_status.csv\" # CSV",
"Connection Settings JAMA_CONNECT_URL = \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If",
"165 # Project's to check sync status against. # This value should be",
"against all projects ex: [] project_list = [] # if your filter is",
"'Current Project' then you must supply a project_id. otherwise set to None filter_project_id",
"against. # This value should be a list ex: [14] # To check",
"to None filter_project_id = None # Enter the location for the output. output_location",
"string to separate values. delimiter = ',' # Logging date time format log_date_time_format",
"[14] # To check against mutiple specified projects: ex: [15, 17] # Use",
"USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth, set OAUTH =",
"for the output. output_location = \"./sync_status.csv\" # CSV Settings # Output header row",
"OAUTH = True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False #",
"= True, set USERNAME = \"CLIENT_ID\" and PASSWORD=\"<PASSWORD>\" OAUTH = False # Input",
"\"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" # If using oauth, set OAUTH",
"list to check all against all projects ex: [] project_list = [] #",
"output_location = \"./sync_status.csv\" # CSV Settings # Output header row in CSV. Must",
"all against all projects ex: [] project_list = [] # if your filter",
"separate values. delimiter = ',' # Logging date time format log_date_time_format = \"%Y-%m-%d",
"# Output header row in CSV. Must be set to True or False",
"# This value should be a list ex: [14] # To check against",
"the output. output_location = \"./sync_status.csv\" # CSV Settings # Output header row in",
"Project' then you must supply a project_id. otherwise set to None filter_project_id =",
"mutiple specified projects: ex: [15, 17] # Use the empty list to check",
"filter_id = 165 # Project's to check sync status against. # This value",
"True # A one character string to separate values. delimiter = ',' #",
"Input / Output settings filter_id = 165 # Project's to check sync status",
"a list ex: [14] # To check against mutiple specified projects: ex: [15,",
"True or False csv_header = True # A one character string to separate",
"check sync status against. # This value should be a list ex: [14]",
"a project_id. otherwise set to None filter_project_id = None # Enter the location",
"sync status against. # This value should be a list ex: [14] #",
"# Connection Settings JAMA_CONNECT_URL = \"https://instance.jamacloud.com\" USERNAME = \"USERNAME\" PASSWORD = \"PASSWORD\" #",
"# If using oauth, set OAUTH = True, set USERNAME = \"CLIENT_ID\" and",
"is set to use 'Current Project' then you must supply a project_id. otherwise",
"OAUTH = False # Input / Output settings filter_id = 165 # Project's",
"This value should be a list ex: [14] # To check against mutiple",
"A one character string to separate values. delimiter = ',' # Logging date"
] |
[
"\"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page and",
"@utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result for a",
"alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result for",
"\"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]: event[\"stdout\"].write(page[\"AbstractURL\"]) else: event[\"stderr\"].write(\"No",
"<reponame>dngfx/MagicBot # --depends-on commands from src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class",
"\"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]: event[\"stdout\"].write(page[\"AbstractURL\"]) else: event[\"stderr\"].write(\"No results found\")",
"min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result for a given",
"= utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", },",
":usage: [search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page =",
"class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\"",
"duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result for a given search term",
"term :usage: [search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page",
"\"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo",
"term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG,",
"--depends-on commands from src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name",
":help: Get first DuckDuckGo result for a given search term :usage: [search term]",
"DuckDuckGo result for a given search term :usage: [search term] \"\"\" phrase =",
"# --depends-on commands from src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule):",
"a given search term :usage: [search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get()",
"[search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request(",
"get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page",
"Get first DuckDuckGo result for a given search term :usage: [search term] \"\"\"",
"\"1\", \"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]: event[\"stdout\"].write(page[\"AbstractURL\"]) else: event[\"stderr\"].write(\"No results",
"for a given search term :usage: [search term] \"\"\" phrase = event[\"args\"] or",
"utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1)",
"def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result for a given search",
"\"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]: event[\"stdout\"].write(page[\"AbstractURL\"]) else:",
"if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\",",
"first DuckDuckGo result for a given search term :usage: [search term] \"\"\" phrase",
"or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\",",
"event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\":",
"= \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first",
"Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help:",
"\"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={",
"= \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self,",
"event): \"\"\" :help: Get first DuckDuckGo result for a given search term :usage:",
"given search term :usage: [search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if",
"\"\"\" :help: Get first DuckDuckGo result for a given search term :usage: [search",
"src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\",",
"= event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase,",
"URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def",
"phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]:",
"\"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if page and page[\"AbstractURL\"]: event[\"stdout\"].write(page[\"AbstractURL\"])",
"commands from src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name =",
"ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\",",
"@utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get first DuckDuckGo result",
"result for a given search term :usage: [search term] \"\"\" phrase = event[\"args\"]",
"utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json()",
"URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\", }, ).json() if",
"phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\":",
"\"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event):",
"search term :usage: [search term] \"\"\" phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase:",
"from src import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\"",
"phrase = event[\"args\"] or event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\":",
"_name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\") @utils.hook(\"received.command.ddg\", min_args=1) def duckduckgo(self, event): \"\"\" :help: Get",
"event[\"target\"].buffer.get() if phrase: page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\":",
"import ModuleManager, utils URL_DDG = \"https://api.duckduckgo.com\" class Module(ModuleManager.BaseModule): _name = \"DDG\" @utils.hook(\"received.command.duckduckgo\", alias_of=\"ddg\")",
"page = utils.http.request( URL_DDG, get_params={ \"q\": phrase, \"format\": \"json\", \"no_html\": \"1\", \"no_redirect\": \"1\","
] |
[
"= 'Twitter bot' __version__ = '1.0' __author__ = '<NAME>' __license__ = 'MIT license'",
"__title__ = 'Twitter bot' __version__ = '1.0' __author__ = '<NAME>' __license__ = 'MIT",
"__author__ = '<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright 2016 <NAME>' #",
"__version__ = '1.0' __author__ = '<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright",
"'Twitter bot' __version__ = '1.0' __author__ = '<NAME>' __license__ = 'MIT license' __copyright__",
"= 'MIT license' __copyright__ = 'Copyright 2016 <NAME>' # Version synonym VERSION =",
"'MIT license' __copyright__ = 'Copyright 2016 <NAME>' # Version synonym VERSION = __version__",
"'<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright 2016 <NAME>' # Version synonym",
"__license__ = 'MIT license' __copyright__ = 'Copyright 2016 <NAME>' # Version synonym VERSION",
"'1.0' __author__ = '<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright 2016 <NAME>'",
"= '<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright 2016 <NAME>' # Version",
"bot' __version__ = '1.0' __author__ = '<NAME>' __license__ = 'MIT license' __copyright__ =",
"<gh_stars>1-10 __title__ = 'Twitter bot' __version__ = '1.0' __author__ = '<NAME>' __license__ =",
"= '1.0' __author__ = '<NAME>' __license__ = 'MIT license' __copyright__ = 'Copyright 2016"
] |
[
"OSError if unset.\"\"\" env = os.getenv(name) if not env: raise OSError(f\"Environment variable {name}",
"raise OSError if unset.\"\"\" env = os.getenv(name) if not env: raise OSError(f\"Environment variable",
"<gh_stars>0 import os def getenv(name): \"\"\"Return the environment variable named `name`, or raise",
"unset.\"\"\" env = os.getenv(name) if not env: raise OSError(f\"Environment variable {name} is not",
"import os def getenv(name): \"\"\"Return the environment variable named `name`, or raise OSError",
"getenv(name): \"\"\"Return the environment variable named `name`, or raise OSError if unset.\"\"\" env",
"= os.getenv(name) if not env: raise OSError(f\"Environment variable {name} is not set\") return",
"os def getenv(name): \"\"\"Return the environment variable named `name`, or raise OSError if",
"the environment variable named `name`, or raise OSError if unset.\"\"\" env = os.getenv(name)",
"or raise OSError if unset.\"\"\" env = os.getenv(name) if not env: raise OSError(f\"Environment",
"environment variable named `name`, or raise OSError if unset.\"\"\" env = os.getenv(name) if",
"variable named `name`, or raise OSError if unset.\"\"\" env = os.getenv(name) if not",
"named `name`, or raise OSError if unset.\"\"\" env = os.getenv(name) if not env:",
"\"\"\"Return the environment variable named `name`, or raise OSError if unset.\"\"\" env =",
"os.getenv(name) if not env: raise OSError(f\"Environment variable {name} is not set\") return env",
"if unset.\"\"\" env = os.getenv(name) if not env: raise OSError(f\"Environment variable {name} is",
"env = os.getenv(name) if not env: raise OSError(f\"Environment variable {name} is not set\")",
"`name`, or raise OSError if unset.\"\"\" env = os.getenv(name) if not env: raise",
"def getenv(name): \"\"\"Return the environment variable named `name`, or raise OSError if unset.\"\"\""
] |
[
"\"\"\" Load and preprocess a list of images. \"\"\" imgs = [] for",
"feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1) % params.save_period ==",
"...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions = [] # Generate the",
"of images. \"\"\" imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs =",
"desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train CNN and RNN feed_dict =",
"%s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name,",
"k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file = img_files[0] img_name",
"= False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def",
"= img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files",
"= train_data.next_batch() if self.train_cnn: # Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True)",
"[] # Generate the captions for the images for k in tqdm(list(range(test_data.count))): batch",
"is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train the",
"/ 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img",
"in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file = img_files[0] img_name =",
"= mode self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn",
"self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save",
"= self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in",
"self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn",
"self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size,",
"batch = train_data.next_batch() if self.train_cnn: # Train CNN and RNN feed_dict = self.get_feed_dict(batch,",
"= img - self.mean return img def load_imgs(self, img_files): \"\"\" Load and preprocess",
"= temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape)",
"var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except",
"img = img - self.mean return img def load_imgs(self, img_files): \"\"\" Load and",
"pd import tensorflow as tf import cv2 import matplotlib.pyplot as plt import matplotlib.image",
"0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate",
"* from utils.words import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import *",
"print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions = []",
"# Train RNN only img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files) if",
"Load and preprocess an image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp =",
"offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean",
"for param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1",
"ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise",
"contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1,",
"= params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor",
"params self.mode = mode self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model =",
"get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\"",
"self.mean return img def load_imgs(self, img_files): \"\"\" Load and preprocess a list of",
"session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count +=",
"epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if",
"train_data): \"\"\" Train the model. \"\"\" print(\"Training the model...\") params = self.params num_epochs",
"is None: print(\"Error: No saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path)",
"utils.words import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object):",
"img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict =",
"model. \"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self,",
"self.params.val_result_dir # Generate the captions for the images for k in tqdm(list(range(val_data.count))): batch",
"if self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0, 2)",
"Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load",
"if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table =",
"def load_img(self, img_file): \"\"\" Load and preprocess an image. \"\"\" img = cv2.imread(img_file)",
"= [224, 224, 3] self.global_step = tf.Variable(0, name = 'global_step', trainable = False)",
"contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts)",
"self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch,",
"CNN model from %s...\" %data_path) data_dict = np.load(data_path).item() count = 0 miss_count =",
"= True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean",
"self.crop_shape) / 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img =",
"= tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved model found. Please train",
"= mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco",
"test(self, sess, test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the model ...\")",
"for the images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch",
"def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data):",
"= tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None,",
"the model. \"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def",
"for the images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch",
"2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img -",
"224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess an",
"import numpy as np import pandas as pd import tensorflow as tf import",
"loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN",
"and preprocess an image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0,",
"__init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224,",
"desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train",
"self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch,",
"for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try:",
"reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count +=",
"img def load_imgs(self, img_files): \"\"\" Load and preprocess a list of images. \"\"\"",
"= [] # Generate the captions for the images for k in tqdm(list(range(test_data.count))):",
"\"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved",
"= self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict =",
"train_data.next_batch() if self.train_cnn: # Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _,",
"the model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions = [] #",
"= mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a",
"tqdm from dataset import * from utils.words import * from utils.coco.coco import *",
"= WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224,",
"the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error:",
"params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir =",
"self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts,",
"self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False})",
"plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results)",
"test_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict",
"is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True,",
"224, 3] self.global_step = tf.Variable(0, name = 'global_step', trainable = False) self.build() self.saver",
"1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d variables loaded.",
"#print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d variables loaded. %d",
"100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError()",
"try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name))",
"self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224,",
"# Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step",
"feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id':",
"False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len,",
"self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files, _, _ = batch imgs",
"self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess an image. \"\"\"",
"from utils.words import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class",
"batch = val_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if",
"sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an image file img",
"np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess an image.",
"= self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k],",
"img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0],",
"= self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats,",
"val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the model ...\") results =",
"is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs,",
"self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0, 2) img",
"self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir,",
"for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class BaseModel(object):",
"train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training the model...\") params = self.params",
"img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions",
"json import numpy as np import pandas as pd import tensorflow as tf",
"for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file = img_files[0]",
"\"\"\" Validate the model. \"\"\" print(\"Validating the model ...\") results = [] result_dir",
"an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() #",
"= sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts",
"CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op,",
"complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the",
"Train RNN only img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats:",
"= self.params.test_result_dir captions = [] # Generate the captions for the images for",
"+ 1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self,",
"\"\"\" print(\"Validating the model ...\") results = [] result_dir = self.params.val_result_dir # Generate",
"for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train CNN",
"(self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :]",
"sys import json import numpy as np import pandas as pd import tensorflow",
"params, mode): self.params = params self.mode = mode self.batch_size = params.batch_size if mode=='train'",
"image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp =",
"np.load(data_path).item() count = 0 miss_count = 0 for op_name in data_dict: with tf.variable_scope(op_name,",
"<gh_stars>0 import os import sys import json import numpy as np import pandas",
"(self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32) img",
"to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the",
"self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats],",
"os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats:",
"model. \"\"\" print(\"Validating the model ...\") results = [] result_dir = self.params.val_result_dir #",
"model. \"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions",
"val_data.img_ids[k], 'caption': sentence}) # Save the result in an image file img =",
"np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self, params, mode): self.params = params",
"img_files): \"\"\" Load and preprocess a list of images. \"\"\" imgs = []",
"self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape =",
"in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) #",
"pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save the model. \"\"\"",
"WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3]",
"2) temp = temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1]))",
"for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file = img_files[0]",
"print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\"",
"loaded\" %(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name))",
"from %s...\" %data_path) data_dict = np.load(data_path).item() count = 0 miss_count = 0 for",
"def save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving model to %s\" %",
"params = self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx",
"import tqdm from dataset import * from utils.words import * from utils.coco.coco import",
"self.params = params self.mode = mode self.batch_size = params.batch_size if mode=='train' else 1",
"print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1) % params.save_period == 0:",
"self.params.test_result_dir captions = [] # Generate the captions for the images for k",
"batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False})",
"tqdm import tqdm from dataset import * from utils.words import * from utils.coco.coco",
"num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'):",
"scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test the model. \"\"\"",
"file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save",
"in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self,",
"image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the",
"= tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError:",
"NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training the",
"def test(self, sess, test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the model",
"else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats,",
"3] self.global_step = tf.Variable(0, name = 'global_step', trainable = False) self.build() self.saver =",
"self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0, name =",
"img_name+'_result.jpg')) # Save the captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file)",
"temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape",
"mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco =",
"img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else:",
"\"\"\" Test the model. \"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir",
"img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1] img",
"save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving model to %s\" % self.save_dir))",
"data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name)",
"data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name,",
"224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file):",
"img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self, params,",
"contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts)",
"self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption':",
"= (self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1],",
"val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate()",
"import sys import json import numpy as np import pandas as pd import",
"results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result in an image file img",
"import matplotlib.image as mpimg from tqdm import tqdm from dataset import * from",
"a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\"",
"\"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading CNN model from %s...\" %data_path)",
"and preprocess a list of images. \"\"\" imgs = [] for img_file in",
"def load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir)",
"= img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img,",
"val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False):",
"batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False)",
"mpimg from tqdm import tqdm from dataset import * from utils.words import *",
"imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return",
"if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats",
"model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True):",
"\"\"\" Save the model. \"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir,",
"Generate the captions for the images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch()",
"val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess,",
"feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op,",
"self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1)",
"self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if",
"img_file): \"\"\" Load and preprocess an image. \"\"\" img = cv2.imread(img_file) if self.bgr:",
"= self.params.test_result_file result_dir = self.params.test_result_dir captions = [] # Generate the captions for",
"feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats:",
"contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f",
"import pandas as pd import tensorflow as tf import cv2 import matplotlib.pyplot as",
"self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result in an image file",
"plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a file results = pd.DataFrame({'image_files':test_data.img_files,",
"= os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file)",
"img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs =",
"feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1,",
"print(\"Loading CNN model from %s...\" %data_path) data_dict = np.load(data_path).item() count = 0 miss_count",
"= [] result_dir = self.params.val_result_dir # Generate the captions for the images for",
"CNN model. \"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict = np.load(data_path).item() count",
"val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test the model.",
"0 miss_count = 0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name,",
"result_dir = self.params.val_result_dir # Generate the captions for the images for k in",
"tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count",
"preprocess a list of images. \"\"\" imgs = [] for img_file in img_files:",
"plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer =",
"self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files, _, _ =",
"import matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm import tqdm from",
"tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved model found. Please train first.\")",
"mode): self.params = params self.mode = mode self.batch_size = params.batch_size if mode=='train' else",
"RNN only img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts,",
"print(\"Validating the model ...\") results = [] result_dir = self.params.val_result_dir # Generate the",
"self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate the",
"load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading CNN",
"= self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an image file img =",
"feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence)",
"[224, 224, 3] self.global_step = tf.Variable(0, name = 'global_step', trainable = False) self.build()",
"# Save the result in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off')",
"an image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp",
"as np import pandas as pd import tensorflow as tf import cv2 import",
"print(\"Error: No saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self,",
"= tf.Variable(0, name = 'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep =",
"if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True,",
"None: print(\"Error: No saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def",
"sess, train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training the model...\") params =",
"the images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file",
"data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading CNN model",
"# Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation",
"as tf import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from",
"sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts =",
"self.global_step = tf.Variable(0, name = 'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep",
"the result in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir,",
"print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing",
"feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs,",
"* from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self,",
"result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save",
"= self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict)",
"captions.append(sentence) # Save the result in an image file img = mpimg.imread(img_file) plt.imshow(img)",
"contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train the model.",
"'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving",
"self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1)",
"contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) #",
"feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats =",
"if checkpoint is None: print(\"Error: No saved model found. Please train first.\") sys.exit(0)",
"plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer",
"contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result",
"in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var =",
"count += 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count += 1",
"= ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0, name = 'global_step',",
"in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train CNN and RNN",
"= 0 miss_count = 0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for",
"in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file = img_files[0] img_name =",
"1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else",
"1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess,",
"as mpimg from tqdm import tqdm from dataset import * from utils.words import",
"pandas as pd import tensorflow as tf import cv2 import matplotlib.pyplot as plt",
"_, _ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats,",
"sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence",
"0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems():",
"in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset()",
"mode self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn =",
"if self.train_cnn: # Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0,",
"self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\")",
"data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s",
"feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result",
"def val(self, sess, val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the model",
"= params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/')",
"= np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def",
"self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch,",
"params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch =",
"RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1,",
"[] result_dir = self.params.val_result_dir # Generate the captions for the images for k",
"= test_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn:",
"% self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the model. \"\"\"",
"Test the model. \"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir =",
"file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions",
"result_dir = self.params.test_result_dir captions = [] # Generate the captions for the images",
"os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs =",
"the model ...\") results = [] result_dir = self.params.val_result_dir # Generate the captions",
"matplotlib.image as mpimg from tqdm import tqdm from dataset import * from utils.words",
"= pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save the model.",
"= sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step",
"params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0,",
"self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN model.",
"else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16'",
"== 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\"",
"= temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset =",
"cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm import tqdm",
"import json import numpy as np import pandas as pd import tensorflow as",
"except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing:",
"COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test the",
"utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file): self.bgr",
"Load the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None:",
"sentence}) # Save the result in an image file img = mpimg.imread(img_file) plt.imshow(img)",
"build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self,",
"self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts,",
"a pretrained CNN model. \"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict =",
"contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results,",
"= self.params.val_result_dir # Generate the captions for the images for k in tqdm(list(range(val_data.count))):",
"loss1)) if (global_step + 1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training",
"self.params.test_result_file result_dir = self.params.test_result_dir captions = [] # Generate the captions for the",
"print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved model",
"params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table",
"\"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess):",
"- self.crop_shape) / 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img",
"import * from utils.words import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import",
"img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch",
"in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn:",
"plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a file results =",
"self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0,",
"= img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return img def load_imgs(self,",
"\"\"\" imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32)",
"self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False",
"Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step =",
"plt import matplotlib.image as mpimg from tqdm import tqdm from dataset import *",
"= val_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn:",
"self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats,",
"result in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg'))",
"missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d variables loaded. %d variables missed.\"",
"self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats",
"mean_file): self.bgr = True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224],",
"%(op_name, param_name)) if not ignore_missing: raise print(\"%d variables loaded. %d variables missed.\" %(count,",
"feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an image file",
"\"\"\" img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1]",
"= os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs",
"False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def get_feed_dict(self,",
"global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files,",
"tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train CNN and RNN feed_dict",
"= np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self, params, mode): self.params =",
"Validate the model. \"\"\" print(\"Validating the model ...\") results = [] result_dir =",
"temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) /",
"imgs = np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self, params, mode): self.params",
"pretrained CNN model. \"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict = np.load(data_path).item()",
"if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts,",
"the captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def",
"tensorflow as tf import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg",
"\"\"\" Load and preprocess an image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp",
"cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0,",
"the model. \"\"\" print(\"Validating the model ...\") results = [] result_dir = self.params.val_result_dir",
"self.bgr = True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32)",
"self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train,",
"the images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file",
"= sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step",
"= self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) #",
"param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not",
"feed_dict=feed_dict) else: # Train RNN only img_files, _, _ = batch imgs =",
"self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate the model. \"\"\"",
"import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def",
"params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step",
"plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a file results",
"img - self.mean return img def load_imgs(self, img_files): \"\"\" Load and preprocess a",
"feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step],",
"\"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is",
"plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions})",
"ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0, name = 'global_step', trainable",
"import os import sys import json import numpy as np import pandas as",
"os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape",
"trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError()",
"idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: # Train CNN and",
"%s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d variables loaded. %d variables",
"_ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats],",
"img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2 offset",
"tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0]",
"= 'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self):",
"op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var",
"result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in",
"is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\"",
"= 100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise",
"is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats =",
"model. \"\"\" print(\"Training the model...\") params = self.params num_epochs = params.num_epochs for epoch_no",
"load_imgs(self, img_files): \"\"\" Load and preprocess a list of images. \"\"\" imgs =",
"name = 'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def",
"sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step +",
"is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence})",
"'caption': sentence}) # Save the result in an image file img = mpimg.imread(img_file)",
"\"\"\" print(\"Training the model...\") params = self.params num_epochs = params.num_epochs for epoch_no in",
"sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files, _, _",
"_, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train",
"and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0,",
"print(\"Training the model...\") params = self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)),",
"sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint",
"batch = test_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if",
"batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train",
"if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False,",
"np import pandas as pd import tensorflow as tf import cv2 import matplotlib.pyplot",
"results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving model",
"else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False})",
"NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess, train_coco,",
"the model. \"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir",
"preprocess an image. \"\"\" img = cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2)",
"params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor =",
"sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result in an",
"file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these",
"feats=None): raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train the model. \"\"\"",
"temp = temp[::-1] img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset",
"%s...\" %data_path) data_dict = np.load(data_path).item() count = 0 miss_count = 0 for op_name",
"self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files, _, _ = batch",
"the model. \"\"\" print(\"Training the model...\") params = self.params num_epochs = params.num_epochs for",
"BaseModel(object): def __init__(self, params, mode): self.params = params self.mode = mode self.batch_size =",
"- self.mean return img def load_imgs(self, img_files): \"\"\" Load and preprocess a list",
"img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to",
"img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return img def",
"# Generate the captions for the images for k in tqdm(list(range(test_data.count))): batch =",
"img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return img def load_imgs(self, img_files):",
"first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained",
"ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape",
"checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved model found. Please",
"self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32) img =",
"model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load",
"feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else:",
"the captions for the images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files",
"self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze())",
"import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file): self.bgr =",
"images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file =",
"(global_step + 1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def",
"def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading",
"feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence =",
"param_name)) if not ignore_missing: raise print(\"%d variables loaded. %d variables missed.\" %(count, miss_count))",
"raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def train(self, sess,",
"self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading",
"offset = (self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0],",
"__init__(self, params, mode): self.params = params self.mode = mode self.batch_size = params.batch_size if",
"is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: #",
"train(self, sess, train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training the model...\") params",
"self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0, name = 'global_step', trainable =",
"= self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict =",
"complete.\") def save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving model to %s\"",
"np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\"",
"is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False,",
"class ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224, 224], np.int32)",
"self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False})",
"result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions = [] # Generate the captions",
"model. \"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict = np.load(data_path).item() count =",
"model...\") params = self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for",
"params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats =",
"= batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs,",
"checkpoint is None: print(\"Error: No saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess,",
"\"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions =",
":] img = img - self.mean return img def load_imgs(self, img_files): \"\"\" Load",
"load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if",
"_, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\"",
"raise NotImplementedError() def train(self, sess, train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training",
"#print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\"",
"results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess): \"\"\" Save the",
"self.get_feed_dict(batch, is_train=True) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else:",
"[] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class",
"captions for the images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files =",
"found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\"",
"scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\"",
"np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess",
"self.train_cnn: # Train CNN and RNN feed_dict = self.get_feed_dict(batch, is_train=True) _, loss0, loss1,",
"load_img(self, img_file): \"\"\" Load and preprocess an image. \"\"\" img = cv2.imread(img_file) if",
"contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats)",
"%data_path) data_dict = np.load(data_path).item() count = 0 miss_count = 0 for op_name in",
"cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2 offset = offset.astype(np.int32)",
"offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return img",
"to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self, sess):",
"ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading CNN model from %s...\"",
"model from %s...\" %data_path) data_dict = np.load(data_path).item() count = 0 miss_count = 0",
"= sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the",
"from dataset import * from utils.words import * from utils.coco.coco import * from",
"the model...\") params = self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'):",
"+= 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d variables",
"imgs class BaseModel(object): def __init__(self, params, mode): self.params = params self.mode = mode",
"contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats)",
"feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict",
"if (global_step + 1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\")",
"dataset import * from utils.words import * from utils.coco.coco import * from utils.coco.pycocoevalcap.eval",
"image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate",
"results = [] result_dir = self.params.val_result_dir # Generate the captions for the images",
"= self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict =",
"= cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2 offset =",
"as plt import matplotlib.image as mpimg from tqdm import tqdm from dataset import",
"np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self,",
"= img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs",
"* class ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224, 224],",
"as pd import tensorflow as tf import cv2 import matplotlib.pyplot as plt import",
"val(self, sess, val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the model ...\")",
"img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files)",
"train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate the model.",
"= val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data,",
"%(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if",
"self.crop_shape = np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load",
"Train the model. \"\"\" print(\"Training the model...\") params = self.params num_epochs = params.num_epochs",
"= np.array([224, 224], np.int32) self.mean = np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and",
"import * class ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224,",
"self.global_step) def load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint =",
"checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\"",
"os import sys import json import numpy as np import pandas as pd",
"if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files)",
"images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file =",
"from tqdm import tqdm from dataset import * from utils.words import * from",
"these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def",
"self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the model. \"\"\" print(\"Loading model...\") checkpoint",
"= COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test",
"model. \"\"\" print(\"Loading model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No",
"# Generate the captions for the images for k in tqdm(list(range(val_data.count))): batch =",
"feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result in",
"No saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path,",
"feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict",
"sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step =",
"params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step =",
"Load a pretrained CNN model. \"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict",
"feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _,",
"miss_count += 1 #print(\"Variable %s:%s missed\" %(op_name, param_name)) if not ignore_missing: raise print(\"%d",
"+= 1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable",
"else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result =",
"Save the captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\")",
"params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco, val_data):",
"loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0,",
"self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file)",
"images. \"\"\" imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs,",
"...\") results = [] result_dir = self.params.val_result_dir # Generate the captions for the",
"feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else:",
"= params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor self.save_dir",
"= cv2.imread(img_file) if self.bgr: temp = img.swapaxes(0, 2) temp = temp[::-1] img =",
"\"\"\" print(\"Loading CNN model from %s...\" %data_path) data_dict = np.load(data_path).item() count = 0",
"self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an image file img = mpimg.imread(img_file)",
"sess): \"\"\" Save the model. \"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess,",
"* from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file): self.bgr = True",
"self.word_table.load() self.img_loader = ImageLoader(params.mean_file) self.img_shape = [224, 224, 3] self.global_step = tf.Variable(0, name",
"self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader =",
"only img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats",
"%(loss0, loss1)) if (global_step + 1) % params.save_period == 0: self.save(sess) train_data.reset() self.save(sess)",
"= sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an",
"numpy as np import pandas as pd import tensorflow as tf import cv2",
"tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch() if self.train_cnn: #",
"= params self.mode = mode self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model",
"with tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data))",
"sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts =",
"test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the model ...\") result_file =",
"Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\")",
"list of images. \"\"\" imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs",
"self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats",
"= offset.astype(np.int32) img = img[offset[0]:offset[0]+self.crop_shape[0], offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return",
"def __init__(self, mean_file): self.bgr = True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape =",
"sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result",
"= os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: imgs = self.img_loader.load_imgs(img_files) if",
"Save the result in an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence)",
"val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the model ...\") results = []",
"self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1) % params.save_period",
"a list of images. \"\"\" imgs = [] for img_file in img_files: imgs.append(self.load_img(img_file))",
"np.float32) return imgs class BaseModel(object): def __init__(self, params, mode): self.params = params self.mode",
"param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable",
"count = 0 miss_count = 0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True):",
"else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0,",
"def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None): raise NotImplementedError() def",
"% params.save_period == 0: self.save(sess) train_data.reset() self.save(sess) print(\"Training complete.\") def val(self, sess, val_coco,",
"tf.variable_scope(op_name, reuse=True): for param_name, data in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count",
"train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a",
"mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if",
"img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco)",
"loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1))",
"print(\"Testing complete.\") def save(self, sess): \"\"\" Save the model. \"\"\" print((\"Saving model to",
"show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the model ...\") result_file = self.params.test_result_file",
"val_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict",
"is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the",
"sess.run(self.results, feed_dict=feed_dict) sentence = self.word_table.indices_to_sent(result.squeeze()) captions.append(sentence) # Save the result in an image",
"sess, test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the model ...\") result_file",
"an image file img = mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save",
"def load_imgs(self, img_files): \"\"\" Load and preprocess a list of images. \"\"\" imgs",
"self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1) %",
"self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats,",
"sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session, ignore_missing=True): \"\"\" Load a pretrained CNN",
"\"\"\" Train the model. \"\"\" print(\"Training the model...\") params = self.params num_epochs =",
"= params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch",
"import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm import",
"tf.train.Saver(max_to_keep = 100) def build(self): raise NotImplementedError() def get_feed_dict(self, batch, is_train, contexts=None, feats=None):",
"= np.load(data_path).item() count = 0 miss_count = 0 for op_name in data_dict: with",
"Generate the captions for the images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch()",
"imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict",
"return imgs class BaseModel(object): def __init__(self, params, mode): self.params = params self.mode =",
"print(\"Training complete.\") def val(self, sess, val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating",
"= batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch,",
"class BaseModel(object): def __init__(self, params, mode): self.params = params self.mode = mode self.batch_size",
"self.get_feed_dict(batch, is_train=False, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch,",
"= [] for img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs",
"session, ignore_missing=True): \"\"\" Load a pretrained CNN model. \"\"\" print(\"Loading CNN model from",
"from utils.coco.coco import * from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file):",
"Loss1=%f\" %(loss0, loss1)) if (global_step + 1) % params.save_period == 0: self.save(sess) train_data.reset()",
"captions for the images for k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files =",
"offset[1]:offset[1]+self.crop_shape[1], :] img = img - self.mean return img def load_imgs(self, img_files): \"\"\"",
"2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape - self.crop_shape) / 2",
"'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep = 100) def build(self): raise",
"import tensorflow as tf import cv2 import matplotlib.pyplot as plt import matplotlib.image as",
"from utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape",
"self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats = params.init_lstm_with_fc_feats if self.cnn_model=='vgg16' else False self.class_balancing_factor = params.class_balancing_factor",
"def train(self, sess, train_coco, train_data): \"\"\" Train the model. \"\"\" print(\"Training the model...\")",
"data_dict = np.load(data_path).item() count = 0 miss_count = 0 for op_name in data_dict:",
"= 0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data in",
"self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict)",
"the captions for the images for k in tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files",
"temp = img.swapaxes(0, 2) temp = temp[::-1] img = temp.swapaxes(0, 2) img =",
"self.mode = mode self.batch_size = params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model",
"def __init__(self, params, mode): self.params = params self.mode = mode self.batch_size = params.batch_size",
"= self.get_feed_dict(batch, is_train=True, contexts=contexts) _, loss0, loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step],",
"imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class BaseModel(object): def __init__(self, params, mode):",
"model ...\") result_file = self.params.test_result_file result_dir = self.params.test_result_dir captions = [] # Generate",
"np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess an image. \"\"\" img =",
"tf import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm",
"sess, val_coco, val_data): \"\"\" Validate the model. \"\"\" print(\"Validating the model ...\") results",
"Loss0=%f Loss1=%f\" %(loss0, loss1)) if (global_step + 1) % params.save_period == 0: self.save(sess)",
"k in tqdm(list(range(test_data.count))): batch = test_data.next_batch() img_files = batch img_file = img_files[0] img_name",
"model ...\") results = [] result_dir = self.params.val_result_dir # Generate the captions for",
"True self.scale_shape = np.array([224, 224], np.int32) self.crop_shape = np.array([224, 224], np.int32) self.mean =",
"plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) val_data.reset() # Evaluate these captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco,",
"self.params num_epochs = params.num_epochs for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)),",
"complete.\") def test(self, sess, test_data, show_result=False): \"\"\" Test the model. \"\"\" print(\"Testing the",
"# Save the captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing",
"return img def load_imgs(self, img_files): \"\"\" Load and preprocess a list of images.",
"feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts = sess.run(self.conv_feats, feed_dict={self.imgs:imgs,",
"model...\") checkpoint = tf.train.get_checkpoint_state(self.save_dir) if checkpoint is None: print(\"Error: No saved model found.",
"= sess.run([self.conv_feats, self.fc_feats], feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=True, contexts=contexts, feats=feats) else: contexts",
"tf.Variable(0, name = 'global_step', trainable = False) self.build() self.saver = tf.train.Saver(max_to_keep = 100)",
"params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load() self.img_loader",
"global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) print(\" Loss0=%f Loss1=%f\" %(loss0, loss1)) if",
"else: # Train RNN only img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files)",
"matplotlib.pyplot as plt import matplotlib.image as mpimg from tqdm import tqdm from dataset",
"1 #print(\"Variable %s:%s loaded\" %(op_name, param_name)) except ValueError: miss_count += 1 #print(\"Variable %s:%s",
"= params.batch_size if mode=='train' else 1 self.cnn_model = params.cnn_model self.train_cnn = params.train_cnn self.init_lstm_with_fc_feats",
"utils.coco.pycocoevalcap.eval import * class ImageLoader(object): def __init__(self, mean_file): self.bgr = True self.scale_shape =",
"= sess.run(self.conv_feats, feed_dict={self.imgs:imgs, self.is_train:False}) feed_dict = self.get_feed_dict(batch, is_train=False, contexts=contexts) result = sess.run(self.results, feed_dict=feed_dict)",
"captions to a file results = pd.DataFrame({'image_files':test_data.img_files, 'caption':captions}) results.to_csv(result_file) print(\"Testing complete.\") def save(self,",
"img_files, _, _ = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats =",
"tqdm(list(range(val_data.count))): batch = val_data.next_batch() img_files = batch img_file = img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0]",
"captions = [] # Generate the captions for the images for k in",
"%s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step) def load(self, sess): \"\"\" Load the model.",
"= sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only img_files, _,",
"for epoch_no in tqdm(list(range(num_epochs)), desc='epoch'): for idx in tqdm(list(range(train_data.num_batches)), desc='batch'): batch = train_data.next_batch()",
"img = temp.swapaxes(0, 2) img = cv2.resize(img, (self.scale_shape[0], self.scale_shape[1])) offset = (self.scale_shape -",
"img_files[0] img_name = os.path.splitext(img_file.split(os.sep)[-1])[0] if self.train_cnn: feed_dict = self.get_feed_dict(batch, is_train=False) else: img_files =",
"Load and preprocess a list of images. \"\"\" imgs = [] for img_file",
"img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts, feats = sess.run([self.conv_feats, self.fc_feats],",
"= self.word_table.indices_to_sent(result.squeeze()) results.append({'image_id': val_data.img_ids[k], 'caption': sentence}) # Save the result in an image",
"= self.get_feed_dict(batch, is_train=False) else: img_files = batch imgs = self.img_loader.load_imgs(img_files) if self.init_lstm_with_fc_feats: contexts,",
"= np.load(mean_file).mean(1).mean(1) def load_img(self, img_file): \"\"\" Load and preprocess an image. \"\"\" img",
"miss_count = 0 for op_name in data_dict: with tf.variable_scope(op_name, reuse=True): for param_name, data",
"img_file in img_files: imgs.append(self.load_img(img_file)) imgs = np.array(imgs, np.float32) return imgs class BaseModel(object): def",
"saved model found. Please train first.\") sys.exit(0) self.saver.restore(sess, checkpoint.model_checkpoint_path) def load2(self, data_path, session,",
"mpimg.imread(img_file) plt.imshow(img) plt.axis('off') plt.title(sentence) plt.savefig(os.path.join(result_dir, img_name+'_result.jpg')) # Save the captions to a file",
"loss1, global_step = sess.run([self.opt_op, self.loss0, self.loss1, self.global_step], feed_dict=feed_dict) else: # Train RNN only",
"else False self.class_balancing_factor = params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed,",
"captions val_res_coco = val_coco.loadRes2(results) scorer = COCOEvalCap(val_coco, val_res_coco) scorer.evaluate() print(\"Validation complete.\") def test(self,",
"in data_dict[op_name].iteritems(): try: var = tf.get_variable(param_name) session.run(var.assign(data)) count += 1 #print(\"Variable %s:%s loaded\"",
"Save the model. \"\"\" print((\"Saving model to %s\" % self.save_dir)) self.saver.save(sess, self.save_dir, self.global_step)",
"= params.class_balancing_factor self.save_dir = os.path.join(params.save_dir, self.cnn_model+'/') self.word_table = WordTable(params.vocab_size, params.dim_embed, params.max_sent_len, params.word_table_file) self.word_table.load()"
] |
[
"\"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], }",
"parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self,",
"and ignores the original 'p' values \"\"\" import numpy as np __example_param_text =",
"subset vx ^ v0 = v0 vx ^ v1 = v0 ... vx",
"vx for n in range(len(self.p_vn) + 1): if n == 0: this_idx, sample_name",
"each sample in population Algorithm: (Repeat for each chromosome copy) Generate random numbers",
"} } \"\"\" _description = __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params =",
"as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to v0 - v1",
"so on \"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx needs to be",
"in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) /",
"v1 v1 E v2 v2 E v3 ... v(n-1) E vn This plugin",
"\"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6,",
"p_v1/p_v0 Set all r corresponding to v0 - v1 as 1.0 so we",
"rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy in [0, 1]: idx_vx[cpy] =",
"sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]],",
"samples done) for each sample in population Algorithm: (Repeat for each chromosome copy)",
"p_vx Pick a random subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set",
"order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs to be >= 0",
"in vx ^ v0 or not in vx for n in range(len(self.p_vn) +",
"for vx set :param p_vn: probability values for v0, v1, v2, v3 ....",
"v0 vx ^ v1 = v0 ... vx ^ vn = v0 v0",
"p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param",
"model that creates samples with more and more variants. Suitable for the aligner",
"def __init__(self, p_vx, p_vn): \"\"\"A population model that creates samples with more and",
"to be >= 0 and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs",
"in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 #",
"\"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\" _description =",
"us an as exact as possible estimate of how many samples we will",
"master list of variants as created by genomes program :param rng_seed: seed for",
"be > p_vn[0]' for n in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n",
"site frequency spectrum model and ignores the original 'p' values \"\"\" import numpy",
"% samples done) for each sample in population Algorithm: (Repeat for each chromosome",
"'p_vn needs to be in ascending order' assert 0 <= self.p_vn[n] <= 1.0,",
"in vx for n in range(len(self.p_vn) + 1): if n == 0: this_idx,",
"exact as possible estimate of how many samples we will produce\"\"\" return 1",
"idx_vx = [None, None] for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0]",
"be >= 0 and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to",
"program :param rng_seed: seed for random number generators :return: A generator returning (generation",
">= 0 and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to be",
"more variants. Suitable for the aligner paper experiments ^ = intersection E =",
"self.p_vx > self.p_vn[0], 'p_vx needs to be > p_vn[0]' for n in range(len(self.p_vn)",
"self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns",
"r < 1.0 are either in vx ^ v0 or not in vx",
"p_vx: probability value for vx set :param p_vn: probability values for v0, v1,",
"v3 ... v(n-1) E vn This plugin does not honor the site frequency",
"^ vn = v0 v0 E v1 v1 E v2 v2 E v3",
"Pick a random subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all",
"Algorithm: (Repeat for each chromosome copy) Generate random numbers r same size as",
"paper experiments :param p_vx: probability value for vx set :param p_vn: probability values",
"vx ^ v0 or not in vx for n in range(len(self.p_vn) + 1):",
":param rng_seed: seed for random number generators :return: A generator returning (generation no,",
"be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1",
"= json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A population",
"0 <= self.p_vx <= 1.0, 'p_vx needs to be >= 0 and <=",
"probability values for v0, v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn =",
"vn This plugin does not honor the site frequency spectrum model and ignores",
"1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us",
"more variants. Suitable for the aligner paper experiments :param p_vx: probability value for",
"chromosome, % samples done) for each sample in population Algorithm: (Repeat for each",
"values \"\"\" import numpy as np __example_param_text = \"\"\" { \"vn\": { \"p_vx\":",
"for v0, v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn",
"aligner paper experiments ^ = intersection E = subset vx ^ v0 =",
"as variants list Select vx <= r < p_vx Pick a random subset",
"more and more variants. Suitable for the aligner paper experiments ^ = intersection",
"\"\"\" _description = __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params",
"the chromosome being considered [1,2,3 ...] (ignored here) :param ml: VariantList. master list",
"r < p_vx Pick a random subset of v0 as v1 size(v1)/size(v0) =",
"np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in vx that are not",
"set :param p_vn: probability values for v0, v1, v2, v3 .... set \"\"\"",
"cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take",
"ascending order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs to be >=",
"numbers r same size as variants list Select vx <= r < p_vx",
"+ __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self, p_vx,",
"- 1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to be in",
"replace=False)) # Take elements in vx that are not going to be in",
"and more variants. Suitable for the aligner paper experiments ^ = intersection E",
"0: this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy] <",
"random subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding",
"random numbers r same size as variants list Select vx <= r <",
"spectrum model and ignores the original 'p' values \"\"\" import numpy as np",
"sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as",
"[None, None] for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx),",
"rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy",
"0 <= self.p_vn[n] <= 1.0, 'p_vn needs to be >= 0 and <=",
"= v0 v0 E v1 v1 E v2 v2 E v3 ... v(n-1)",
"list of variants as created by genomes program :param rng_seed: seed for random",
"= rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy in [0, 1]: idx_vx[cpy]",
"vx set :param p_vn: probability values for v0, v1, v2, v3 .... set",
"v2, v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None,",
"returning (generation no, serial_no, chromosome, % samples done) for each sample in population",
"variants list Select vx <= r < p_vx Pick a random subset of",
"self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name,",
"\"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx needs to be >= 0",
"<= 1.0, 'p_vn needs to be >= 0 and <= 1.0' rng =",
"Model: def __init__(self, p_vx, p_vn): \"\"\"A population model that creates samples with more",
"<= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to be > p_vn[0]' for",
"list Select vx <= r < p_vx Pick a random subset of v0",
"self.p_vx), replace=False)) # Take elements in vx that are not going to be",
"possible estimate of how many samples we will produce\"\"\" return 1 + len(self.p_vn)",
"r corresponding to v0 - v1 as 1.0 so we never select these",
"= v0 vx ^ v1 = v0 ... vx ^ vn = v0",
"[1,2,3 ...] (ignored here) :param ml: VariantList. master list of variants as created",
"population model that creates samples with more and more variants. Suitable for the",
"^ v0 or not in vx for n in range(len(self.p_vn) + 1): if",
"considered [1,2,3 ...] (ignored here) :param ml: VariantList. master list of variants as",
"A generator returning (generation no, serial_no, chromosome, % samples done) for each sample",
"value for vx set :param p_vn: probability values for v0, v1, v2, v3",
"by genomes program :param rng_seed: seed for random number generators :return: A generator",
"the original 'p' values \"\"\" import numpy as np __example_param_text = \"\"\" {",
"p_v2, p_v3 and so on \"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx",
"vx that are not going to be in v0 completely out of circulation",
"either in vx ^ v0 or not in vx for n in range(len(self.p_vn)",
"vx ^ v1 = v0 ... vx ^ vn = v0 v0 E",
"<= r < p_vx Pick a random subset of v0 as v1 size(v1)/size(v0)",
"r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements for r <",
"in range(len(self.p_vn) + 1): if n == 0: this_idx, sample_name = idx_vx, 'vx'",
"ml: VariantList. master list of variants as created by genomes program :param rng_seed:",
"+ '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model:",
"p_vx, p_vn): \"\"\"A population model that creates samples with more and more variants.",
"v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to v0 -",
"all r corresponding to v0 - v1 as 1.0 so we never select",
":param p_vx: probability value for vx set :param p_vn: probability values for v0,",
"1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in vx",
"ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact",
"population Algorithm: (Repeat for each chromosome copy) Generate random numbers r same size",
"... by comparing r to p_v2, p_v3 and so on \"\"\" assert 0",
"2) idx_vx = [None, None] for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0],",
"v2, v3 ... by comparing r to p_v2, p_v3 and so on \"\"\"",
"in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements",
"__doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class",
"to be > p_vn[0]' for n in range(len(self.p_vn) - 1): assert self.p_vn[n] <",
"circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements for r",
"< self.p_vn[n + 1], 'p_vn needs to be in ascending order' assert 0",
"0 and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to be >",
"vn = v0 v0 E v1 v1 E v2 v2 E v3 ...",
"size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in vx that are not going",
"assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs to be >= 0 and",
"elements for r < 1.0 are either in vx ^ v0 or not",
"**kwargs): \"\"\"This returns an iterator :param chrom_no: number of the chromosome being considered",
"serial_no, chromosome, % samples done) for each sample in population Algorithm: (Repeat for",
"+ 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact as possible",
"needs to be >= 0 and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx",
"as possible estimate of how many samples we will produce\"\"\" return 1 +",
"size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to v0 - v1 as 1.0",
"1.1 # Now all elements for r < 1.0 are either in vx",
"by comparing r to p_v2, p_v3 and so on \"\"\" assert 0 <=",
"np __example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3,",
"ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no: number of the chromosome",
"class Model: def __init__(self, p_vx, p_vn): \"\"\"A population model that creates samples with",
"v0, v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def",
"v1 as 1.0 so we never select these again Pick v2, v3 ...",
"p_vn[0]' for n in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n + 1],",
"for n in range(len(self.p_vn) + 1): if n == 0: this_idx, sample_name =",
"frequency spectrum model and ignores the original 'p' values \"\"\" import numpy as",
"self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements for r < 1.0 are",
"E = subset vx ^ v0 = v0 vx ^ v1 = v0",
"for r < 1.0 are either in vx ^ v0 or not in",
"to be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] =",
"self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact as possible estimate of how",
"returns an iterator :param chrom_no: number of the chromosome being considered [1,2,3 ...]",
"select these again Pick v2, v3 ... by comparing r to p_v2, p_v3",
"numpy as np __example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1,",
"1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n",
"0 and <= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx =",
"for each chromosome copy) Generate random numbers r same size as variants list",
"elements in vx that are not going to be in v0 completely out",
"This plugin does not honor the site frequency spectrum model and ignores the",
"as 1.0 so we never select these again Pick v2, v3 ... by",
"for the aligner paper experiments :param p_vx: probability value for vx set :param",
"Suitable for the aligner paper experiments ^ = intersection E = subset vx",
"v0 - v1 as 1.0 so we never select these again Pick v2,",
"rng_seed: seed for random number generators :return: A generator returning (generation no, serial_no,",
"in ascending order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs to be",
"this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n",
"Pick v2, v3 ... by comparing r to p_v2, p_v3 and so on",
"in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to",
"E vn This plugin does not honor the site frequency spectrum model and",
"> self.p_vn[0], 'p_vx needs to be > p_vn[0]' for n in range(len(self.p_vn) -",
"samples with more and more variants. Suitable for the aligner paper experiments :param",
"to be in ascending order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs",
"with more and more variants. Suitable for the aligner paper experiments ^ =",
"idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in vx that",
"comparing r to p_v2, p_v3 and so on \"\"\" assert 0 <= self.p_vx",
"experiments :param p_vx: probability value for vx set :param p_vn: probability values for",
"< self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n - 1) yield",
":param chrom_no: number of the chromosome being considered [1,2,3 ...] (ignored here) :param",
"or not in vx for n in range(len(self.p_vn) + 1): if n ==",
"0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\" _description",
"<= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None]",
"size as variants list Select vx <= r < p_vx Pick a random",
"'vx' else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy",
"import numpy as np __example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\":",
"as exact as possible estimate of how many samples we will produce\"\"\" return",
"> p_vn[0]' for n in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n +",
"v2 v2 E v3 ... v(n-1) E vn This plugin does not honor",
"= subset vx ^ v0 = v0 vx ^ v1 = v0 ...",
"vx ^ v0 = v0 vx ^ v1 = v0 ... vx ^",
">= 0 and <= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx",
"v2 E v3 ... v(n-1) E vn This plugin does not honor the",
"p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no:",
"'p_vx needs to be >= 0 and <= 1.0' assert self.p_vx > self.p_vn[0],",
"chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no: number of the",
"to p_v2, p_v3 and so on \"\"\" assert 0 <= self.p_vx <= 1.0,",
"to be >= 0 and <= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0],",
"r to p_v2, p_v3 and so on \"\"\" assert 0 <= self.p_vx <=",
"same size as variants list Select vx <= r < p_vx Pick a",
"float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact as",
"1], 'p_vn needs to be in ascending order' assert 0 <= self.p_vn[n] <=",
"this_idx, sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in [0,",
"if n == 0: this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name =",
"1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for",
"n in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs",
"random number generators :return: A generator returning (generation no, serial_no, chromosome, % samples",
"- 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx),",
"None] for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False))",
"paper experiments ^ = intersection E = subset vx ^ v0 = v0",
"more and more variants. Suitable for the aligner paper experiments :param p_vx: probability",
"number generators :return: A generator returning (generation no, serial_no, chromosome, % samples done)",
"json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A population model",
"^ v0 = v0 vx ^ v1 = v0 ... vx ^ vn",
"E v1 v1 E v2 v2 E v3 ... v(n-1) E vn This",
"'p_vx needs to be > p_vn[0]' for n in range(len(self.p_vn) - 1): assert",
"1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def",
"self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an",
"cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n - 1)",
"here) :param ml: VariantList. master list of variants as created by genomes program",
"self.p_vn[n + 1], 'p_vn needs to be in ascending order' assert 0 <=",
"else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in",
"as np __example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2,",
"Suitable for the aligner paper experiments :param p_vx: probability value for vx set",
"p_vn): \"\"\"A population model that creates samples with more and more variants. Suitable",
":param p_vn: probability values for v0, v1, v2, v3 .... set \"\"\" self.p_vx,",
"= [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n",
"for cpy in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n +",
"0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\" _description = __doc__ + '\\nExample",
"1.0 so we never select these again Pick v2, v3 ... by comparing",
"- 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give",
"needs to be >= 0 and <= 1.0' rng = np.random.RandomState(rng_seed) r =",
"== 0: this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy]",
"an as exact as possible estimate of how many samples we will produce\"\"\"",
"[0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in",
"+ 1): if n == 0: this_idx, sample_name = idx_vx, 'vx' else: this_idx,",
"that creates samples with more and more variants. Suitable for the aligner paper",
"= v0 ... vx ^ vn = v0 v0 E v1 v1 E",
"v1 = v0 ... vx ^ vn = v0 v0 E v1 v1",
"set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs):",
"[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\" _description = __doc__",
"0.6, 0.7], } } \"\"\" _description = __doc__ + '\\nExample parameters:\\n' + __example_param_text",
"\"\"\"A population model that creates samples with more and more variants. Suitable for",
">= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements for r < 1.0",
"+ 1], 'p_vn needs to be in ascending order' assert 0 <= self.p_vn[n]",
"0.5, 0.6, 0.7], } } \"\"\" _description = __doc__ + '\\nExample parameters:\\n' +",
"n == 0: this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name = [(r[:,",
"seed for random number generators :return: A generator returning (generation no, serial_no, chromosome,",
"\"\"\" import numpy as np __example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2,",
"rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no: number of the chromosome being",
"'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self):",
"an iterator :param chrom_no: number of the chromosome being considered [1,2,3 ...] (ignored",
"Generate random numbers r same size as variants list Select vx <= r",
"1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact as possible estimate",
"self.p_vn[n] <= 1.0, 'p_vn needs to be >= 0 and <= 1.0' rng",
"<= self.p_vx <= 1.0, 'p_vx needs to be >= 0 and <= 1.0'",
"1.0, 'p_vx needs to be >= 0 and <= 1.0' assert self.p_vx >",
"def get_sample_count_estimate(self): \"\"\"Give us an as exact as possible estimate of how many",
"VariantList. master list of variants as created by genomes program :param rng_seed: seed",
"1.0, 'p_vn needs to be >= 0 and <= 1.0' rng = np.random.RandomState(rng_seed)",
":param ml: VariantList. master list of variants as created by genomes program :param",
"honor the site frequency spectrum model and ignores the original 'p' values \"\"\"",
"E v3 ... v(n-1) E vn This plugin does not honor the site",
"__example_param_text = \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4,",
"= idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0]",
"r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy in [0, 1]:",
"Set all r corresponding to v0 - v1 as 1.0 so we never",
"of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to v0",
"0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\" _description = __doc__ +",
"self.p_vx <= 1.0, 'p_vx needs to be >= 0 and <= 1.0' assert",
"ignores the original 'p' values \"\"\" import numpy as np __example_param_text = \"\"\"",
"for the aligner paper experiments ^ = intersection E = subset vx ^",
"- v1 as 1.0 so we never select these again Pick v2, v3",
"v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to v0 - v1 as",
"going to be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy]",
"v0 E v1 v1 E v2 v2 E v3 ... v(n-1) E vn",
"\"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } } \"\"\"",
"original 'p' values \"\"\" import numpy as np __example_param_text = \"\"\" { \"vn\":",
"needs to be > p_vn[0]' for n in range(len(self.p_vn) - 1): assert self.p_vn[n]",
"__init__(self, p_vx, p_vn): \"\"\"A population model that creates samples with more and more",
"v0 ... vx ^ vn = v0 v0 E v1 v1 E v2",
"and more variants. Suitable for the aligner paper experiments :param p_vx: probability value",
"< p_vx Pick a random subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0",
"variants as created by genomes program :param rng_seed: seed for random number generators",
"= 1.1 # Now all elements for r < 1.0 are either in",
"range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to be",
"eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A population model that creates samples",
"0.4, 0.5, 0.6, 0.7], } } \"\"\" _description = __doc__ + '\\nExample parameters:\\n'",
"chromosome being considered [1,2,3 ...] (ignored here) :param ml: VariantList. master list of",
"sample_name = idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n -",
"__example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn):",
"[(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for cpy in [0, 1]], 'v{:d}'.format(n -",
"subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r corresponding to",
"1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to be in ascending",
"of variants as created by genomes program :param rng_seed: seed for random number",
"never select these again Pick v2, v3 ... by comparing r to p_v2,",
"1.0 are either in vx ^ v0 or not in vx for n",
"= __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text)",
"v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now",
"a random subset of v0 as v1 size(v1)/size(v0) = p_v1/p_v0 Set all r",
"to v0 - v1 as 1.0 so we never select these again Pick",
"v(n-1) E vn This plugin does not honor the site frequency spectrum model",
"yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an",
"for each sample in population Algorithm: (Repeat for each chromosome copy) Generate random",
"vx <= r < p_vx Pick a random subset of v0 as v1",
"are not going to be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >=",
"iterator :param chrom_no: number of the chromosome being considered [1,2,3 ...] (ignored here)",
"(ignored here) :param ml: VariantList. master list of variants as created by genomes",
"be >= 0 and <= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2)",
"self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to be in ascending order' assert",
"v3 ... by comparing r to p_v2, p_v3 and so on \"\"\" assert",
"<= 1.0, 'p_vx needs to be >= 0 and <= 1.0' assert self.p_vx",
"= p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator",
"= eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A population model that creates",
"variants. Suitable for the aligner paper experiments ^ = intersection E = subset",
"not going to be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]],",
"n in range(len(self.p_vn) + 1): if n == 0: this_idx, sample_name = idx_vx,",
"corresponding to v0 - v1 as 1.0 so we never select these again",
".... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1,",
"number of the chromosome being considered [1,2,3 ...] (ignored here) :param ml: VariantList.",
"... vx ^ vn = v0 v0 E v1 v1 E v2 v2",
"not honor the site frequency spectrum model and ignores the original 'p' values",
"samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no: number of",
"for n in range(len(self.p_vn) - 1): assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn",
"E v2 v2 E v3 ... v(n-1) E vn This plugin does not",
"completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all",
"'p' values \"\"\" import numpy as np __example_param_text = \"\"\" { \"vn\": {",
"<= self.p_vn[n] <= 1.0, 'p_vn needs to be >= 0 and <= 1.0'",
"each chromosome copy) Generate random numbers r same size as variants list Select",
"probability value for vx set :param p_vn: probability values for v0, v1, v2,",
"= \"\"\" { \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5,",
"assert self.p_vx > self.p_vn[0], 'p_vx needs to be > p_vn[0]' for n in",
"Now all elements for r < 1.0 are either in vx ^ v0",
"and <= 1.0' rng = np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None,",
"experiments ^ = intersection E = subset vx ^ v0 = v0 vx",
"cpy in [0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1)",
"in vx that are not going to be in v0 completely out of",
"v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self,",
"with more and more variants. Suitable for the aligner paper experiments :param p_vx:",
"out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements",
"get_sample_count_estimate(self): \"\"\"Give us an as exact as possible estimate of how many samples",
"created by genomes program :param rng_seed: seed for random number generators :return: A",
"v0 v0 E v1 v1 E v2 v2 E v3 ... v(n-1) E",
"1): if n == 0: this_idx, sample_name = idx_vx, 'vx' else: this_idx, sample_name",
"\"\"\"Give us an as exact as possible estimate of how many samples we",
"v0 = v0 vx ^ v1 = v0 ... vx ^ vn =",
"sample in population Algorithm: (Repeat for each chromosome copy) Generate random numbers r",
"genomes program :param rng_seed: seed for random number generators :return: A generator returning",
"of circulation r[idx_vx[cpy][(r[idx_vx[cpy]] >= self.p_vn[0]).nonzero()[0]], cpy] = 1.1 # Now all elements for",
"p_vn: probability values for v0, v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn",
"def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This returns an iterator :param chrom_no: number",
"0.7], } } \"\"\" _description = __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params",
"all elements for r < 1.0 are either in vx ^ v0 or",
"(generation no, serial_no, chromosome, % samples done) for each sample in population Algorithm:",
"= intersection E = subset vx ^ v0 = v0 vx ^ v1",
"are either in vx ^ v0 or not in vx for n in",
"intersection E = subset vx ^ v0 = v0 vx ^ v1 =",
"chrom_no: number of the chromosome being considered [1,2,3 ...] (ignored here) :param ml:",
"range(len(self.p_vn) + 1): if n == 0: this_idx, sample_name = idx_vx, 'vx' else:",
":return: A generator returning (generation no, serial_no, chromosome, % samples done) for each",
"#_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A",
"for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) #",
"samples with more and more variants. Suitable for the aligner paper experiments ^",
"= p_v1/p_v0 Set all r corresponding to v0 - v1 as 1.0 so",
"= np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy in",
"Take elements in vx that are not going to be in v0 completely",
"{ \"vn\": { \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7],",
"copy) Generate random numbers r same size as variants list Select vx <=",
"...] (ignored here) :param ml: VariantList. master list of variants as created by",
"so we never select these again Pick v2, v3 ... by comparing r",
"r same size as variants list Select vx <= r < p_vx Pick",
"for random number generators :return: A generator returning (generation no, serial_no, chromosome, %",
"^ = intersection E = subset vx ^ v0 = v0 vx ^",
"(Repeat for each chromosome copy) Generate random numbers r same size as variants",
"again Pick v2, v3 ... by comparing r to p_v2, p_v3 and so",
"= np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] * self.p_vx), replace=False)) # Take elements in vx that are",
"... v(n-1) E vn This plugin does not honor the site frequency spectrum",
"'\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params = eval(__example_param_text) class Model: def",
"in population Algorithm: (Repeat for each chromosome copy) Generate random numbers r same",
"not in vx for n in range(len(self.p_vn) + 1): if n == 0:",
"v1 E v2 v2 E v3 ... v(n-1) E vn This plugin does",
"generators :return: A generator returning (generation no, serial_no, chromosome, % samples done) for",
"generator returning (generation no, serial_no, chromosome, % samples done) for each sample in",
"done) for each sample in population Algorithm: (Repeat for each chromosome copy) Generate",
"_example_params = eval(__example_param_text) class Model: def __init__(self, p_vx, p_vn): \"\"\"A population model that",
"\"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None, rng_seed=1, **kwargs): \"\"\"This",
"and so on \"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx needs to",
"1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to be > p_vn[0]' for n",
"be in ascending order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn needs to",
"cpy] = 1.1 # Now all elements for r < 1.0 are either",
"p_v3 and so on \"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx needs",
"# Now all elements for r < 1.0 are either in vx ^",
"we never select these again Pick v2, v3 ... by comparing r to",
"the aligner paper experiments ^ = intersection E = subset vx ^ v0",
"^ v1 = v0 ... vx ^ vn = v0 v0 E v1",
"'p_vn needs to be >= 0 and <= 1.0' rng = np.random.RandomState(rng_seed) r",
"creates samples with more and more variants. Suitable for the aligner paper experiments",
"} \"\"\" _description = __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text)",
"values for v0, v1, v2, v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx,",
"idx_vx, 'vx' else: this_idx, sample_name = [(r[:, cpy] < self.p_vn[n - 1]).nonzero()[0] for",
"assert self.p_vn[n] < self.p_vn[n + 1], 'p_vn needs to be in ascending order'",
"v3 .... set \"\"\" self.p_vx, self.p_vn = p_vx, p_vn def samples(self, chrom_no=None, ml=None,",
"< 1.0 are either in vx ^ v0 or not in vx for",
"as created by genomes program :param rng_seed: seed for random number generators :return:",
"# Take elements in vx that are not going to be in v0",
"being considered [1,2,3 ...] (ignored here) :param ml: VariantList. master list of variants",
"variants. Suitable for the aligner paper experiments :param p_vx: probability value for vx",
"needs to be in ascending order' assert 0 <= self.p_vn[n] <= 1.0, 'p_vn",
"np.random.RandomState(rng_seed) r = rng.rand(ml.variants.shape[0], 2) idx_vx = [None, None] for cpy in [0,",
"does not honor the site frequency spectrum model and ignores the original 'p'",
"no, serial_no, chromosome, % samples done) for each sample in population Algorithm: (Repeat",
"v0 or not in vx for n in range(len(self.p_vn) + 1): if n",
"on \"\"\" assert 0 <= self.p_vx <= 1.0, 'p_vx needs to be >=",
"= [None, None] for cpy in [0, 1]: idx_vx[cpy] = np.sort(rng.choice(ml.variants.shape[0], size=int(ml.variants.shape[0] *",
"these again Pick v2, v3 ... by comparing r to p_v2, p_v3 and",
"of the chromosome being considered [1,2,3 ...] (ignored here) :param ml: VariantList. master",
"/ self.get_sample_count_estimate() def get_sample_count_estimate(self): \"\"\"Give us an as exact as possible estimate of",
"aligner paper experiments :param p_vx: probability value for vx set :param p_vn: probability",
"model and ignores the original 'p' values \"\"\" import numpy as np __example_param_text",
"plugin does not honor the site frequency spectrum model and ignores the original",
"that are not going to be in v0 completely out of circulation r[idx_vx[cpy][(r[idx_vx[cpy]]",
"chromosome copy) Generate random numbers r same size as variants list Select vx",
"{ \"p_vx\": 0.2, \"p_vn\": [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7], } }",
"the aligner paper experiments :param p_vx: probability value for vx set :param p_vn:",
"\"\"\"This returns an iterator :param chrom_no: number of the chromosome being considered [1,2,3",
"assert 0 <= self.p_vx <= 1.0, 'p_vx needs to be >= 0 and",
"Select vx <= r < p_vx Pick a random subset of v0 as",
"vx ^ vn = v0 v0 E v1 v1 E v2 v2 E",
"_description = __doc__ + '\\nExample parameters:\\n' + __example_param_text #_example_params = json.loads(__example_param_text) _example_params =",
"[0, 1]], 'v{:d}'.format(n - 1) yield sample_name, ml.zip_up_chromosome(*this_idx), float(n + 1) / self.get_sample_count_estimate()",
"the site frequency spectrum model and ignores the original 'p' values \"\"\" import",
"* self.p_vx), replace=False)) # Take elements in vx that are not going to",
"and <= 1.0' assert self.p_vx > self.p_vn[0], 'p_vx needs to be > p_vn[0]'",
"self.p_vn[0], 'p_vx needs to be > p_vn[0]' for n in range(len(self.p_vn) - 1):"
] |
[
"_prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o for o in godag.values()",
"GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through r0 GO IDs",
"GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03 R03 regulation of cellular process",
"in go2nt.items() if go in goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt,",
"- Generate GO DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1,",
"print('ANS', sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, '",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates'])",
"not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp =",
"as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt,",
"goids_leaf_all = set(o.id for o in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all,",
"RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par =",
"R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for go, nt in go2nt.items()",
"GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o",
"D07 R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8 3",
"{'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par =",
"rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is the",
"GOTerm.get_all_upper() is the same as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1",
"prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print",
"r1: Test that GOTerm.get_all_upper() is the same as GoSubDag ancestors for goid, term",
"import sys ## import timeit ## import datetime import collections as cx from",
"R03 regulation of cellular process #ffd1df GO:0019222 # BP 3382 20 D03 R03",
"#ffd1df GO:0019222 # BP 3382 20 D03 R03 regulation of metabolic process #ffd1df",
"# BP 2417 65 D04 R04 positive regulation of cellular process #ffd1df GO:0060255",
"objs_r1_sub = set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms",
"godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates",
"godag.values() if o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all for k in",
"gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates',",
"('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel}",
"triggering of virus induced gene silencing # - Generate GO DAG subset for",
"user-specified relationships\"\"\" # Leaf GO: viral triggering of virus induced gene silencing goid_chosen",
"== set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates',",
"REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of)",
"GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 =",
"of cellular process #ffd1df GO:0019222 # BP 3382 20 D03 R03 regulation of",
"from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py",
"REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only",
"= [nt for go, nt in go2nt.items() if go in goids] for ntd",
"== '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019, <NAME>, <NAME>, All rights",
"= 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print('",
"R05 regulation of gene expression #ffd1df GO:0060968 # BP 53 4 D06 R08",
"loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all",
"WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag",
"relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 =",
"= gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj'",
"'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in",
"import collections as cx from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from",
"not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr =",
"assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms",
"gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is the same as GoSubDag ancestors",
"for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794",
"for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for",
"goid_chosen = 'GO:0060150' # Load GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\")",
"of gene silencing #ffd1df GO:0060147 # BP 24 4 D07 R09 regulation of",
"obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO}",
"gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1,",
"\"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3}",
"reserved.\" from os.path import join from os import system import sys ## import",
"for o in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout)",
"dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] ####",
"go, nt in go2nt.items() if go in goids] for ntd in sorted(nts, key=lambda",
"goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if not o.children) for goid in",
"65 D04 R04 positive regulation of cellular process #ffd1df GO:0060255 # BP 2130",
"process #ffd1df GO:0048522 # BP 2417 65 D04 R04 positive regulation of cellular",
"ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos =",
"'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values() if not o.children) gosubdag_r1",
"BP 53 4 D06 R08 regulation of gene silencing #ffd1df GO:0060147 # BP",
"hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if not",
"in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier",
"set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0)",
"GO:0060968 # BP 53 4 D06 R08 regulation of gene silencing #ffd1df GO:0060147",
"# BP 24 4 D07 R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148",
"go2nt.items() if go in goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True):",
"set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM",
"--obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources))))",
"ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### #",
"_get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs as a source",
"rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj'",
"o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all for k in o.relationship.keys()) #",
"in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences",
"# BP 3382 20 D03 R03 regulation of metabolic process #ffd1df GO:0048522 #",
"R10 positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0 0",
"gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]),",
"part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen]",
"GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not",
"# {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts",
"o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key,",
"of GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02}",
"cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o in pterms))) #### # print('')",
"#ffd1df GO:0060147 # BP 24 4 D07 R09 regulation of posttranscriptional gene silencing",
"gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0,",
"regulation of macromolecule metabolic process #ffd1df GO:0010468 # BP 862 20 D05 R05",
"goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils",
"key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check",
"pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'),",
"== 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships ==",
"from os.path import join from os import system import sys ## import timeit",
"len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships",
"3 D08 R10 positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150 # BP",
"silencing # - Generate GO DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo,",
"= set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs",
"= gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1)",
"{SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details",
"term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO",
"Generate GO DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo):",
"== regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper()",
"_prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df {GO} #",
"# print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for rel, pterms in",
"gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that",
"in gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels",
"in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]),",
"as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot",
"PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all relationships",
"cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the",
"0 0 D09 R11 viral triggering of virus induced gene silencing # -",
"== set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM",
"tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors",
"subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o",
"rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt,",
"term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### #",
"{GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n')",
"not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all)",
"# Load GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0",
"pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019, <NAME>,",
"rels = set(k for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels",
"go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents for k in",
"relationships.\"\"\" objs_r1_all = set(o for o in godag.values() if o.relationship.keys()) octr = cx.Counter(k",
"r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through",
"== set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'})",
"'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not",
"up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values()",
"= set(o.id for o in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag,",
"<NAME>, <NAME>, All rights reserved.\" from os.path import join from os import system",
"as cx from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import",
"= join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None,",
"#ffd1df GO:0048522 # BP 2417 65 D04 R04 positive regulation of cellular process",
"D04 R04 regulation of macromolecule metabolic process #ffd1df GO:0010468 # BP 862 20",
"= gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys())",
"set(o.id for o in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True,",
"that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in",
"from only the user-specified relationships\"\"\" # Leaf GO: viral triggering of virus induced",
"for o in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub = set(o.id for",
"pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o in pterms))) ####",
"GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo,",
"regulation of gene expression #ffd1df GO:0060968 # BP 53 4 D06 R08 regulation",
"all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for o",
"pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}'",
"GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def",
"0 D09 R11 viral triggering of virus induced gene silencing # - Generate",
"between the two go2obb dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) !=",
"D04 R04 positive regulation of cellular process #ffd1df GO:0060255 # BP 2130 20",
"gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates'])",
"go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS}",
"if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019, <NAME>, <NAME>,",
"that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through r0 GO",
"def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" #",
"GoSubDag contains ancestors from only the user-specified relationships\"\"\" # Leaf GO: viral triggering",
"# BP 0 0 D09 R11 viral triggering of virus induced gene silencing",
"#### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for",
"get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo",
"WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset",
"for go, nt in go2nt.items() if go in goids] for ntd in sorted(nts,",
"assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert",
"in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 ==",
"prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt):",
"GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert",
"== GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through r0 GO IDs for",
"GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have",
"#### reldict = sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### #",
"rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o in pterms)))",
"terms in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r",
"with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral),",
"octr = cx.Counter(k for o in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub",
"RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par =",
"through r0 GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set())",
"GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): #### if goid",
"their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if",
"go2o_sub): # \"\"\"Check the differences between the two go2obb dicts.\"\"\" # pass if",
"#### # print('ANS', sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items(): #### #",
"for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o in",
"# print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441'",
"assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test",
"as a source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout)",
"import system import sys ## import timeit ## import datetime import collections as",
"D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for go, nt in",
"_chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the two go2obb dicts.\"\"\" # pass",
"for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set())",
"of macromolecule metabolic process #ffd1df GO:0010468 # BP 862 20 D05 R05 regulation",
"BP 862 20 D05 R05 regulation of gene expression #ffd1df GO:0060968 # BP",
"# objs_r1_sub = set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO",
"OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0",
"= gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp =",
"GO:0060147 # BP 24 4 D07 R09 regulation of posttranscriptional gene silencing #ffd1df",
"fin_obo): \"\"\"Sub plot used for visualizing this test file's elements\"\"\" # Load GO-DAG:",
"set()) assert ancestors_r1 == term.get_all_upper() #### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]),",
"count of relationships.\"\"\" objs_r1_all = set(o for o in godag.values() if o.relationship.keys()) octr",
"from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO #",
"low-level GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) #",
"# goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import",
"gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] #",
"relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates",
"dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C)",
"not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt",
"disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\"",
"in godag.values() if o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all for k",
"Load GO-DAG: Load optional 'relationship' godag = {go:o for go, o in godag_r1.items()",
"def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all relationships up their hierarchy.\"\"\"",
"set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all)))",
"# BP 8 3 D08 R10 positive regulation of posttranscriptional gene silencing #ffd1df",
"r1_ancestors_more print('{N} r1 GO terms in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more)))",
"20 D05 R05 regulation of gene expression #ffd1df GO:0060968 # BP 53 4",
"silencing #ffd1df GO:0060147 # BP 24 4 D07 R09 regulation of posttranscriptional gene",
"= '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen))",
"pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only the user-specified",
"GO terms above this low-level GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub,",
"# print('ANS', sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel,",
"gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents()",
"#ffd1df GO:0060148 # BP 8 3 D08 R10 positive regulation of posttranscriptional gene",
"## import timeit ## import datetime import collections as cx from goatools.base import",
"open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo))",
"cx.Counter(k for o in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub = set(o.id",
"more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos",
"#### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid]",
"# RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS:",
"--------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this test",
"set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if not o.children) for goid",
"_wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen])",
"GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through r0 GO IDs for goid,",
"'**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION",
"# assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert",
"20 D03 R03 regulation of metabolic process #ffd1df GO:0048522 # BP 2417 65",
"for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys())",
"from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains",
"#### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() ####",
"BP 2417 65 D04 R04 positive regulation of cellular process #ffd1df GO:0060255 #",
"posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0 0 D09 R11 viral triggering",
"gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL:",
"fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 #",
"have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png",
"'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE:",
"_run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set()",
"system import sys ## import timeit ## import datetime import collections as cx",
"R04 positive regulation of cellular process #ffd1df GO:0060255 # BP 2130 20 D04",
"[nt for go, nt in go2nt.items() if go in goids] for ntd in",
"GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) #",
"GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents'",
"= set(o for o in godag.values() if o.relationship.keys()) octr = cx.Counter(k for o",
"of metabolic process #ffd1df GO:0048522 # BP 2417 65 D04 R04 positive regulation",
"assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag have more ancestors than r0'.format(",
"' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for go,",
"set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'}",
"regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is",
"RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs)",
"R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8 3 D08",
"4 D06 R08 regulation of gene silencing #ffd1df GO:0060147 # BP 24 4",
"\"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # Leaf GO:",
"from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False):",
"import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import",
"ancestors_r1 == term.get_all_upper() #### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'},",
"set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert",
"the count of relationships.\"\"\" objs_r1_all = set(o for o in godag.values() if o.relationship.keys())",
"R04 regulation of macromolecule metabolic process #ffd1df GO:0010468 # BP 862 20 D05",
"_run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is the same as GoSubDag",
"rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships",
"metabolic process #ffd1df GO:0010468 # BP 862 20 D05 R05 regulation of gene",
"regulation of cellular process #ffd1df GO:0060255 # BP 2130 20 D04 R04 regulation",
"#### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for rel, pterms",
"goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert",
"GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of",
"len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag have",
"gene silencing #ffd1df GO:0060150 # BP 0 0 D09 R11 viral triggering of",
"for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid)",
"godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all,",
"above this low-level GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1,",
"the same as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid,",
"goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() ####",
"\"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path import join from",
"goid, dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid]",
"goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO # pylint:",
"= ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL}",
"\"tests/data/viral_gene_silence.obo\") # Get all GO terms above this low-level GO ID using all",
"relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py",
"gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO",
"differences between the two go2obb dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv)",
"gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more",
"== term.get_all_upper() #### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout)",
"go in goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb",
"in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates'])",
"godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the",
"have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag,",
"gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that",
"53 4 D06 R08 regulation of gene silencing #ffd1df GO:0060147 # BP 24",
"= gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### # Test that #### gosubdag_rp",
"in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test",
"nt in go2nt.items() if go in goids] for ntd in sorted(nts, key=lambda nt:",
"\"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop",
"# - Generate GO DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen,",
"prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: ####",
"in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def",
"gene silencing # - Generate GO DAG subset for this test --------------------------------------------------------- def",
"k in o.relationship.keys()) # objs_r1_sub = set(o.id for o in objs_r1_all if not",
"gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION",
"GoSubDag contains ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py #",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1)",
"in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### # Test",
"None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1",
"system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all",
"set() # Loop through r0 GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0",
"= set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if not o.children) for",
"gos_r1_relsinhier = set() goids_leaf = set(o.id for o in gosubdag_r1.go2obj.values() if not o.children)",
"o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p",
"go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id",
"r0 GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1",
"assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates",
"# Get all GO terms above this low-level GO ID using all relationships",
"rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp",
"assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not",
"as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert",
"sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278",
"GO:0019222 # BP 3382 20 D03 R03 regulation of metabolic process #ffd1df GO:0048522",
"REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert",
"def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this test file's",
"all GO terms above this low-level GO ID using all relationships if wr_new_obo_subset:",
"relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in",
"negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen]",
"cellular process #ffd1df GO:0060255 # BP 2130 20 D04 R04 regulation of macromolecule",
"prt): \"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5}",
"if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1)",
"tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__",
"that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py",
"if go in goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict()))",
"D03 R03 regulation of cellular process #ffd1df GO:0019222 # BP 3382 20 D03",
"20 D04 R04 regulation of macromolecule metabolic process #ffd1df GO:0010468 # BP 862",
"r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag have more ancestors than",
"= 'GO:0060150' # Load GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") #",
"process #ffd1df GO:0060255 # BP 2130 20 D04 R04 regulation of macromolecule metabolic",
"-o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen))",
"= GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one",
"'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in",
"RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of',",
"ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py #",
"go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS:",
"GO terms in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt",
"prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03 R03 regulation of",
"terms above this low-level GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen,",
"that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id",
"viral triggering of virus induced gene silencing goid_chosen = 'GO:0060150' # Load GODag",
"gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### # Test that #### gosubdag_rp =",
"for go, o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of',",
"'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen]",
"D08 R10 positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0",
"godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this test file's elements\"\"\" # Load",
"goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents",
"for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): #",
"def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df {GO}",
"the user-specified relationships\"\"\" # Leaf GO: viral triggering of virus induced gene silencing",
"cx from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag",
"reldict = sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB',",
"3382 20 D03 R03 regulation of metabolic process #ffd1df GO:0048522 # BP 2417",
"visualizing this test file's elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag =",
"o in godag.values() if o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all for",
"#ffd1df GO:0050794 # BP 8278 64 D03 R03 regulation of cellular process #ffd1df",
"GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' #",
"gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert",
"metabolic process #ffd1df GO:0048522 # BP 2417 65 D04 R04 positive regulation of",
"TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships",
"ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None",
"IDs that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf =",
"have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for",
"ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 #",
"rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1,",
"# goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright (C) 2016-2019,",
"print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key))",
"gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count",
"assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more",
"GO:0060150 # BP 0 0 D09 R11 viral triggering of virus induced gene",
"optional 'relationship' godag = {go:o for go, o in godag_r1.items() if go ==",
"the two go2obb dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1)",
"induced gene silencing # - Generate GO DAG subset for this test ---------------------------------------------------------",
"file's elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag = {go:o for go,",
"## import datetime import collections as cx from goatools.base import get_godag from goatools.godag.consts",
"= get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms",
"relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO",
"nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): #### if",
"GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships ==",
"gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o for o",
"goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) ==",
"#### for goid, dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors",
"# goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>,",
"o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o",
"if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common():",
"'**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM",
"GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1,",
"< len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag have more",
"p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return",
"# assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS:",
"regulation of cellular process #ffd1df GO:0019222 # BP 3382 20 D03 R03 regulation",
"REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert",
"godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn",
"IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid,",
"gene expression #ffd1df GO:0060968 # BP 53 4 D06 R08 regulation of gene",
"of virus induced gene silencing # - Generate GO DAG subset for this",
"for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag):",
"godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term =",
"GO:0050794 # BP 8278 64 D03 R03 regulation of cellular process #ffd1df GO:0019222",
"in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o in pterms))) #### #",
"goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function",
"set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE:",
"GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441'",
"the differences between the two go2obb dicts.\"\"\" # pass if __name__ == '__main__':",
"assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() ==",
"prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\"",
"= gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1):",
"print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the",
"gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs =",
"# BP 2130 20 D04 R04 regulation of macromolecule metabolic process #ffd1df GO:0010468",
"= GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt:",
"'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) #",
"from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from",
"not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in",
"gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441'",
"'.join(sorted(o.id for o in pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441'",
"#ffd1df GO:0060255 # BP 2130 20 D04 R04 regulation of macromolecule metabolic process",
"862 20 D05 R05 regulation of gene expression #ffd1df GO:0060968 # BP 53",
"posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8 3 D08 R10 positive regulation",
"godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not",
"process #ffd1df GO:0019222 # BP 3382 20 D03 R03 regulation of metabolic process",
"IDs as a source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True,",
"# RELATIONSHIPS: regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1,",
"in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents for",
"= join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above this low-level GO ID",
"#### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt",
"set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert",
"import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from",
"prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N}",
"D05 R05 regulation of gene expression #ffd1df GO:0060968 # BP 53 4 D06",
"N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos,",
"key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64",
"silencing #ffd1df GO:0060148 # BP 8 3 D08 R10 positive regulation of posttranscriptional",
"\"\"\"Sub plot used for visualizing this test file's elements\"\"\" # Load GO-DAG: Load",
"of relationships.\"\"\" objs_r1_all = set(o for o in godag.values() if o.relationship.keys()) octr =",
"# BP 862 20 D05 R05 regulation of gene expression #ffd1df GO:0060968 #",
"ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N}",
"len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships",
"loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above this",
"'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1,",
"of gene expression #ffd1df GO:0060968 # BP 53 4 D06 R08 regulation of",
"collections as cx from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag",
"Get all GO terms above this low-level GO ID using all relationships if",
"triggering of virus induced gene silencing goid_chosen = 'GO:0060150' # Load GODag with",
"set(o for o in godag.values() if o.relationship.keys()) octr = cx.Counter(k for o in",
"in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt",
"join from os import system import sys ## import timeit ## import datetime",
"godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO",
"ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) <",
"wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert",
"'**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'})",
"GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) #",
"gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): ####",
"goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO",
"reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03 R03 regulation",
"RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par =",
"relationships\"\"\" # Leaf GO: viral triggering of virus induced gene silencing goid_chosen =",
"negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships ==",
"godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE",
"open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def",
"if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of",
"for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper()",
"'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values() if not o.children)",
"of cellular process #ffd1df GO:0060255 # BP 2130 20 D04 R04 regulation of",
"rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all =",
"# RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par",
"that GOTerm.get_all_upper() is the same as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items():",
"'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0:",
"RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par =",
"'relationship' godag = {go:o for go, o in godag_r1.items() if go == o.item_id}",
"# Leaf GO: viral triggering of virus induced gene silencing goid_chosen = 'GO:0060150'",
"24 4 D07 R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148 # BP",
"BP 24 4 D07 R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148 #",
"if not o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k",
"= GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]),",
"= gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is the same",
"plot used for visualizing this test file's elements\"\"\" # Load GO-DAG: Load optional",
"o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) #",
"# Load GO-DAG: Load optional 'relationship' godag = {go:o for go, o in",
"goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright (C)",
"gosubdag_r1): \"\"\"Get GO IDs that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier =",
"4 D07 R09 regulation of posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8",
"godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\")",
"Test that GOTerm.get_all_upper() is the same as GoSubDag ancestors for goid, term in",
"import join from os import system import sys ## import timeit ## import",
"'{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo',",
"only the user-specified relationships\"\"\" # Leaf GO: viral triggering of virus induced gene",
"{REL} {rel} {GO_name}\\n') nts = [nt for go, nt in go2nt.items() if go",
"term.get_all_upper() #### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) ####",
"D06 R08 regulation of gene silencing #ffd1df GO:0060147 # BP 24 4 D07",
"== RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS:",
"in goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150",
"GO:0060148 # BP 8 3 D08 R10 positive regulation of posttranscriptional gene silencing",
"== 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships ==",
"sys ## import timeit ## import datetime import collections as cx from goatools.base",
"print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors))",
"virus induced gene silencing # - Generate GO DAG subset for this test",
"== rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all",
"2417 65 D04 R04 positive regulation of cellular process #ffd1df GO:0060255 # BP",
"assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441'",
"print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items():",
"__copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path import",
"sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid) #### # print('DAG',",
"sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for rel,",
"go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates'])",
"of virus induced gene silencing goid_chosen = 'GO:0060150' # Load GODag with all",
"positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen]",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS:",
"in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all =",
"prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo",
"sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) ####",
"assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50",
"for goid, dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors =",
"a source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral",
"GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1",
"#### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid) #### #",
"'_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that",
"k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print",
"#### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### #",
"virus induced gene silencing goid_chosen = 'GO:0060150' # Load GODag with all relationships",
"{NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts =",
"is the same as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 =",
"REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the two go2obb",
"fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5}",
"for k in o.relationship.keys()) # objs_r1_sub = set(o.id for o in objs_r1_all if",
"join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship'])",
"ancestors from only the user-specified relationships\"\"\" # Leaf GO: viral triggering of virus",
"'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr",
"= {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par",
"godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen])",
"{GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'),",
"GO IDs as a source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag,",
"Load GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 =",
"for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for",
"gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items()",
"-o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1):",
"\"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO,",
"assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates",
"for o in godag.values() if o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all",
"go2obb dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright",
"only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py #",
"__name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019, <NAME>, <NAME>, All",
"GO IDs that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf",
"contains ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py",
"optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above this low-level",
"# Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid,",
"ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates',",
"source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral =",
"GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO}",
"gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0,",
"elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag = {go:o for go, o",
"# def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the two go2obb dicts.\"\"\"",
"objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in",
"induced gene silencing goid_chosen = 'GO:0060150' # Load GODag with all relationships fin_obo",
"goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All",
"os.path import join from os import system import sys ## import timeit ##",
"goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test",
"assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL:",
"in pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150']",
"\"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py #",
"import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import",
"Loop through r0 GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid,",
"{rel} {GO_name}\\n') nts = [nt for go, nt in go2nt.items() if go in",
"set(o.id for o in gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf: go_parents",
"goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__ =",
"def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the two go2obb dicts.\"\"\" #",
"relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]),",
"rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\"",
"o in godag.values() if not o.children) gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all",
"o.relationship.keys()) # objs_r1_sub = set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,}",
"DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w')",
"in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term",
"sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items(): ####",
"datetime import collections as cx from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET",
"prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs",
"# goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright",
"regulation of posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0 0 D09 R11",
"r1_ancestors_more = set() # Loop through r0 GO IDs for goid, term in",
"in o.relationship.keys()) # objs_r1_sub = set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys()))",
"TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships",
"os import system import sys ## import timeit ## import datetime import collections",
"'**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'})",
"= gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships ==",
"file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above this low-level GO",
"set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp =",
"--go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt:",
"GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates",
"{D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for go, nt in go2nt.items() if",
"r1 GO terms in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py",
"#ffd1df GO:0010468 # BP 862 20 D05 R05 regulation of gene expression #ffd1df",
"\"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o for o in godag.values() if",
"gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' #",
"= _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs as a",
"# Pick one of the GO IDs as a source for the subset",
"RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO",
"return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o for",
"'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag",
"regulation of posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8 3 D08 R10",
"positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships",
"# print(rel, ' '.join(sorted(o.id for o in pterms))) #### # print('') #### print(gosubdag_rp.relationships)",
"regulates positively_regulates negatively_regulates regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert",
"IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o",
"# for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for o",
"print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt ####",
"GO:0060255 # BP 2130 20 D04 R04 regulation of macromolecule metabolic process #ffd1df",
"'_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all relationships up",
"GO:0048522 # BP 2417 65 D04 R04 positive regulation of cellular process #ffd1df",
"Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def",
"in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par,",
"BP 8278 64 D03 R03 regulation of cellular process #ffd1df GO:0019222 # BP",
"cellular process #ffd1df GO:0019222 # BP 3382 20 D03 R03 regulation of metabolic",
"details of GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} '",
"#### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items():",
"godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral,",
"than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt'",
"for o in pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not",
"term in gosubdag_r0.go2obj.items(): ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0",
"godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12",
"if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all =",
"= set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values() if",
"test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # Leaf",
"{GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt = ('#ffd1df",
"# pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019,",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS:",
"gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() #",
"{childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for",
"godag = {go:o for go, o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag)",
"print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### # for",
"'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt for go, nt",
"= set(k for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels ==",
"#### # for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id for",
"print(rel, ' '.join(sorted(o.id for o in pterms))) #### # print('') #### print(gosubdag_rp.relationships) ####",
"#### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1):",
"= gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert",
"in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP",
"-r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb",
"= cx.Counter(k for o in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub =",
"'__main__': test_gosubdag_relationships(len(sys.argv) != 1) # Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.",
"goids_viral, prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1",
"{go:o for go, o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all =",
"#### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp",
"used for visualizing this test file's elements\"\"\" # Load GO-DAG: Load optional 'relationship'",
"'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'})",
"o in gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid]",
"__future__ import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\"",
"if goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] ####",
"gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid) ####",
"assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates positively_regulates negatively_regulates regs",
"positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0 0 D09",
"Load optional 'relationship' godag = {go:o for go, o in godag_r1.items() if go",
"TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of)",
"RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL",
"_prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of",
"import datetime import collections as cx from goatools.base import get_godag from goatools.godag.consts import",
"# tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from",
"import WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that",
"relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) ==",
"8278 64 D03 R03 regulation of cellular process #ffd1df GO:0019222 # BP 3382",
"fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt)",
"two go2obb dicts.\"\"\" # pass if __name__ == '__main__': test_gosubdag_relationships(len(sys.argv) != 1) #",
"godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in",
"goids] for ntd in sorted(nts, key=lambda nt: nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df",
"goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>,",
"# RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par",
"2130 20 D04 R04 regulation of macromolecule metabolic process #ffd1df GO:0010468 # BP",
"objs_r1_all for k in o.relationship.keys()) # objs_r1_sub = set(o.id for o in objs_r1_all",
"relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn =",
"gene silencing #ffd1df GO:0060148 # BP 8 3 D08 R10 positive regulation of",
"rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of)",
"gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs as a source for the",
"def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o for o in",
"relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo, goids_viral, prt)",
"o in pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in",
"GO-DAG: Load optional 'relationship' godag = {go:o for go, o in godag_r1.items() if",
"gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if",
"godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True)",
"test file's elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag = {go:o for",
"-o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more,",
"<NAME>, All rights reserved.\" from os.path import join from os import system import",
"relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj,",
"= '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO,",
"'GO:0060150' # Load GODag with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\")",
"if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0)",
"# RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par",
"nts = [nt for go, nt in go2nt.items() if go in goids] for",
"# BP 8278 64 D03 R03 regulation of cellular process #ffd1df GO:0019222 #",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert",
"objs_r1_all = set(o for o in godag.values() if o.relationship.keys()) octr = cx.Counter(k for",
"print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py",
"gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the count of relationships.\"\"\" objs_r1_all = set(o",
"gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] #",
"{GO_name}\\n') nts = [nt for go, nt in go2nt.items() if go in goids]",
"one of the GO IDs as a source for the subset DAG gosubdag_viral",
"GO: viral triggering of virus induced gene silencing goid_chosen = 'GO:0060150' # Load",
"Pick one of the GO IDs as a source for the subset DAG",
"# print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS',",
"assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj,",
"ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 ==",
"ancestors_r0 = gosubdag_r0.rcntobj.go2ancestors.get(goid, set()) ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert",
"'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids,",
"R03 regulation of metabolic process #ffd1df GO:0048522 # BP 2417 65 D04 R04",
"gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels =",
"regs = {'positively_regulates', 'negatively_regulates'} gosubdag_rnp = GoSubDag(set([goid_chosen]), godag_r1, relationships=regs) assert gosubdag_rnp.relationships == regs",
"assert ancestors_r1 == term.get_all_upper() #### # Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1,",
"if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag",
"12 # RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET",
"godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all",
"assert gosubdag_rp.relationships == set(['positively_regulates']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]),",
"user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py #",
"goid in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict",
"# Loop through r0 GO IDs for goid, term in gosubdag_r0.go2obj.items(): ancestors_r0 =",
"BP 3382 20 D03 R03 regulation of metabolic process #ffd1df GO:0048522 # BP",
"expression #ffd1df GO:0060968 # BP 53 4 D06 R08 regulation of gene silencing",
"in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]),",
"#assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467'",
"with all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None)",
"gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] #",
"subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo,",
"# RELATIONSHIPS: ALL gosubdag_r1 = GoSubDag(set([goid_chosen]), godag_r1, relationships=True) assert gosubdag_r1.relationships == RELATIONSHIP_SET ####",
"DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot",
"# goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py # goatools/obo_parser.py from __future__ import print_function __copyright__",
"# RELATIONSHIPS: negatively_regulates gosubdag_rn = GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par",
"#ffd1df GO:0060150 # BP 0 0 D09 R11 viral triggering of virus induced",
"{REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between the two",
"timeit ## import datetime import collections as cx from goatools.base import get_godag from",
"len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in GoSubDag have more ancestors",
"this test file's elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag = {go:o",
"gosubdag_r0 = GoSubDag(set([goid_chosen]), godag_r0) assert len(gosubdag_r0.rcntobj.go2ancestors[goid_chosen]) == 12 # RELATIONSHIPS: ALL gosubdag_r1 =",
"\"\"\"Get GO IDs that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set()",
"set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values() if not",
"All rights reserved.\" from os.path import join from os import system import sys",
"go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def",
"# BASELINE r1: Test that GOTerm.get_all_upper() is the same as GoSubDag ancestors for",
"'{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def",
"rights reserved.\" from os.path import join from os import system import sys ##",
"that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # Leaf GO: viral",
"viral triggering of virus induced gene silencing # - Generate GO DAG subset",
"regulation of metabolic process #ffd1df GO:0048522 # BP 2417 65 D04 R04 positive",
"if o.relationship.keys()) octr = cx.Counter(k for o in objs_r1_all for k in o.relationship.keys())",
"gene silencing goid_chosen = 'GO:0060150' # Load GODag with all relationships fin_obo =",
"gosubdag_r1.relationships == RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 #",
"= {go:o for go, o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all",
"{OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r'",
"= set(o.id for o in gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf:",
"GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all relationships up their",
"scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as",
"print(' WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt",
"(C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path import join from os",
"ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### # Test that ####",
"in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr: gos_r1_relsinhier.add(goid) return gos_r1_relsinhier def _prt_rtel_ctr(godag): \"\"\"Print the",
"GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS:",
"regulation of gene silencing #ffd1df GO:0060147 # BP 24 4 D07 R09 regulation",
"from os import system import sys ## import timeit ## import datetime import",
"prt) print('{N} GO IDs WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 =",
"relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub):",
"rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1,",
"print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path",
"assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert",
"\"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub",
"{dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02} {D1:5} {REL} {rel} {GO_name}\\n') nts = [nt",
"#ffd1df GO:0060968 # BP 53 4 D06 R08 regulation of gene silencing #ffd1df",
"# pylint: disable=line-too-long,unused-variable def test_gosubdag_relationships(wr_new_obo_subset=False): \"\"\"Test that GoSubDag contains ancestors from only the",
"print('{N} r1 GO terms in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) #",
"the subset DAG gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with",
"# print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) #### #",
"50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of'])",
"gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION",
"# Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 =",
"== set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen] # assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION",
"o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates',",
"GO:0010468 # BP 862 20 D05 R05 regulation of gene expression #ffd1df GO:0060968",
"Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more = set() # Loop through r0",
"goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from goatools.test_data.wr_subobo",
"rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values()",
"# \"\"\"Check the differences between the two go2obb dicts.\"\"\" # pass if __name__",
"REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM",
"'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of gosubdag_rp = GoSubDag(set([goid_chosen]),",
"# scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w')",
"not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par,",
"in gosubdag_r1.rcntobj.go2ancestors: #### ancestors = gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict =",
"in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\"",
"goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs as",
"gosubdag_r1 = GoSubDag(goids_leaf_all, godag, relationships=True, prt=sys.stdout) goids_src_r1_all = _get_leafs_w_relsinhier(rels_all, gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick",
"RELATIONSHIP_SET #### set(['part_of', 'regulates', 'positively_regulates', 'negatively_regulates']) assert len(gosubdag_r1.rcntobj.go2ancestors[goid_chosen]) == 50 # RELATIONSHIPS: part_of",
"TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents'",
"gosubdag_viral = GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as",
"= set() # Loop through r0 GO IDs for goid, term in gosubdag_r0.go2obj.items():",
"process #ffd1df GO:0010468 # BP 862 20 D05 R05 regulation of gene expression",
"PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs",
"not o.children) for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for",
"regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships == set(['regulates']) rp_par = gosubdag_rr.rcntobj.go2ancestors[goid_chosen]",
"for o in gosubdag_r1.go2obj.values() if not o.children) for goid in goids_leaf: go_parents =",
"in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' assert 'GO:0016441' not in rp_par, '**FATAL:",
"all relationships fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1",
"silencing goid_chosen = 'GO:0060150' # Load GODag with all relationships fin_obo = join(REPO,",
"silencing #ffd1df GO:0060150 # BP 0 0 D09 R11 viral triggering of virus",
"64 D03 R03 regulation of cellular process #ffd1df GO:0019222 # BP 3382 20",
"set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441' not in gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of)",
"from __future__ import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights",
"# \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub =",
"gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) ####",
"GoSubDag(set([goid_chosen]), godag_r1, relationships={'negatively_regulates'}) assert gosubdag_rn.relationships == set(['negatively_regulates']) rp_par = gosubdag_rn.rcntobj.go2ancestors[goid_chosen] # RELATIONSHIPS: regulates",
"go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' #",
"BP 8 3 D08 R10 positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150",
"for goid in goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in",
"pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] ####",
"this low-level GO ID using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo)",
"#!/usr/bin/env python \"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" #",
"fin_obo = join(REPO, \"tests/data/i126/viral_gene_silence.obo\") # \"go-basic.obo\") godag_r0 = get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo,",
"'GO:0016441' not in rp_par, '**FATAL: REGULATION TERM GoSubDag(part_of) go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp",
"' '.join(sorted(o.id for o in pterms))) #### # print('') #### print(gosubdag_rp.relationships) #### #assert",
"relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): #### if goid in gosubdag_r1.rcntobj.go2ancestors:",
"print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in",
"i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt,",
"go, o in godag_r1.items() if go == o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates',",
"2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path import join from os import",
"system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO",
"import timeit ## import datetime import collections as cx from goatools.base import get_godag",
"= gosubdag_rp.rcntobj.go2ancestors[goid] #### sub_term = gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid)",
"get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above",
"#### # print('') #### print(gosubdag_rp.relationships) #### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert",
"GoSubDag({goid_chosen}, godag, relationships=True, prt=sys.stdout) goids_viral = set(gosubdag_viral.go2obj.keys()) with open(fout_obo, 'w') as prt: WrSubObo.prt_goterms(fin_obo,",
"= \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from os.path import join",
"8 3 D08 R10 positive regulation of posttranscriptional gene silencing #ffd1df GO:0060150 #",
"import GoSubDag from goatools.test_data.wr_subobo import WrSubObo from tests.utils import REPO # pylint: disable=line-too-long,unused-variable",
"_prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for o in",
"#### #assert 'GO:0016441' not in gosubdag_rp.rcntobj.go2ancestors['GO:0060150'] #### assert 'GO:0016441' in gosubdag_r1.go2nt #### assert",
"same as GoSubDag ancestors for goid, term in gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set())",
"gosubdag_r1) gosubdag_r1.prt_goids(goids_src_r1_all) # Pick one of the GO IDs as a source for",
"the GO IDs as a source for the subset DAG gosubdag_viral = GoSubDag({goid_chosen},",
"-r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo',",
"gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1: Test that GOTerm.get_all_upper() is the same as",
"gosubdag_rp.go2obj, '**FATAL: REGULATION TERM GoSubDag(part_of) go2obj' # assert 'GO:0016441' not in rp_par, '**FATAL:",
"macromolecule metabolic process #ffd1df GO:0010468 # BP 862 20 D05 R05 regulation of",
"positive regulation of cellular process #ffd1df GO:0060255 # BP 2130 20 D04 R04",
"o in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub = set(o.id for o",
"gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if",
"in objs_r1_all for k in o.relationship.keys()) # objs_r1_sub = set(o.id for o in",
"Test that #### gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term",
"= sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper()))",
"#### # print(rel, ' '.join(sorted(o.id for o in pterms))) #### # print('') ####",
"WROTE: {GOs}'.format(GOs=fout_gos)) def _prt_goterms(goids, go2nt, prt): \"\"\"Print details of GO terms\"\"\" fmt =",
"D09 R11 viral triggering of virus induced gene silencing # - Generate GO",
"BP 2130 20 D04 R04 regulation of macromolecule metabolic process #ffd1df GO:0010468 #",
"def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents() == GoSubDag ancestors\"\"\" r1_ancestors_more =",
"from goatools.base import get_godag from goatools.godag.consts import RELATIONSHIP_SET from goatools.gosubdag.gosubdag import GoSubDag from",
"#### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE r0: Test that GOTerm.get_all_parents()",
"subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used",
"octr.most_common(): print('{N:6,} {REL}'.format(N=cnt, REL=key)) # def _chk_child_parent(go2o_dag, go2o_sub): # \"\"\"Check the differences between",
"join(REPO, \"tests/data/viral_gene_silence.obo\") # Get all GO terms above this low-level GO ID using",
"gene silencing #ffd1df GO:0060147 # BP 24 4 D07 R09 regulation of posttranscriptional",
"for visualizing this test file's elements\"\"\" # Load GO-DAG: Load optional 'relationship' godag",
"Leaf GO: viral triggering of virus induced gene silencing goid_chosen = 'GO:0060150' #",
"{GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr,",
"r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo -o i126_goids_baseline.png fout_gos = 'i126_goids_baseline.txt' with",
"go2parents' # RELATIONSHIPS: positively_regulates gosubdag_rp = GoSubDag(set([goid_chosen]), godag_r1, relationships={'positively_regulates'}) assert gosubdag_rp.relationships == set(['positively_regulates'])",
"{PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r0.png'), GO=goid_chosen)) def _get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get",
"BASELINE r1: Test that GOTerm.get_all_upper() is the same as GoSubDag ancestors for goid,",
"'positively_regulates']) goids_leaf_all = set(o.id for o in godag.values() if not o.children) gosubdag_r1 =",
"== term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1",
"not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have relationships.'.format(N=len(objs_r1_all))) for key, cnt in octr.most_common(): print('{N:6,}",
"goids_leaf: go_parents = gosubdag_r1.rcntobj.go2ancestors[goid] rels = set(k for p in go_parents for k",
"{PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}' system(pat_r1.format(REPO=REPO, PNG=fout_obo.replace('.obo', '_r1.png'), GO=goid_chosen)) system(pat_r0.format(REPO=REPO,",
"import print_function __copyright__ = \"Copyright (C) 2016-2019, <NAME>, <NAME>, All rights reserved.\" from",
"godag_r1, relationships={'part_of'}, prt=sys.stdout) #### for goid, dag_term in godag_r1.items(): #### if goid in",
"of posttranscriptional gene silencing #ffd1df GO:0060150 # BP 0 0 D09 R11 viral",
"gosubdag_r1.go2obj.items(): ancestors_r1 = gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r1 == term.get_all_upper() #### # Test that",
"all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0 =",
"# BP 53 4 D06 R08 regulation of gene silencing #ffd1df GO:0060147 #",
"= GoSubDag(set([goid_chosen]), godag_r1, relationships={'part_of'}) assert gosubdag_rp.relationships == set(['part_of']) rp_par = gosubdag_rp.rcntobj.go2ancestors[goid_chosen] assert 'GO:0016441'",
"assert 'GO:0016441' in gosubdag_r1.go2nt #### assert 'GO:0010467' in gosubdag_r1.go2nt def _run_baseline_r0(gosubdag_r0, gosubdag_r1): \"\"\"BASELINE",
"ancestors\"\"\" r1_ancestors_more = set() # Loop through r0 GO IDs for goid, term",
"sorted(ancestors)) #### # for rel, pterms in cx.OrderedDict(reldict).items(): #### # print(rel, ' '.join(sorted(o.id",
"with open(fout_gos, 'w') as prt: prt.write('#cafffb {SRC_GO}\\n'.format(SRC_GO=next(iter(gosubdag_r0.go_sources)))) _prt_goterms(r1_ancestors_more, gosubdag_r1.go2nt, prt) print(' WROTE: {GOs}'.format(GOs=fout_gos))",
"_wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this test file's elements\"\"\"",
"of posttranscriptional gene silencing #ffd1df GO:0060148 # BP 8 3 D08 R10 positive",
"python \"\"\"Test that GoSubDag contains ancestors from only the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py",
"nt.dcnt, reverse=True): prt.write(fmt.format(**ntd._asdict())) #cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03 R03",
"GO terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02}",
"using all relationships if wr_new_obo_subset: _wr_sub_obo(file_sub, goid_chosen, godag_r1, fin_obo) # RELATIONSHIPS: None gosubdag_r0",
"#### # print('DAG', sorted(dag_term.get_all_upper())) #### # print('SUB', sorted(sub_term.get_all_upper())) #### # print('ANS', sorted(ancestors)) ####",
"R08 regulation of gene silencing #ffd1df GO:0060147 # BP 24 4 D07 R09",
"this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing",
"relationships up their hierarchy.\"\"\" gos_r1_relsinhier = set() goids_leaf = set(o.id for o in",
"= get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") #",
"\"\"\"Check the differences between the two go2obb dicts.\"\"\" # pass if __name__ ==",
"ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid) assert r1_ancestors_more print('{N} r1 GO terms in",
"test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this",
"GO DAG subset for this test --------------------------------------------------------- def _wr_sub_obo(fout_obo, goid_chosen, godag_r1, fin_obo): \"\"\"Sub",
"goid_chosen, godag_r1, fin_obo): \"\"\"Sub plot used for visualizing this test file's elements\"\"\" #",
"of the GO IDs as a source for the subset DAG gosubdag_viral =",
"set(k for p in go_parents for k in gosubdag_r1.go2obj[p].relationship.keys()) if rels == rels_usr:",
"#cafffb GO:0060150 #ffd1df GO:0050794 # BP 8278 64 D03 R03 regulation of cellular",
"R11 viral triggering of virus induced gene silencing # - Generate GO DAG",
"the user-specified relationships\"\"\" # tests/test_gosubdag_relationships_i126.py # goatools/gosubdag/gosubdag.py # goatools/gosubdag/godag_rcnt.py # goatools/gosubdag/godag_rcnt_init.py # goatools/godag/go_tasks.py",
"get_godag(fin_obo, loading_bar=None) godag_r1 = get_godag(fin_obo, loading_bar=None, optional_attrs=['relationship']) file_sub = join(REPO, \"tests/data/viral_gene_silence.obo\") # Get",
"BP 0 0 D09 R11 viral triggering of virus induced gene silencing #",
"contains ancestors from only the user-specified relationships\"\"\" # Leaf GO: viral triggering of",
"== o.item_id} _prt_rtel_ctr(godag) rels_all = set(['part_of', 'regulates', 'negatively_regulates', 'positively_regulates']) goids_leaf_all = set(o.id for",
"GoSubDag(part_of) go2parents' # RELATIONSHIPS: regulates gosubdag_rr = GoSubDag(set([goid_chosen]), godag_r1, relationships={'regulates'}) assert gosubdag_rr.relationships ==",
"relationships=regs) assert gosubdag_rnp.relationships == regs rp_par = gosubdag_rnp.rcntobj.go2ancestors[goid_chosen] _run_baseline_r0(gosubdag_r0, gosubdag_r1) # BASELINE r1:",
"WROTE: {OBO}'.format(N=len(goids_viral), OBO=fout_obo)) # Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG}",
"terms\"\"\" fmt = ('#ffd1df {GO} # {NS} {dcnt:5} {childcnt:3} ' 'L{level:02} D{depth:02} R{reldepth:02}",
"= gosubdag_rp.go2obj[goid] #### reldict = sub_term.relationship.items() #### # print(goid) #### # print('DAG', sorted(dag_term.get_all_upper()))",
"gosubdag_r1.rcntobj.go2ancestors.get(goid, set()) assert ancestors_r0 == term.get_all_parents() assert ancestors_r0.issubset(ancestors_r1) if len(ancestors_r0) < len(ancestors_r1): r1_ancestors_more.add(goid)",
"Plot obo subset pat_r1 = '{REPO}/scripts/go_plot.py {GO} -o {PNG} -r' pat_r0 = '{REPO}/scripts/go_plot.py",
"_get_leafs_w_relsinhier(rels_usr, gosubdag_r1): \"\"\"Get GO IDs that have all relationships up their hierarchy.\"\"\" gos_r1_relsinhier",
"in GoSubDag have more ancestors than r0'.format( N=len(r1_ancestors_more))) # scripts/go_plot.py --go_file=i126_goids_baseline.txt -r --obo=tests/data/viral_gene_silence.obo",
"= set(o.id for o in objs_r1_all if not rels_all.isdisjoint(o.relationship.keys())) print('{N:6,} GO Terms have",
"D03 R03 regulation of metabolic process #ffd1df GO:0048522 # BP 2417 65 D04"
] |
[
"1 != 2: print(\"true\") if 1 != 2: print(\"true\") if not 1 <",
"or, not if 1 < 2 and 1 < 3: print(\"true\") else: print(\"false\")",
"< 3: print(\"true\") else: print(\"false\") if 1 < 0 or 1 > 2:",
"!= 2: print(\"true\") if not 1 < 0: # \"not <expr>\" means false",
"if 1 < 2 and 1 < 3: print(\"true\") else: print(\"false\") if 1",
"< 2 and 1 < 3: print(\"true\") else: print(\"false\") if 1 < 0",
"not 1 < 0: # \"not <expr>\" means false print(\"1 is not less",
"print(\"false\") if 1 < 0 or 1 > 2: print(\"true\") else: print(\"false\") if",
"print(\"false\") if 1 != 2: print(\"true\") if 1 != 2: print(\"true\") if not",
"3: print(\"true\") else: print(\"false\") if 1 < 0 or 1 > 2: print(\"true\")",
"!= 2: print(\"true\") if 1 != 2: print(\"true\") if not 1 < 0:",
"#!/usr/bin/env python3 # and, or, not if 1 < 2 and 1 <",
"and, or, not if 1 < 2 and 1 < 3: print(\"true\") else:",
"not if 1 < 2 and 1 < 3: print(\"true\") else: print(\"false\") if",
"if not 1 < 0: # \"not <expr>\" means false print(\"1 is not",
"1 != 2: print(\"true\") if not 1 < 0: # \"not <expr>\" means",
"else: print(\"false\") if 1 != 2: print(\"true\") if 1 != 2: print(\"true\") if",
"< 0: # \"not <expr>\" means false print(\"1 is not less than 0\")",
"<reponame>CrazyJ36/python #!/usr/bin/env python3 # and, or, not if 1 < 2 and 1",
"< 0 or 1 > 2: print(\"true\") else: print(\"false\") if 1 != 2:",
"1 < 3: print(\"true\") else: print(\"false\") if 1 < 0 or 1 >",
"or 1 > 2: print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\") if",
"1 < 2 and 1 < 3: print(\"true\") else: print(\"false\") if 1 <",
"2: print(\"true\") if 1 != 2: print(\"true\") if not 1 < 0: #",
"else: print(\"false\") if 1 < 0 or 1 > 2: print(\"true\") else: print(\"false\")",
"2 and 1 < 3: print(\"true\") else: print(\"false\") if 1 < 0 or",
"1 < 0 or 1 > 2: print(\"true\") else: print(\"false\") if 1 !=",
"1 > 2: print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\") if 1",
"> 2: print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\") if 1 !=",
"print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\") if 1 != 2: print(\"true\")",
"print(\"true\") if 1 != 2: print(\"true\") if not 1 < 0: # \"not",
"2: print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\") if 1 != 2:",
"2: print(\"true\") if not 1 < 0: # \"not <expr>\" means false print(\"1",
"print(\"true\") else: print(\"false\") if 1 < 0 or 1 > 2: print(\"true\") else:",
"# and, or, not if 1 < 2 and 1 < 3: print(\"true\")",
"if 1 < 0 or 1 > 2: print(\"true\") else: print(\"false\") if 1",
"python3 # and, or, not if 1 < 2 and 1 < 3:",
"if 1 != 2: print(\"true\") if 1 != 2: print(\"true\") if not 1",
"1 < 0: # \"not <expr>\" means false print(\"1 is not less than",
"and 1 < 3: print(\"true\") else: print(\"false\") if 1 < 0 or 1",
"if 1 != 2: print(\"true\") if not 1 < 0: # \"not <expr>\"",
"0 or 1 > 2: print(\"true\") else: print(\"false\") if 1 != 2: print(\"true\")",
"print(\"true\") if not 1 < 0: # \"not <expr>\" means false print(\"1 is"
] |
[
"import logger from base import db from base.users.models import User from base.threads.models import",
"= int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none if",
"user_id = g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id)) comment.vote(user_id=user_id) logger.info(comment.votes) return",
"logzero import logger from base import db from base.users.models import User from base.threads.models",
"= g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return",
"import db from base.users.models import User from base.threads.models import Thread, Comment from base.users.decorators",
"empty means none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1",
"comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via ajax \"\"\"",
"thread_id = int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id))",
"session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\": token =",
"not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token())",
"All view code for async get/post calls towards the server must be contained",
"in the last hour. user_id = g.user.id if not user_id: abort(404) since =",
"has not submitted more than 20 comments # in the last hour. user_id",
"request, render_template, flash, g, session, redirect, url_for, jsonify, abort) from werkzeug import check_password_hash,",
"abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST'])",
"= arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if",
"comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread():",
"from flask import (Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify, abort)",
"or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments",
"import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None",
"too many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] #",
"thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username,",
"if not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id ==",
"@mod.before_request def csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token', None) if not",
"render_template, flash, g, session, redirect, url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash",
"the last hour. user_id = g.user.id if not user_id: abort(404) since = arrow.utcnow()",
"== user_id, Comment.created_on > since).count() if submission_count >= 20: return jsonify(error='You have been",
"comment_parent_id = request.form['parent_id'] # empty means none if not comment_text: abort(404) thread =",
"methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id'])",
"request.method == \"POST\": token = session.pop('csrf_token', None) if not token or token !=",
"mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None if 'user_id'",
"def before_request(): g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request",
"\"POST\": token = session.pop('csrf_token', None) if not token or token != request.form.get('csrf_token'): abort(403)",
"base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user =",
"contained in this file. \"\"\" import arrow from flask import (Blueprint, request, render_template,",
"jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via ajax",
"return jsonify(error='You have been submitting too many comments') thread_id = int(request.form['thread_id']) comment_text =",
"jsonify(error='You have been submitting too many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text']",
"return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit",
"token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via",
"async get/post calls towards the server must be contained in this file. \"\"\"",
"@mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via ajax \"\"\" # Check",
"@requires_login def vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id",
"since).count() if submission_count >= 20: return jsonify(error='You have been submitting too many comments')",
"last hour. user_id = g.user.id if not user_id: abort(404) since = arrow.utcnow() -",
"@mod.before_request def before_request(): g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id'])",
"Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if not",
"arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count",
"= g.user.id if not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count =",
"generate_password_hash from logzero import logger from base import db from base.users.models import User",
"= session.pop('csrf_token', None) if not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST'])",
"in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\": token",
"\"\"\" Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if",
"means none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit()",
"save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id",
"= g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id)) comment.vote(user_id=user_id) logger.info(comment.votes) return jsonify(votes=comment.votes,",
"generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request():",
"redirect, url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from logzero import logger",
"ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread",
"session, redirect, url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from logzero import",
"@requires_login def submit_comment(): \"\"\" Submit comments via ajax \"\"\" # Check that user",
"request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none if not comment_text: abort(404) thread",
"User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token', None) if",
"comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST'])",
"submitted more than 20 comments # in the last hour. user_id = g.user.id",
"save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via ajax \"\"\"",
"\"\"\" # Check that user has not submitted more than 20 comments #",
"must be contained in this file. \"\"\" import arrow from flask import (Blueprint,",
"session.pop('csrf_token', None) if not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login",
"from logzero import logger from base import db from base.users.models import User from",
"request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via ajax \"\"\"",
"from base import db from base.users.models import User from base.threads.models import Thread, Comment",
"submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count >= 20: return",
"comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means",
"werkzeug import check_password_hash, generate_password_hash from logzero import logger from base import db from",
"= request.form['parent_id'] # empty means none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id))",
"db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/',",
"int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status =",
"from werkzeug import check_password_hash, generate_password_hash from logzero import logger from base import db",
"server must be contained in this file. \"\"\" import arrow from flask import",
"if submission_count >= 20: return jsonify(error='You have been submitting too many comments') thread_id",
"requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__,",
"g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect():",
"user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id)",
"base.threads.models import Thread, Comment from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from",
"return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via",
"g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id)) comment.vote(user_id=user_id) logger.info(comment.votes) return jsonify(votes=comment.votes, csrf_token=generate_csrf_token())",
"@mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id =",
"# in the last hour. user_id = g.user.id if not user_id: abort(404) since",
"Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count >= 20: return jsonify(error='You have",
"def vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id =",
"base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod =",
"\"\"\" Submit comments via ajax \"\"\" # Check that user has not submitted",
"from base.users.models import User from base.threads.models import Thread, Comment from base.users.decorators import requires_login",
"have been submitting too many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id",
"= None if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if",
"not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\"",
"thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/',",
"import User from base.threads.models import Thread, Comment from base.users.decorators import requires_login from base.utils.misc",
"via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404)",
"= thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit",
"jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes",
"jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from logzero import logger from base",
"import arrow from flask import (Blueprint, request, render_template, flash, g, session, redirect, url_for,",
"= thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit",
"Submit comments via ajax \"\"\" # Check that user has not submitted more",
"(Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify, abort) from werkzeug import",
"= Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text),",
"comment_id = int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id))",
"- arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count >=",
"= g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return",
"user_id = g.user.id if not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count",
"csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id",
"not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token())",
"from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis')",
"20: return jsonify(error='You have been submitting too many comments') thread_id = int(request.form['thread_id']) comment_text",
"ajax \"\"\" # Check that user has not submitted more than 20 comments",
"int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none if not",
"= int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status",
"coding: utf-8 -*- \"\"\" All view code for async get/post calls towards the",
"in this file. \"\"\" import arrow from flask import (Blueprint, request, render_template, flash,",
"\"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if",
"import (Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify, abort) from werkzeug",
"comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none if not comment_text:",
"\"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread =",
"g, session, redirect, url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from logzero",
"g.user.id if not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id",
"== \"POST\": token = session.pop('csrf_token', None) if not token or token != request.form.get('csrf_token'):",
"many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty",
"__name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None if 'user_id' in session: g.user",
"# empty means none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments +=",
"base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request",
"<filename>base/apis/views.py # -*- coding: utf-8 -*- \"\"\" All view code for async get/post",
"if request.method == \"POST\": token = session.pop('csrf_token', None) if not token or token",
"import check_password_hash, generate_password_hash from logzero import logger from base import db from base.users.models",
"flash, g, session, redirect, url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from",
"if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status,",
"g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes,",
"\"\"\" import arrow from flask import (Blueprint, request, render_template, flash, g, session, redirect,",
"view code for async get/post calls towards the server must be contained in",
"return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via",
"before_request(): g.user = None if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def",
"the server must be contained in this file. \"\"\" import arrow from flask",
"for async get/post calls towards the server must be contained in this file.",
"via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404)",
"thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return",
"def vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id =",
"base.users.models import User from base.threads.models import Thread, Comment from base.users.decorators import requires_login from",
"thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes",
"db from base.users.models import User from base.threads.models import Thread, Comment from base.users.decorators import",
"abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via ajax \"\"\" #",
"from base.threads.models import Thread, Comment from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token",
"none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment",
"1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token())",
"= request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none if not comment_text: abort(404)",
"format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None if",
"abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST'])",
"if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method ==",
"thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login",
"submit_comment(): \"\"\" Submit comments via ajax \"\"\" # Check that user has not",
"votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id if not thread_id:",
"'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\":",
"User from base.threads.models import Thread, Comment from base.users.decorators import requires_login from base.utils.misc import",
"code for async get/post calls towards the server must be contained in this",
">= 20: return jsonify(error='You have been submitting too many comments') thread_id = int(request.form['thread_id'])",
"int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id)) comment.vote(user_id=user_id) logger.info(comment.votes)",
"@requires_login def vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id",
"user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id)",
"submission_count >= 20: return jsonify(error='You have been submitting too many comments') thread_id =",
"def submit_comment(): \"\"\" Submit comments via ajax \"\"\" # Check that user has",
"abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id)",
"Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread():",
"get/post calls towards the server must be contained in this file. \"\"\" import",
"calls towards the server must be contained in this file. \"\"\" import arrow",
"if not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment():",
"Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None if 'user_id' in session:",
"g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\"",
"Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment():",
"!= request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via ajax",
"ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404) comment",
"Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(),",
"\"\"\" All view code for async get/post calls towards the server must be",
"from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user",
"import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis',",
"token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit",
"user has not submitted more than 20 comments # in the last hour.",
"more than 20 comments # in the last hour. user_id = g.user.id if",
"-*- \"\"\" All view code for async get/post calls towards the server must",
"comments # in the last hour. user_id = g.user.id if not user_id: abort(404)",
"csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token', None) if not token or",
"g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves,",
"def csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token', None) if not token",
"token = session.pop('csrf_token', None) if not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/',",
"not submitted more than 20 comments # in the last hour. user_id =",
"flask import (Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify, abort) from",
"Comment.created_on > since).count() if submission_count >= 20: return jsonify(error='You have been submitting too",
"thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id'] # empty means none",
"towards the server must be contained in this file. \"\"\" import arrow from",
"= User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token', None)",
"vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\"",
"username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via ajax",
"\"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404) comment =",
"vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id = g.user.id",
"check_password_hash, generate_password_hash from logzero import logger from base import db from base.users.models import",
"url_for, jsonify, abort) from werkzeug import check_password_hash, generate_password_hash from logzero import logger from",
"Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if not",
"> since).count() if submission_count >= 20: return jsonify(error='You have been submitting too many",
"g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method == \"POST\": token = session.pop('csrf_token',",
"= Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def",
"@mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id =",
"url_prefix='/apis') @mod.before_request def before_request(): g.user = None if 'user_id' in session: g.user =",
"int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status =",
"logger from base import db from base.users.models import User from base.threads.models import Thread,",
"request.form['parent_id'] # empty means none if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments",
"methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id'])",
"= Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count >= 20: return jsonify(error='You",
"been submitting too many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id =",
"vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id",
"@mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id =",
"thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login",
"base import db from base.users.models import User from base.threads.models import Thread, Comment from",
"if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status,",
"methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id'])",
"Thread, Comment from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import",
"utf-8 -*- \"\"\" All view code for async get/post calls towards the server",
"Comment from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment",
"submitting too many comments') thread_id = int(request.form['thread_id']) comment_text = request.form['comment_text'] comment_parent_id = request.form['parent_id']",
"abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on >",
"csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id",
"via ajax \"\"\" # Check that user has not submitted more than 20",
"this file. \"\"\" import arrow from flask import (Blueprint, request, render_template, flash, g,",
"arrow from flask import (Blueprint, request, render_template, flash, g, session, redirect, url_for, jsonify,",
"def save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id =",
"vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via ajax \"\"\"",
"import generate_csrf_token from base.utils.text_utils import format_comment mod = Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def",
"None) if not token or token != request.form.get('csrf_token'): abort(403) @mod.route('/comments/submit/', methods=['POST']) @requires_login def",
"= int(request.form['thread_id']) user_id = g.user.id if not thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status",
"# Check that user has not submitted more than 20 comments # in",
"comments via ajax \"\"\" # Check that user has not submitted more than",
"@requires_login def save_thread(): \"\"\" Submit votes via ajax \"\"\" thread_id = int(request.form['thread_id']) user_id",
"# -*- coding: utf-8 -*- \"\"\" All view code for async get/post calls",
"thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def",
"not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id,",
"date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login def vote_thread(): \"\"\" Submit votes via",
"than 20 comments # in the last hour. user_id = g.user.id if not",
"arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count() if submission_count >= 20:",
"file. \"\"\" import arrow from flask import (Blueprint, request, render_template, flash, g, session,",
"import Thread, Comment from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils",
"abort) from werkzeug import check_password_hash, generate_password_hash from logzero import logger from base import",
"thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes",
"20 comments # in the last hour. user_id = g.user.id if not user_id:",
"None if 'user_id' in session: g.user = User.query.get(session['user_id']) @mod.before_request def csrf_protect(): if request.method",
"csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\" Submit votes via ajax \"\"\" comment_id",
"-*- coding: utf-8 -*- \"\"\" All view code for async get/post calls towards",
"= thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id, csrf_token=generate_csrf_token()) @mod.route('/threads/vote/', methods=['POST']) @requires_login",
"be contained in this file. \"\"\" import arrow from flask import (Blueprint, request,",
"user_id, Comment.created_on > since).count() if submission_count >= 20: return jsonify(error='You have been submitting",
"thread_id: abort(404) thread = Thread.query.get_or_404(int(thread_id)) save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/',",
"not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text,",
"from base.users.decorators import requires_login from base.utils.misc import generate_csrf_token from base.utils.text_utils import format_comment mod",
"that user has not submitted more than 20 comments # in the last",
"user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on",
"votes via ajax \"\"\" comment_id = int(request.form['comment_id']) user_id = g.user.id if not comment_id:",
"since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime submission_count = Comment.query.filter(Comment.user_id == user_id, Comment.created_on > since).count()",
"Check that user has not submitted more than 20 comments # in the",
"hour. user_id = g.user.id if not user_id: abort(404) since = arrow.utcnow() - arrow.utcnow().shift(hours=-1).datetime",
"jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def save_thread(): \"\"\" Submit votes via ajax",
"= Blueprint('apis', __name__, url_prefix='/apis') @mod.before_request def before_request(): g.user = None if 'user_id' in",
"methods=['POST']) @requires_login def submit_comment(): \"\"\" Submit comments via ajax \"\"\" # Check that",
"+= 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id, g.user.id) return jsonify(comment_text=format_comment(comment.text), date=comment.pretty_date(), username=g.user.username, comment_id=comment.id,",
"if not comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment =",
"comment_text: abort(404) thread = Thread.query.get_or_404(int(thread_id)) thread.n_comments += 1 db.session.commit() comment = thread.add_comment(comment_text, comment_parent_id,",
"= int(request.form['comment_id']) user_id = g.user.id if not comment_id: abort(404) comment = Comment.query.get_or_404(int(comment_id)) comment.vote(user_id=user_id)",
"= Thread.query.get_or_404(int(thread_id)) vote_status = thread.vote(user_id=user_id) return jsonify(new_votes=thread.votes, vote_status=vote_status, csrf_token=generate_csrf_token()) @mod.route('/threads/save/', methods=['POST']) @requires_login def",
"save_status = thread.save(user_id=user_id) return jsonify(new_saves=thread.saves, save_status=save_status, csrf_token=generate_csrf_token()) @mod.route('/comments/vote/', methods=['POST']) @requires_login def vote_comment(): \"\"\""
] |
[
"import Wizard from .data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer,",
"SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import Intrinsics import logging logging.basicConfig(level=logging.INFO) Paths().create()",
"AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from",
"LiveCamera from .paths import Paths from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor",
"from .prediction import Predictor, LiveCamera from .paths import Paths from .prediction.analysis import Grapher",
"from .wizards import Wizard from .data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import",
"from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths",
"from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from",
"Predictor, LiveCamera from .paths import Paths from .prediction.analysis import Grapher from .prediction.synthetic import",
".data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction",
"import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import",
"Paths from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling",
"import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths import Paths",
"from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import Intrinsics import",
"Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import Intrinsics",
"RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths import Paths from .prediction.analysis import",
".wizards import Wizard from .data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer,",
"import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import",
"from .data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from",
"DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera",
"from .paths import Paths from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from",
"DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths import Paths from .prediction.analysis",
".prediction import Predictor, LiveCamera from .paths import Paths from .prediction.analysis import Grapher from",
".simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths import",
"Wizard from .data import Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator",
"Dataset, DatasetInfo, AutomaticAnnotator from .simulation import Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor,",
"Renderer, DatasetRenderer, RobotLookupCreator from .prediction import Predictor, LiveCamera from .paths import Paths from",
".paths import Paths from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration",
"import Predictor, LiveCamera from .paths import Paths from .prediction.analysis import Grapher from .prediction.synthetic",
".prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection",
".prediction.synthetic import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import Intrinsics import logging",
"import Paths from .prediction.analysis import Grapher from .prediction.synthetic import SyntheticPredictor from .textfile_integration import",
"import SyntheticPredictor from .textfile_integration import JSONCoupling from .projection import Intrinsics import logging logging.basicConfig(level=logging.INFO)"
] |
[] |
[
"l - 2) if lis[i] == first and lis[i + 1] == second]",
"in range(0, l - 2) if lis[i] == first and lis[i + 1]",
"second: str) -> List[str]: lis = text.split() l = len(lis) return [lis[i +",
"<reponame>Nightwish-cn/my_leetcode<filename>code/1078.py class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]:",
"str, first: str, second: str) -> List[str]: lis = text.split() l = len(lis)",
"text: str, first: str, second: str) -> List[str]: lis = text.split() l =",
"= len(lis) return [lis[i + 2] for i in range(0, l - 2)",
"text.split() l = len(lis) return [lis[i + 2] for i in range(0, l",
"l = len(lis) return [lis[i + 2] for i in range(0, l -",
"+ 2] for i in range(0, l - 2) if lis[i] == first",
"i in range(0, l - 2) if lis[i] == first and lis[i +",
"first: str, second: str) -> List[str]: lis = text.split() l = len(lis) return",
"for i in range(0, l - 2) if lis[i] == first and lis[i",
"str) -> List[str]: lis = text.split() l = len(lis) return [lis[i + 2]",
"Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: lis =",
"-> List[str]: lis = text.split() l = len(lis) return [lis[i + 2] for",
"List[str]: lis = text.split() l = len(lis) return [lis[i + 2] for i",
"[lis[i + 2] for i in range(0, l - 2) if lis[i] ==",
"findOcurrences(self, text: str, first: str, second: str) -> List[str]: lis = text.split() l",
"return [lis[i + 2] for i in range(0, l - 2) if lis[i]",
"2] for i in range(0, l - 2) if lis[i] == first and",
"= text.split() l = len(lis) return [lis[i + 2] for i in range(0,",
"lis = text.split() l = len(lis) return [lis[i + 2] for i in",
"str, second: str) -> List[str]: lis = text.split() l = len(lis) return [lis[i",
"def findOcurrences(self, text: str, first: str, second: str) -> List[str]: lis = text.split()",
"len(lis) return [lis[i + 2] for i in range(0, l - 2) if",
"class Solution: def findOcurrences(self, text: str, first: str, second: str) -> List[str]: lis",
"range(0, l - 2) if lis[i] == first and lis[i + 1] =="
] |
[
"to radians/yr\"\"\" radyr = omega * (np.pi / 180) * 1e-6; return radyr;",
"1000; # mm/yr in x, y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1];",
"the equator with positive to the north. :param lon: Longitude of initial point,",
":param lat: Latitude of initial point, in degrees :type lat: float :returns: [X,",
"A more complex function xyz2enu(X, Y, Z, lon, lat) could be written later.",
"return [e, n]; if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; #",
"Y, Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x =",
"a point on earth's surface in XYZ coordinates. The XYZ coordinate system has",
"R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X * X -",
"and north, assuming spherical earth and no vertical motion. We take the dot",
"= omega * (np.pi / 180) * 1e-6; return radyr; def get_r(lon, lat):",
"in one reference frame with respect to another reference frame. The resulting velocity",
"(np.pi / 180) * 1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector from",
"< 0: n = n * -1; return [e, n]; if __name__ ==",
"earth. This function is useful for computing the velocity of a stationary point",
"a stationary point in one reference frame with respect to another reference frame.",
"= fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in radians",
":type lon: float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector = [x,",
"assuming spherical earth and no vertical motion. We take the dot product of",
"Y, Z, lon, lat) could be written later. :param x: x velocity at",
"take the dot product of the velocity with the unit east vector and",
"meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk *",
"of a stationary point in one reference frame with respect to another reference",
"total = np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f east, %.2f north,",
"function is useful for computing the velocity of a stationary point in one",
"float, float] \"\"\" R_fixed = 6378000; # In meters R_equatorial_disk = R_fixed *",
"np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of",
"the north. The return value of Z is zero for eastward motion. :param",
"is useful for computing the velocity of a stationary point in one reference",
"0]; def xyz2en(x, y, z, lon): \"\"\" Convert velocities from xyz to horizontal",
"at the equator with positive to the north. :param lon: Longitude of initial",
"to be horizontal. :param Point: [longitude, latitude] of observation point, in degrees :type",
"z velocity at observation point :type z: float :param lon: Longitude of observation",
"= xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; # by definition the velocity",
"degrees :type lon: float :returns: [X, Y, Z] components :rtype: [float, float, float]",
"Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point = [-124, 40.5];",
"degrees :type Point: array_like :param Euler_Pole: [longitude, latitude, omega] of Euler Pole, in",
"north_vel] :rtype: [float, float] \"\"\" vel_vector = [x, y, z]; unit_east = get_unit_east(lon);",
"* east_transform + north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f",
"if lat < 0: Z = Z * -1; return [X, Y, Z];",
"Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform",
"= 0; # by definition the velocity will be horizontal return [east_transform, north_transform,",
"* np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk",
"float :returns: [X, Y, Z] coordinates in meters. :rtype: [float, float, float] \"\"\"",
"[e, n]; if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon,",
"earth and no vertical motion. We take the dot product of the velocity",
":returns: [e_velocity, n_velocity, u_velocity] of point in rotated reference frame, in mm/yr :rtype:",
"pole rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in x, y, z",
"lon: float :param lat: Latitude of initial point, in degrees :type lat: float",
"east, %.2f north, %.2f up, %.2f mm/yr total\" % (east_transform, north_transform, up_transform, total));",
"horizontal. :param Point: [longitude, latitude] of observation point, in degrees :type Point: array_like",
"per year velocity_of_transformation = np.cross(omega, R_point); # velocity at the station from the",
"Euler_Pole): \"\"\" Compute the velocity of rotation of a point about an Euler",
"zero for eastward motion. :param lon: Longitude of initial point, in degrees :type",
"R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw",
"= np.dot(vel_vector, unit_east); n = np.sqrt(x * x + y * y +",
"def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi",
"a point by a known euler pole. \"\"\" import numpy as np from",
"velocity at observation point :type x: float :param y: y velocity at observation",
"lat) could be written later. :param x: x velocity at observation point :type",
"velocity at observation point :type y: float :param z: z velocity at observation",
"x=0 at longitude=0 and z=0 at the equator with positive to the north.",
"Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f east, %.2f",
"east_transform + north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr",
"assuming a spherical earth. The XYZ coordinate system has x=0 at longitude=0 and",
"spherical earth. This function is useful for computing the velocity of a stationary",
"with positive to the north. :param lon: Longitude of initial point, in degrees",
"up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform * north_transform);",
"[X, Y, Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x",
"known euler pole. \"\"\" import numpy as np from . import fault_vector_functions def",
"\"\"\" Functions to rotate a point by a known euler pole. \"\"\" import",
"at observation point :type y: float :param z: z velocity at observation point",
"observation point :type z: float :param lon: Longitude of observation point, in degrees",
"about an Euler pole on a spherical earth. This function is useful for",
"float] \"\"\" vel_vector = [x, y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector,",
"east and north, assuming spherical earth and no vertical motion. We take the",
"the euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in x,",
"motion. :param lon: Longitude of initial point, in degrees :type lon: float :returns:",
"In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk",
":param lon: Longitude of observation point, in degrees :type lon: float :returns: [east_vel,",
"[east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector = [x, y, z]; unit_east =",
"lat: float :returns: [X, Y, Z] coordinates in meters. :rtype: [float, float, float]",
"np.sqrt(x * x + y * y + z * z - e",
"zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0;",
"north, assuming spherical earth and no vertical motion. We take the dot product",
"written later. :param x: x velocity at observation point :type x: float :param",
"Longitude of initial point, in degrees :type lon: float :param lat: Latitude of",
"y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform]",
"stationary point in one reference frame with respect to another reference frame. The",
"frame, in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0],",
"the unit east vector and the north component is the remainder. A more",
"Z]; def get_unit_east(lon): \"\"\" Unit east vector from a point on earth's surface",
"radyr = omega * (np.pi / 180) * 1e-6; return radyr; def get_r(lon,",
"degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point in",
"= point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f",
"dot product of the velocity with the unit east vector and the north",
"earth to the point in question assuming a spherical earth. The XYZ coordinate",
"Z = np.sqrt(R_fixed * R_fixed - X * X - Y * Y);",
"and z=0 at the equator with positive to the north. :param lon: Longitude",
"lat): \"\"\" Vector from center of earth to the point in question assuming",
"np.sqrt(R_fixed * R_fixed - X * X - Y * Y); if lat",
"the velocity with the unit east vector and the north component is the",
":param Euler_Pole: [longitude, latitude, omega] of Euler Pole, in degrees and degrees/Ma :type",
"Unit east vector from a point on earth's surface in XYZ coordinates. The",
":type lat: float :returns: [X, Y, Z] coordinates in meters. :rtype: [float, float,",
"the remainder. A more complex function xyz2enu(X, Y, Z, lon, lat) could be",
"\"\"\" Compute the velocity of rotation of a point about an Euler pole",
"* 1000; # mm/yr in x, y, z xvel = velocity_of_transformation[0]; yvel =",
"* y + z * z - e * e); if z <",
"point about an Euler pole on a spherical earth. This function is useful",
"euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in x, y,",
"# by definition the velocity will be horizontal return [east_transform, north_transform, up_transform]; def",
"horizontal east and north, assuming spherical earth and no vertical motion. We take",
"Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega =",
"point :type y: float :param z: z velocity at observation point :type z:",
"[east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr =",
"point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation of a point about an",
"at longitude=0 and z=0 at the equator with positive to the north. The",
"array_like :param Euler_Pole: [longitude, latitude, omega] of Euler Pole, in degrees and degrees/Ma",
"- e * e); if z < 0: n = n * -1;",
"pole on a spherical earth. This function is useful for computing the velocity",
"frame with respect to another reference frame. The resulting velocity is assumed to",
"[float, float] \"\"\" vel_vector = [x, y, z]; unit_east = get_unit_east(lon); e =",
"+ north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr total\"",
"spherical earth and no vertical motion. We take the dot product of the",
"coordinates. The XYZ coordinate system has x=0 at longitude=0 and z=0 at the",
"north. The return value of Z is zero for eastward motion. :param lon:",
"assumed to be horizontal. :param Point: [longitude, latitude] of observation point, in degrees",
"degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point in rotated reference",
"to rotate a point by a known euler pole. \"\"\" import numpy as",
"# In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X =",
"in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]);",
"Longitude of initial point, in degrees :type lon: float :returns: [X, Y, Z]",
"[e_velocity, n_velocity, u_velocity] of point in rotated reference frame, in mm/yr :rtype: array_like",
"Lat, Deg/Ma Point = [-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform] =",
"velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform =",
"initial point, in degrees :type lat: float :returns: [X, Y, Z] coordinates in",
"velocity_of_transformation * 1000; # mm/yr in x, y, z xvel = velocity_of_transformation[0]; yvel",
"velocity of rotation of a point about an Euler pole on a spherical",
"velocity at the station from the euler pole rotation velocity_of_transformation = velocity_of_transformation *",
":param lon: Longitude of initial point, in degrees :type lon: float :param lat:",
"initial point, in degrees :type lon: float :param lat: Latitude of initial point,",
"lon: Longitude of initial point, in degrees :type lon: float :param lat: Latitude",
"coordinates in meters. :rtype: [float, float, float] \"\"\" R_fixed = 6378000; # In",
"surface in XYZ coordinates. The XYZ coordinate system has x=0 at longitude=0 and",
"velocity_of_transformation = np.cross(omega, R_point); # velocity at the station from the euler pole",
"* X - Y * Y); if lat < 0: Z = Z",
"\"\"\" Unit east vector from a point on earth's surface in XYZ coordinates.",
"180) * 1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector from center of",
"Z is zero for eastward motion. :param lon: Longitude of initial point, in",
"lat: Latitude of initial point, in degrees :type lat: float :returns: [X, Y,",
"= velocity_of_transformation * 1000; # mm/yr in x, y, z xvel = velocity_of_transformation[0];",
"= get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw *",
"lon, lat) could be written later. :param x: x velocity at observation point",
"the velocity of rotation of a point about an Euler pole on a",
"degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in radians per year velocity_of_transformation =",
"y, z, lon): \"\"\" Convert velocities from xyz to horizontal east and north,",
":returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector = [x, y, z]; unit_east",
"be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to",
"degrees :type lon: float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector =",
"y velocity at observation point :type y: float :param z: z velocity at",
"omega_raw * unit_ep; # in radians per year velocity_of_transformation = np.cross(omega, R_point); #",
"y: float :param z: z velocity at observation point :type z: float :param",
"latitude] of observation point, in degrees :type Point: array_like :param Euler_Pole: [longitude, latitude,",
"positive to the north. The return value of Z is zero for eastward",
"Deg/Ma Point = [-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point,",
"Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector from a point on earth's",
"vel_vector = [x, y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n",
"# Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform *",
"and no vertical motion. We take the dot product of the velocity with",
"function xyz2enu(X, Y, Z, lon, lat) could be written later. :param x: x",
"import numpy as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute",
"\"\"\" R_fixed = 6378000; # In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk",
"* -1; return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector from",
"We take the dot product of the velocity with the unit east vector",
"horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\"",
"* x + y * y + z * z - e *",
"np.dot(vel_vector, unit_east); n = np.sqrt(x * x + y * y + z",
"degrees :type lat: float :returns: [X, Y, Z] coordinates in meters. :rtype: [float,",
"point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f east,",
"to another reference frame. The resulting velocity is assumed to be horizontal. :param",
"x + y * y + z * z - e * e);",
"point by a known euler pole. \"\"\" import numpy as np from .",
"Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; #",
"R_fixed = 6378000; # In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk =",
"north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform *",
"x: x velocity at observation point :type x: float :param y: y velocity",
"spherical earth. The XYZ coordinate system has x=0 at longitude=0 and z=0 at",
"complex function xyz2enu(X, Y, Z, lon, lat) could be written later. :param x:",
"= get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x * x + y",
"zvel, Point[0]); up_transform = 0; # by definition the velocity will be horizontal",
"observation point, in degrees :type Point: array_like :param Euler_Pole: [longitude, latitude, omega] of",
"question assuming a spherical earth. The XYZ coordinate system has x=0 at longitude=0",
"computing the velocity of a stationary point in one reference frame with respect",
"xyz to horizontal east and north, assuming spherical earth and no vertical motion.",
"# velocity at the station from the euler pole rotation velocity_of_transformation = velocity_of_transformation",
"and the north component is the remainder. A more complex function xyz2enu(X, Y,",
"\"\"\" import numpy as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\"",
"Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point in rotated reference frame, in",
"Latitude of initial point, in degrees :type lat: float :returns: [X, Y, Z]",
"np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x,",
"in degrees :type Point: array_like :param Euler_Pole: [longitude, latitude, omega] of Euler Pole,",
"Z = Z * -1; return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit",
"east vector from a point on earth's surface in XYZ coordinates. The XYZ",
"Point: [longitude, latitude] of observation point, in degrees :type Point: array_like :param Euler_Pole:",
"u_velocity] of point in rotated reference frame, in mm/yr :rtype: array_like \"\"\" R_point",
"Functions to rotate a point by a known euler pole. \"\"\" import numpy",
"Vector from center of earth to the point in question assuming a spherical",
"the velocity will be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega",
"at longitude=0 and z=0 at the equator with positive to the north. :param",
"-1; return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector from a",
"observation point, in degrees :type lon: float :returns: [east_vel, north_vel] :rtype: [float, float]",
"point, in degrees :type lon: float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\"",
"- Y * Y); if lat < 0: Z = Z * -1;",
"point in one reference frame with respect to another reference frame. The resulting",
"* z - e * e); if z < 0: n = n",
"np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X",
"vector from a point on earth's surface in XYZ coordinates. The XYZ coordinate",
"-1; return [e, n]; if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55];",
"is assumed to be horizontal. :param Point: [longitude, latitude] of observation point, in",
"Point[0]); up_transform = 0; # by definition the velocity will be horizontal return",
":rtype: [float, float, float] \"\"\" R_fixed = 6378000; # In meters R_equatorial_disk =",
"unit_ep; # in radians per year velocity_of_transformation = np.cross(omega, R_point); # velocity at",
"import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation of a",
"xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; # by definition the velocity will",
"\"\"\" Convert velocities from xyz to horizontal east and north, assuming spherical earth",
"vector and the north component is the remainder. A more complex function xyz2enu(X,",
"degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi / 180) * 1e-6; return",
"of observation point, in degrees :type lon: float :returns: [east_vel, north_vel] :rtype: [float,",
":rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep =",
"# in radians per year velocity_of_transformation = np.cross(omega, R_point); # velocity at the",
":type Point: array_like :param Euler_Pole: [longitude, latitude, omega] of Euler Pole, in degrees",
"= np.sqrt(R_fixed * R_fixed - X * X - Y * Y); if",
"0.55]; # Lon, Lat, Deg/Ma Point = [-124, 40.5]; # Lon, Lat [east_transform,",
"\"\"\" Vector from center of earth to the point in question assuming a",
"positive to the north. :param lon: Longitude of initial point, in degrees :type",
"[east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform + north_transform",
"a spherical earth. The XYZ coordinate system has x=0 at longitude=0 and z=0",
"numpy as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the",
"def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation of a point about",
"np.cross(omega, R_point); # velocity at the station from the euler pole rotation velocity_of_transformation",
"[east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; # by definition",
"np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f up,",
"-12.3, 0.55]; # Lon, Lat, Deg/Ma Point = [-124, 40.5]; # Lon, Lat",
"Lon, Lat, Deg/Ma Point = [-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform]",
"fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation of a point",
"z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x * x",
"[x, y, 0]; def xyz2en(x, y, z, lon): \"\"\" Convert velocities from xyz",
":param y: y velocity at observation point :type y: float :param z: z",
"e); if z < 0: n = n * -1; return [e, n];",
"xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel,",
"north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr total\" % (east_transform, north_transform,",
"mm/yr in x, y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel =",
"frame. The resulting velocity is assumed to be horizontal. :param Point: [longitude, latitude]",
"radians/yr\"\"\" radyr = omega * (np.pi / 180) * 1e-6; return radyr; def",
"reference frame with respect to another reference frame. The resulting velocity is assumed",
":type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point in rotated reference frame,",
"be written later. :param x: x velocity at observation point :type x: float",
"z: z velocity at observation point :type z: float :param lon: Longitude of",
"+ y * y + z * z - e * e); if",
"velocity is assumed to be horizontal. :param Point: [longitude, latitude] of observation point,",
"X * X - Y * Y); if lat < 0: Z =",
"an Euler pole on a spherical earth. This function is useful for computing",
"= [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point = [-124, 40.5]; #",
"x: float :param y: y velocity at observation point :type y: float :param",
"pole. \"\"\" import numpy as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole):",
"print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr total\" % (east_transform, north_transform, up_transform,",
"Z] coordinates in meters. :rtype: [float, float, float] \"\"\" R_fixed = 6378000; #",
"R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed",
"float :param y: y velocity at observation point :type y: float :param z:",
"the station from the euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000; #",
"radyr; def get_r(lon, lat): \"\"\" Vector from center of earth to the point",
"of Z is zero for eastward motion. :param lon: Longitude of initial point,",
"velocity with the unit east vector and the north component is the remainder.",
"is the remainder. A more complex function xyz2enu(X, Y, Z, lon, lat) could",
"# Lon, Lat, Deg/Ma Point = [-124, 40.5]; # Lon, Lat [east_transform, north_transform,",
"if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma",
"from degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi / 180) * 1e-6;",
"in degrees :type lat: float :returns: [X, Y, Z] coordinates in meters. :rtype:",
"point :type x: float :param y: y velocity at observation point :type y:",
"omega = omega_raw * unit_ep; # in radians per year velocity_of_transformation = np.cross(omega,",
"from a point on earth's surface in XYZ coordinates. The XYZ coordinate system",
"unit east vector and the north component is the remainder. A more complex",
"Euler Pole, in degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity]",
"yvel, zvel, Point[0]); up_transform = 0; # by definition the velocity will be",
"of a point about an Euler pole on a spherical earth. This function",
"e * e); if z < 0: n = n * -1; return",
"n_velocity, u_velocity] of point in rotated reference frame, in mm/yr :rtype: array_like \"\"\"",
"float] \"\"\" R_fixed = 6378000; # In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat));",
"lon: Longitude of observation point, in degrees :type lon: float :returns: [east_vel, north_vel]",
"and z=0 at the equator with positive to the north. The return value",
"with positive to the north. The return value of Z is zero for",
"array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep);",
"T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk);",
"has x=0 at longitude=0 and z=0 at the equator with positive to the",
"\"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point = [-124,",
"component is the remainder. A more complex function xyz2enu(X, Y, Z, lon, lat)",
"= degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in radians per year velocity_of_transformation",
"from xyz to horizontal east and north, assuming spherical earth and no vertical",
"def xyz2en(x, y, z, lon): \"\"\" Convert velocities from xyz to horizontal east",
"and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point in rotated",
"get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep;",
"* R_fixed - X * X - Y * Y); if lat <",
"* Y); if lat < 0: Z = Z * -1; return [X,",
"north. :param lon: Longitude of initial point, in degrees :type lon: float :param",
"to the north. :param lon: Longitude of initial point, in degrees :type lon:",
"of Euler Pole, in degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity,",
"return [x, y, 0]; def xyz2en(x, y, z, lon): \"\"\" Convert velocities from",
"resulting velocity is assumed to be horizontal. :param Point: [longitude, latitude] of observation",
"in question assuming a spherical earth. The XYZ coordinate system has x=0 at",
"omega from degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi / 180) *",
"of observation point, in degrees :type Point: array_like :param Euler_Pole: [longitude, latitude, omega]",
"n]; if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat,",
"< 0: Z = Z * -1; return [X, Y, Z]; def get_unit_east(lon):",
"z * z - e * e); if z < 0: n =",
"= R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X * X",
"from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation",
"z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] =",
"unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in",
"the point in question assuming a spherical earth. The XYZ coordinate system has",
"= np.cross(omega, R_point); # velocity at the station from the euler pole rotation",
"__name__ == \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point",
"y: y velocity at observation point :type y: float :param z: z velocity",
"\"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw",
"east vector and the north component is the remainder. A more complex function",
"x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y,",
"= np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z",
"rotate a point by a known euler pole. \"\"\" import numpy as np",
"point, in degrees :type lat: float :returns: [X, Y, Z] coordinates in meters.",
"get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega",
"def get_r(lon, lat): \"\"\" Vector from center of earth to the point in",
"Pole, in degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of",
"Euler pole on a spherical earth. This function is useful for computing the",
":type y: float :param z: z velocity at observation point :type z: float",
"be horizontal. :param Point: [longitude, latitude] of observation point, in degrees :type Point:",
"later. :param x: x velocity at observation point :type x: float :param y:",
"y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x *",
"to the point in question assuming a spherical earth. The XYZ coordinate system",
"R_point); # velocity at the station from the euler pole rotation velocity_of_transformation =",
"observation point :type y: float :param z: z velocity at observation point :type",
"lat < 0: Z = Z * -1; return [X, Y, Z]; def",
"6378000; # In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X",
"\"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi / 180)",
"longitude=0 and z=0 at the equator with positive to the north. The return",
"definition the velocity will be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert",
"of point in rotated reference frame, in mm/yr :rtype: array_like \"\"\" R_point =",
"point :type z: float :param lon: Longitude of observation point, in degrees :type",
"omega] of Euler Pole, in degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity,",
"equator with positive to the north. :param lon: Longitude of initial point, in",
"[longitude, latitude] of observation point, in degrees :type Point: array_like :param Euler_Pole: [longitude,",
"to horizontal east and north, assuming spherical earth and no vertical motion. We",
"* 1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector from center of earth",
"-np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y, z, lon):",
"equator with positive to the north. The return value of Z is zero",
"float :returns: [X, Y, Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk =",
"= get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]);",
"unit_east); n = np.sqrt(x * x + y * y + z *",
"point, in degrees :type lon: float :returns: [X, Y, Z] components :rtype: [float,",
":param lon: Longitude of initial point, in degrees :type lon: float :returns: [X,",
"The resulting velocity is assumed to be horizontal. :param Point: [longitude, latitude] of",
"The XYZ coordinate system has x=0 at longitude=0 and z=0 at the equator",
"point, in degrees :type Point: array_like :param Euler_Pole: [longitude, latitude, omega] of Euler",
"remainder. A more complex function xyz2enu(X, Y, Z, lon, lat) could be written",
"Euler_Pole: [longitude, latitude, omega] of Euler Pole, in degrees and degrees/Ma :type Euler_Pole:",
"omega * (np.pi / 180) * 1e-6; return radyr; def get_r(lon, lat): \"\"\"",
"one reference frame with respect to another reference frame. The resulting velocity is",
"\"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y,",
"float :param lat: Latitude of initial point, in degrees :type lat: float :returns:",
"np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z =",
"# mm/yr in x, y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel",
":rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y =",
"velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; # by",
"x velocity at observation point :type x: float :param y: y velocity at",
"with the unit east vector and the north component is the remainder. A",
"to the north. The return value of Z is zero for eastward motion.",
"float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return",
"motion. We take the dot product of the velocity with the unit east",
"velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel,",
"as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity",
"= np.sqrt(east_transform * east_transform + north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f",
"return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr",
"north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr = omega",
"1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector from center of earth to",
"on a spherical earth. This function is useful for computing the velocity of",
"= [-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total",
"no vertical motion. We take the dot product of the velocity with the",
"rotated reference frame, in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep",
"for eastward motion. :param lon: Longitude of initial point, in degrees :type lon:",
"Z, lon, lat) could be written later. :param x: x velocity at observation",
"of rotation of a point about an Euler pole on a spherical earth.",
"np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y, z, lon): \"\"\" Convert velocities",
"useful for computing the velocity of a stationary point in one reference frame",
"0: n = n * -1; return [e, n]; if __name__ == \"__main__\":",
"velocities from xyz to horizontal east and north, assuming spherical earth and no",
"center of earth to the point in question assuming a spherical earth. The",
"= 6378000; # In meters R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon);",
"omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in radians per year",
"* np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed -",
"the north component is the remainder. A more complex function xyz2enu(X, Y, Z,",
"z=0 at the equator with positive to the north. The return value of",
"lon: float :returns: [X, Y, Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk",
"meters. :rtype: [float, float, float] \"\"\" R_fixed = 6378000; # In meters R_equatorial_disk",
":param x: x velocity at observation point :type x: float :param y: y",
"a point about an Euler pole on a spherical earth. This function is",
"Y, Z] coordinates in meters. :rtype: [float, float, float] \"\"\" R_fixed = 6378000;",
"velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in x, y, z xvel =",
"observation point :type x: float :param y: y velocity at observation point :type",
"rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in x, y, z xvel",
"float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector = [x, y, z];",
"Convert velocities from xyz to horizontal east and north, assuming spherical earth and",
"more complex function xyz2enu(X, Y, Z, lon, lat) could be written later. :param",
"array_like :returns: [e_velocity, n_velocity, u_velocity] of point in rotated reference frame, in mm/yr",
"latitude, omega] of Euler Pole, in degrees and degrees/Ma :type Euler_Pole: array_like :returns:",
"R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep = fault_vector_functions.get_unit_vector(R_ep); omega_raw =",
"= velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; #",
"in degrees :type lon: float :returns: [X, Y, Z] components :rtype: [float, float,",
"= -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y, z,",
"[float, float, float] \"\"\" R_fixed = 6378000; # In meters R_equatorial_disk = R_fixed",
"the equator with positive to the north. The return value of Z is",
"* unit_ep; # in radians per year velocity_of_transformation = np.cross(omega, R_point); # velocity",
"point on earth's surface in XYZ coordinates. The XYZ coordinate system has x=0",
"at the station from the euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000;",
"of initial point, in degrees :type lon: float :returns: [X, Y, Z] components",
"xyz2enu(X, Y, Z, lon, lat) could be written later. :param x: x velocity",
"get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x * x + y *",
"components :rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y",
"x, y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform,",
"y + z * z - e * e); if z < 0:",
"- X * X - Y * Y); if lat < 0: Z",
"[69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point = [-124, 40.5]; # Lon,",
"reference frame, in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep =",
"== \"__main__\": Euler_Pole = [69.9, -12.3, 0.55]; # Lon, Lat, Deg/Ma Point =",
"The return value of Z is zero for eastward motion. :param lon: Longitude",
"/ 180) * 1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector from center",
"respect to another reference frame. The resulting velocity is assumed to be horizontal.",
"a known euler pole. \"\"\" import numpy as np from . import fault_vector_functions",
"[longitude, latitude, omega] of Euler Pole, in degrees and degrees/Ma :type Euler_Pole: array_like",
"= omega_raw * unit_ep; # in radians per year velocity_of_transformation = np.cross(omega, R_point);",
"[X, Y, Z] coordinates in meters. :rtype: [float, float, float] \"\"\" R_fixed =",
"[-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total =",
":param z: z velocity at observation point :type z: float :param lon: Longitude",
"initial point, in degrees :type lon: float :returns: [X, Y, Z] components :rtype:",
":type lon: float :returns: [X, Y, Z] components :rtype: [float, float, float] \"\"\"",
"in radians per year velocity_of_transformation = np.cross(omega, R_point); # velocity at the station",
":returns: [X, Y, Z] coordinates in meters. :rtype: [float, float, float] \"\"\" R_fixed",
":param Point: [longitude, latitude] of observation point, in degrees :type Point: array_like :param",
"0; # by definition the velocity will be horizontal return [east_transform, north_transform, up_transform];",
"is zero for eastward motion. :param lon: Longitude of initial point, in degrees",
"in degrees :type lon: float :param lat: Latitude of initial point, in degrees",
"y * y + z * z - e * e); if z",
"in rotated reference frame, in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]);",
":type lon: float :param lat: Latitude of initial point, in degrees :type lat:",
"lon: float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector = [x, y,",
"north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform = 0; # by definition the",
"the velocity of a stationary point in one reference frame with respect to",
"velocity will be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from",
"earth's surface in XYZ coordinates. The XYZ coordinate system has x=0 at longitude=0",
"n = n * -1; return [e, n]; if __name__ == \"__main__\": Euler_Pole",
"Compute the velocity of rotation of a point about an Euler pole on",
"z < 0: n = n * -1; return [e, n]; if __name__",
"X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed",
"n * -1; return [e, n]; if __name__ == \"__main__\": Euler_Pole = [69.9,",
"z - e * e); if z < 0: n = n *",
"product of the velocity with the unit east vector and the north component",
"XYZ coordinates. The XYZ coordinate system has x=0 at longitude=0 and z=0 at",
"velocity of a stationary point in one reference frame with respect to another",
"Y * Y); if lat < 0: Z = Z * -1; return",
"= R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y",
"[X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector from a point on",
"in XYZ coordinates. The XYZ coordinate system has x=0 at longitude=0 and z=0",
"* (np.pi / 180) * 1e-6; return radyr; def get_r(lon, lat): \"\"\" Vector",
"a spherical earth. This function is useful for computing the velocity of a",
"* np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X * X - Y",
"euler pole. \"\"\" import numpy as np from . import fault_vector_functions def point_rotation_by_Euler_Pole(Point,",
"Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk);",
"= np.sqrt(x * x + y * y + z * z -",
"n = np.sqrt(x * x + y * y + z * z",
"fault_vector_functions.get_unit_vector(R_ep); omega_raw = degma2radyr(Euler_Pole[2]); omega = omega_raw * unit_ep; # in radians per",
"at observation point :type z: float :param lon: Longitude of observation point, in",
"= R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed *",
"xyz2en(x, y, z, lon): \"\"\" Convert velocities from xyz to horizontal east and",
"T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0];",
"float :param z: z velocity at observation point :type z: float :param lon:",
"= [x, y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n =",
"Point: array_like :param Euler_Pole: [longitude, latitude, omega] of Euler Pole, in degrees and",
"float :param lon: Longitude of observation point, in degrees :type lon: float :returns:",
"float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x,",
"another reference frame. The resulting velocity is assumed to be horizontal. :param Point:",
"north component is the remainder. A more complex function xyz2enu(X, Y, Z, lon,",
":returns: [X, Y, Z] components :rtype: [float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon);",
"40.5]; # Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform",
"point in rotated reference frame, in mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0],",
"return radyr; def get_r(lon, lat): \"\"\" Vector from center of earth to the",
"[float, float, float] \"\"\" T_equatorial_disk = np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk);",
"longitude=0 and z=0 at the equator with positive to the north. :param lon:",
"* north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr total\" % (east_transform,",
"will be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma",
"Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole); total = np.sqrt(east_transform * east_transform +",
"on earth's surface in XYZ coordinates. The XYZ coordinate system has x=0 at",
"e = np.dot(vel_vector, unit_east); n = np.sqrt(x * x + y * y",
"radians per year velocity_of_transformation = np.cross(omega, R_point); # velocity at the station from",
"z=0 at the equator with positive to the north. :param lon: Longitude of",
"mm/yr :rtype: array_like \"\"\" R_point = get_r(Point[0], Point[1]); R_ep = get_r(Euler_Pole[0], Euler_Pole[1]); unit_ep",
"* e); if z < 0: n = n * -1; return [e,",
"Longitude of observation point, in degrees :type lon: float :returns: [east_vel, north_vel] :rtype:",
"XYZ coordinate system has x=0 at longitude=0 and z=0 at the equator with",
":rtype: [float, float] \"\"\" vel_vector = [x, y, z]; unit_east = get_unit_east(lon); e",
"= np.deg2rad(lon); x = -np.sin(T_equatorial_disk); y = np.cos(T_equatorial_disk); return [x, y, 0]; def",
"Z * -1; return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector",
"lon: Longitude of initial point, in degrees :type lon: float :returns: [X, Y,",
"Y); if lat < 0: Z = Z * -1; return [X, Y,",
"z, lon): \"\"\" Convert velocities from xyz to horizontal east and north, assuming",
"reference frame. The resulting velocity is assumed to be horizontal. :param Point: [longitude,",
"R_equatorial_disk = R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk);",
"\"\"\" vel_vector = [x, y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east);",
"= velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel,",
"return value of Z is zero for eastward motion. :param lon: Longitude of",
":type z: float :param lon: Longitude of observation point, in degrees :type lon:",
"by definition the velocity will be horizontal return [east_transform, north_transform, up_transform]; def degma2radyr(omega):",
"coordinate system has x=0 at longitude=0 and z=0 at the equator with positive",
"y = np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y, z, lon): \"\"\"",
"up_transform]; def degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr = omega *",
"z: float :param lon: Longitude of observation point, in degrees :type lon: float",
"* -1; return [e, n]; if __name__ == \"__main__\": Euler_Pole = [69.9, -12.3,",
"from the euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr in",
"Y = R_equatorial_disk * np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X *",
"in meters. :rtype: [float, float, float] \"\"\" R_fixed = 6378000; # In meters",
". import fault_vector_functions def point_rotation_by_Euler_Pole(Point, Euler_Pole): \"\"\" Compute the velocity of rotation of",
"velocity at observation point :type z: float :param lon: Longitude of observation point,",
"year velocity_of_transformation = np.cross(omega, R_point); # velocity at the station from the euler",
"could be written later. :param x: x velocity at observation point :type x:",
"north_transform * north_transform); print(\"%.2f east, %.2f north, %.2f up, %.2f mm/yr total\" %",
"in degrees :type lon: float :returns: [east_vel, north_vel] :rtype: [float, float] \"\"\" vel_vector",
"point in question assuming a spherical earth. The XYZ coordinate system has x=0",
"unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x * x +",
"value of Z is zero for eastward motion. :param lon: Longitude of initial",
"from center of earth to the point in question assuming a spherical earth.",
"[x, y, z]; unit_east = get_unit_east(lon); e = np.dot(vel_vector, unit_east); n = np.sqrt(x",
"up_transform = 0; # by definition the velocity will be horizontal return [east_transform,",
"lon): \"\"\" Convert velocities from xyz to horizontal east and north, assuming spherical",
"earth. The XYZ coordinate system has x=0 at longitude=0 and z=0 at the",
"the north. :param lon: Longitude of initial point, in degrees :type lon: float",
"at observation point :type x: float :param y: y velocity at observation point",
"in x, y, z xvel = velocity_of_transformation[0]; yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2];",
"yvel = velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]);",
"in degrees and degrees/Ma :type Euler_Pole: array_like :returns: [e_velocity, n_velocity, u_velocity] of point",
"degrees :type lon: float :param lat: Latitude of initial point, in degrees :type",
"for computing the velocity of a stationary point in one reference frame with",
"of the velocity with the unit east vector and the north component is",
"return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east vector from a point",
"of initial point, in degrees :type lon: float :param lat: Latitude of initial",
"+ z * z - e * e); if z < 0: n",
"Point = [-124, 40.5]; # Lon, Lat [east_transform, north_transform, up_transform] = point_rotation_by_Euler_Pole(Point, Euler_Pole);",
"rotation of a point about an Euler pole on a spherical earth. This",
"R_fixed - X * X - Y * Y); if lat < 0:",
"the dot product of the velocity with the unit east vector and the",
"get_unit_east(lon): \"\"\" Unit east vector from a point on earth's surface in XYZ",
"get_r(lon, lat): \"\"\" Vector from center of earth to the point in question",
"np.sin(T_equatorial_disk); Z = np.sqrt(R_fixed * R_fixed - X * X - Y *",
"R_fixed * np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y =",
"at the equator with positive to the north. The return value of Z",
"= n * -1; return [e, n]; if __name__ == \"__main__\": Euler_Pole =",
"vertical motion. We take the dot product of the velocity with the unit",
"by a known euler pole. \"\"\" import numpy as np from . import",
"This function is useful for computing the velocity of a stationary point in",
"= Z * -1; return [X, Y, Z]; def get_unit_east(lon): \"\"\" Unit east",
"np.cos(np.deg2rad(lat)); T_equatorial_disk = np.deg2rad(lon); X = R_equatorial_disk * np.cos(T_equatorial_disk); Y = R_equatorial_disk *",
"of initial point, in degrees :type lat: float :returns: [X, Y, Z] coordinates",
"= velocity_of_transformation[1]; zvel = velocity_of_transformation[2]; [east_transform, north_transform] = xyz2en(xvel, yvel, zvel, Point[0]); up_transform",
"eastward motion. :param lon: Longitude of initial point, in degrees :type lon: float",
"station from the euler pole rotation velocity_of_transformation = velocity_of_transformation * 1000; # mm/yr",
"= np.cos(T_equatorial_disk); return [x, y, 0]; def xyz2en(x, y, z, lon): \"\"\" Convert",
"0: Z = Z * -1; return [X, Y, Z]; def get_unit_east(lon): \"\"\"",
"X - Y * Y); if lat < 0: Z = Z *",
"def get_unit_east(lon): \"\"\" Unit east vector from a point on earth's surface in",
":type x: float :param y: y velocity at observation point :type y: float",
"of earth to the point in question assuming a spherical earth. The XYZ",
"y, 0]; def xyz2en(x, y, z, lon): \"\"\" Convert velocities from xyz to",
"point, in degrees :type lon: float :param lat: Latitude of initial point, in",
"if z < 0: n = n * -1; return [e, n]; if",
"degma2radyr(omega): \"\"\"Convert omega from degrees/Ma to radians/yr\"\"\" radyr = omega * (np.pi /",
"with respect to another reference frame. The resulting velocity is assumed to be",
"system has x=0 at longitude=0 and z=0 at the equator with positive to"
] |
[
"# unique list of words in list 2 list_2_words = ' '.join([i for",
"= ' '.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though",
"Variables base_list = 'List_1' # this is the base list, each item in",
"row in df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count = (df_0.list_2 ==",
"df['Exact Matches'] = '' df['Words Matched'] = '' # unique list of words",
"the other list_2 = 'List_2' # List_2 is the name of the list",
"in df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count = (df_0.list_2 == current_key).sum()",
"columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create new df",
"# Importing Libs import pandas as pd import numpy as np # Smart",
"list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create new df df['base_list'] = df_0['base_list']",
"# create new columns df['Exact Matches'] = '' df['Words Matched'] = '' #",
"list in the excel file xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas",
"in list_2_words: row['Words Matched'] = row['Words Matched'] + '|' + item # Dump",
"df df['base_list'] = df_0['base_list'] # create new columns df['Exact Matches'] = '' df['Words",
"count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ') for",
"row['Exact Matches']= count current_key_list = current_key.split(' ') for item in current_key_list: if item",
"= df_0['base_list'] # create new columns df['Exact Matches'] = '' df['Words Matched'] =",
"keys for index, row in df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count",
"of the list in the excel file xlfile = 'DATA_IN.xlsx' # Importing Libs",
"= 'List_2' # List_2 is the name of the list in the excel",
"import numpy as np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns",
"= '' df['Words Matched'] = '' # unique list of words in list",
"pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] # create new columns df['Exact Matches']",
"index, row in df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count = (df_0.list_2",
"the base list, each item in this list is checked for a match",
"current_key.split(' ') for item in current_key_list: if item in list_2_words: row['Words Matched'] =",
"Matched'] = row['Words Matched'] + '|' + item # Dump Excel Sheet df.to_excel('DATA_OUT.xlsx')",
"item in this list is checked for a match in the other list_2",
"'' # unique list of words in list 2 list_2_words = ' '.join([i",
"= row['base_list'] current_key = str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count",
"list of words in list 2 list_2_words = ' '.join([i for i in",
", inplace=True) df = pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] # create",
"str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ')",
"= pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] # create new columns df['Exact",
"of words in list 2 list_2_words = ' '.join([i for i in df_0['list_2']]).split()",
"= pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df =",
"for a match in the other list_2 = 'List_2' # List_2 is the",
"list_2_words: row['Words Matched'] = row['Words Matched'] + '|' + item # Dump Excel",
"\"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create new df df['base_list'] =",
"in current_key_list: if item in list_2_words: row['Words Matched'] = row['Words Matched'] + '|'",
"numpy as np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list:",
"') for item in current_key_list: if item in list_2_words: row['Words Matched'] = row['Words",
"dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create",
"# Variables base_list = 'List_1' # this is the base list, each item",
"in the other list_2 = 'List_2' # List_2 is the name of the",
"list_2 = 'List_2' # List_2 is the name of the list in the",
"list is checked for a match in the other list_2 = 'List_2' #",
"current_key = row['base_list'] current_key = str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']=",
"pandas as pd import numpy as np # Smart Stuff df_0 = pd.read_excel(xlfile,",
"List_2 is the name of the list in the excel file xlfile =",
"the name of the list in the excel file xlfile = 'DATA_IN.xlsx' #",
"create new columns df['Exact Matches'] = '' df['Words Matched'] = '' # unique",
"\"list_2\"} , inplace=True) df = pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] #",
"loop though keys for index, row in df.iterrows(): current_key = row['base_list'] current_key =",
"'List_2' # List_2 is the name of the list in the excel file",
"for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for index,",
"np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2:",
"unique list of words in list 2 list_2_words = ' '.join([i for i",
"list, each item in this list is checked for a match in the",
"match in the other list_2 = 'List_2' # List_2 is the name of",
"import pandas as pd import numpy as np # Smart Stuff df_0 =",
"df_0['base_list'] # create new columns df['Exact Matches'] = '' df['Words Matched'] = ''",
"xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas as pd import numpy as",
"Matches']= count current_key_list = current_key.split(' ') for item in current_key_list: if item in",
"as pd import numpy as np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str)",
"this is the base list, each item in this list is checked for",
"this list is checked for a match in the other list_2 = 'List_2'",
"Libs import pandas as pd import numpy as np # Smart Stuff df_0",
"if item in list_2_words: row['Words Matched'] = row['Words Matched'] + '|' + item",
"'DATA_IN.xlsx' # Importing Libs import pandas as pd import numpy as np #",
"row['Words Matched'] = row['Words Matched'] + '|' + item # Dump Excel Sheet",
"i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for index, row",
"pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame()",
"#rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create new",
"'List_1' # this is the base list, each item in this list is",
"each item in this list is checked for a match in the other",
"df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df",
"checked for a match in the other list_2 = 'List_2' # List_2 is",
"# Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"}",
"= (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ') for item",
"is the base list, each item in this list is checked for a",
"current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ') for item in current_key_list: if",
"in the excel file xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas as",
"current_key_list: if item in list_2_words: row['Words Matched'] = row['Words Matched'] + '|' +",
"base_list = 'List_1' # this is the base list, each item in this",
"inplace=True) df = pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] # create new",
"the list in the excel file xlfile = 'DATA_IN.xlsx' # Importing Libs import",
"the excel file xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas as pd",
"item in current_key_list: if item in list_2_words: row['Words Matched'] = row['Words Matched'] +",
"df = pd.DataFrame() #create new df df['base_list'] = df_0['base_list'] # create new columns",
"in list 2 list_2_words = ' '.join([i for i in df_0['list_2']]).split() list_2_words =",
"df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True) df = pd.DataFrame() #create new df df['base_list']",
"base list, each item in this list is checked for a match in",
"count current_key_list = current_key.split(' ') for item in current_key_list: if item in list_2_words:",
"words in list 2 list_2_words = ' '.join([i for i in df_0['list_2']]).split() list_2_words",
"(df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ') for item in",
"item in list_2_words: row['Words Matched'] = row['Words Matched'] + '|' + item #",
"# this is the base list, each item in this list is checked",
"for item in current_key_list: if item in list_2_words: row['Words Matched'] = row['Words Matched']",
"current_key_list = current_key.split(' ') for item in current_key_list: if item in list_2_words: row['Words",
"= 'List_1' # this is the base list, each item in this list",
"new columns df['Exact Matches'] = '' df['Words Matched'] = '' # unique list",
"columns df['Exact Matches'] = '' df['Words Matched'] = '' # unique list of",
"== current_key).sum() row['Exact Matches']= count current_key_list = current_key.split(' ') for item in current_key_list:",
"Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} ,",
"row['base_list'] current_key = str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list",
"is checked for a match in the other list_2 = 'List_2' # List_2",
"is the name of the list in the excel file xlfile = 'DATA_IN.xlsx'",
"other list_2 = 'List_2' # List_2 is the name of the list in",
"df['Words Matched'] = '' # unique list of words in list 2 list_2_words",
"new df df['base_list'] = df_0['base_list'] # create new columns df['Exact Matches'] = ''",
"list_2_words = ' '.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop",
"Matches'] = '' df['Words Matched'] = '' # unique list of words in",
"a match in the other list_2 = 'List_2' # List_2 is the name",
"= list(dict.fromkeys(list_2_words)) # loop though keys for index, row in df.iterrows(): current_key =",
"= str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list = current_key.split('",
"Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\", list_2: \"list_2\"} , inplace=True)",
"df['base_list'] = df_0['base_list'] # create new columns df['Exact Matches'] = '' df['Words Matched']",
"list(dict.fromkeys(list_2_words)) # loop though keys for index, row in df.iterrows(): current_key = row['base_list']",
"in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for index, row in",
"df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact",
"2 list_2_words = ' '.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) #",
"= current_key.split(' ') for item in current_key_list: if item in list_2_words: row['Words Matched']",
"pd import numpy as np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename",
"current_key = str(current_key) count = (df_0.list_2 == current_key).sum() row['Exact Matches']= count current_key_list =",
"= '' # unique list of words in list 2 list_2_words = '",
"list 2 list_2_words = ' '.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words))",
"file xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas as pd import numpy",
"Importing Libs import pandas as pd import numpy as np # Smart Stuff",
"for index, row in df.iterrows(): current_key = row['base_list'] current_key = str(current_key) count =",
"in this list is checked for a match in the other list_2 =",
"= 'DATA_IN.xlsx' # Importing Libs import pandas as pd import numpy as np",
"#create new df df['base_list'] = df_0['base_list'] # create new columns df['Exact Matches'] =",
"' '.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys",
"name of the list in the excel file xlfile = 'DATA_IN.xlsx' # Importing",
"list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for index, row in df.iterrows(): current_key",
"# loop though keys for index, row in df.iterrows(): current_key = row['base_list'] current_key",
"'' df['Words Matched'] = '' # unique list of words in list 2",
"df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for index, row in df.iterrows():",
"excel file xlfile = 'DATA_IN.xlsx' # Importing Libs import pandas as pd import",
"'.join([i for i in df_0['list_2']]).split() list_2_words = list(dict.fromkeys(list_2_words)) # loop though keys for",
"though keys for index, row in df.iterrows(): current_key = row['base_list'] current_key = str(current_key)",
"as np # Smart Stuff df_0 = pd.read_excel(xlfile, dtype=str) #rename columns df_0.rename(columns={base_list: \"base_list\",",
"Matched'] = '' # unique list of words in list 2 list_2_words =",
"# List_2 is the name of the list in the excel file xlfile"
] |
[
"\"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits",
"original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits =",
"individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits = [50, 100]",
"fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100",
"import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the unit square",
"MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits = [50, 100] col_limits = [2,",
"return dataframe size = 100 row_limits = [50, 100] col_limits = [2, 2]",
"square for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe",
"2] max_iter = 100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0,",
"100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions =",
"import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe",
"def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the unit square for calculating",
"col_limits = [2, 2] max_iter = 100 best_prop = 0.1 mutation_prob = 0.01",
"the experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual):",
"the individual's dataframe to the unit square for calculating fitness. \"\"\" original =",
"[2, 2] max_iter = 100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] =",
"\"\"\" Common functions and parameters amongst the experiments. \"\"\" from edo.distributions import Uniform",
"max_iter = 100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1]",
"Common functions and parameters amongst the experiments. \"\"\" from edo.distributions import Uniform from",
"from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the",
"edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's",
"= [50, 100] col_limits = [2, 2] max_iter = 100 best_prop = 0.1",
"0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions = [Uniform] root =",
"Scale the individual's dataframe to the unit square for calculating fitness. \"\"\" original",
"= [2, 2] max_iter = 100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"]",
"the unit square for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original)",
"amongst the experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def",
"dataframe size = 100 row_limits = [50, 100] col_limits = [2, 2] max_iter",
"sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the unit",
"100 row_limits = [50, 100] col_limits = [2, 2] max_iter = 100 best_prop",
"calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size =",
"for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size",
"mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions = [Uniform] root = \"../data/\"",
"\"\"\" from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale",
"= MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits = [50, 100] col_limits =",
"best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions = [Uniform]",
"[50, 100] col_limits = [2, 2] max_iter = 100 best_prop = 0.1 mutation_prob",
"\"\"\" Scale the individual's dataframe to the unit square for calculating fitness. \"\"\"",
"row_limits = [50, 100] col_limits = [2, 2] max_iter = 100 best_prop =",
"to the unit square for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe =",
"functions and parameters amongst the experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing",
"MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the unit square for",
"individual's dataframe to the unit square for calculating fitness. \"\"\" original = individual.dataframe.copy()",
"unit square for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return",
"size = 100 row_limits = [50, 100] col_limits = [2, 2] max_iter =",
"= 100 row_limits = [50, 100] col_limits = [2, 2] max_iter = 100",
"scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the unit square for calculating fitness.",
"= individual.dataframe.copy() dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits = [50,",
"from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to the",
"parameters amongst the experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler",
"Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\" Scale the individual's dataframe to",
"dataframe = MinMaxScaler().fit_transform(original) return dataframe size = 100 row_limits = [50, 100] col_limits",
"experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing import MinMaxScaler def scale_dataframe(individual): \"\"\"",
"100] col_limits = [2, 2] max_iter = 100 best_prop = 0.1 mutation_prob =",
"= 100 best_prop = 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions",
"= 0.1 mutation_prob = 0.01 Uniform.param_limits[\"bounds\"] = [0, 1] distributions = [Uniform] root",
"and parameters amongst the experiments. \"\"\" from edo.distributions import Uniform from sklearn.preprocessing import",
"dataframe to the unit square for calculating fitness. \"\"\" original = individual.dataframe.copy() dataframe"
] |
[
"InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using the current date and time.",
"l2amin(l): a = 1. / l a = a * 180.* 60. /",
"def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi =",
"np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5,",
"if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog,",
"arc minutes # SKI_SURFACE IN SQUARE DEGREES = 4. * !PI * (360.",
"def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T ' if opt is not",
"is not None: optParam = ' -n ' + str(nside) + optParam p",
"hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin crashes. def eb2g(ke,kb):",
"np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def",
"is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return",
"import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def make_healpix_map(ra, dec,",
"optParam = ' -T ' + opt if nside is not None: optParam",
"importlib import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def make_healpix_map(ra,",
"if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam,",
"\" \" + file_fits + \" \" + file_out if verbose: print ('CMD",
"file_name = path + 'mr_temp_' + unique_string file_fits = file_name + '.fits' if",
"in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' #",
"np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels,",
"= gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2) =",
"file_name + '.fits' if FileOut is not None: file_out = FileOut else: file_out",
"mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam",
"from scipy import ndimage import healpy as hp from astropy.io import fits import",
"' + opt if lmax is not None: optParam = ' -l '",
"not None: optParam = ' -n ' + str(nside) + optParam p =",
"from importlib import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def",
"arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno'",
"np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec),",
"+ optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog,",
"* 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems that",
"pol=False) return ke def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab",
"/ l a = a * 180.* 60. / np.pi return a def",
"pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside): pixels=",
"if verbose: optF = optF + \" -v \" cmd = cmd +",
"def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map,",
"pixel size of a healpix map in arc minutes # SKI_SURFACE IN SQUARE",
"sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut)",
"= prog if isinstance(opt, type(None)): optF=' ' else: optF= opt if verbose: optF",
"args) call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else:",
"k # smoothing with sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.)",
"is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b",
"prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def",
"a = a * 180.* 60. / np.pi return a def amin2l(a): ar",
"title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return",
"def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p",
"' + opt if nside is not None: optParam = ' -n '",
"= mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None,",
"mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd = prog if",
"(ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside",
"/ (180.* 60.) * np.pi l = 1. / ar return l def",
"mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin",
"= data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside): # Return the pixel",
"nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab,",
"= gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke def",
"return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return nside def",
"None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def",
"= gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb,",
"= mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam",
"pixel_size(nside): # Return the pixel size of a healpix map in arc minutes",
"return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k # smoothing",
"hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin,",
"get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return nside",
"optF = optF + \" -v \" cmd = cmd + \" \"",
"result=0 # Set the ouput file names. file_name = path + 'mr_temp_' +",
"a healpix map in arc minutes # SKI_SURFACE IN SQUARE DEGREES = 4.",
"+ file_fits + \" \" + file_out if verbose: print ('CMD = ',",
"as plt from scipy.signal import savgol_filter from astropy.io import fits from importlib import",
"', args) call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out)",
"mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None,",
"= hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin,",
"input data to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data)",
"dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount =",
"np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside):",
"1 ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) =",
"result = readfits(file_out) # Return the mr_transform results (and the output file names).",
"dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount",
"minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount,",
"np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside),",
"= 41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l):",
"60. / np.pi return a def amin2l(a): ar = a / (180.* 60.)",
"def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a",
"import * from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta",
"healpix map in arc minutes # SKI_SURFACE IN SQUARE DEGREES = 4. *",
"= 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside))",
"prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\",",
"4. * !PI * (360. / (2*!PI))^2 = 41253 psize = 41253. /",
"not None: optParam = ' -l ' + str(lmax) + optParam if progpath",
"= hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside =",
"def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T ' if opt is",
"' -T ' if opt is not None: optParam = ' -T '",
"g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create",
"fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \", prog)",
"prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True,path=path) return p",
"hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke,",
"optF= opt if verbose: optF = optF + \" -v \" cmd =",
"= hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2",
"gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke):",
"opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T '",
"is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose, opt=optParam,",
"hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data):",
"ar = a / (180.* 60.) * np.pi l = 1. / ar",
"+ str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return",
"'_out.fits' # Write the input data to a fits file. if InputFormatisHealpix: mrs_write(file_fits,",
"def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout):",
"+ \" -v \" cmd = cmd + \" \" + optF +",
"0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted",
"Write the input data to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else:",
"+ opt if nside is not None: optParam = ' -n ' +",
"p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns=",
"file_name + '_out.fits' # Write the input data to a fits file. if",
"# lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut)",
"gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b =",
"return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if",
"eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False) ab",
"data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside): # Return the pixel size",
"else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd = prog if isinstance(opt, type(None)):",
"-T ' + opt if lmax is not None: optParam = ' -l",
"nside is not None: optParam = ' -n ' + str(nside) + optParam",
"weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount =",
"fits import matplotlib.pyplot as plt from scipy.signal import savgol_filter from astropy.io import fits",
"hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside,",
"file names. file_name = path + 'mr_temp_' + unique_string file_fits = file_name +",
"opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is not None: optParam",
"+ str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p =",
"from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi",
"= np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN,",
"datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names. file_name = path + 'mr_temp_'",
"def pixel_size(nside): # Return the pixel size of a healpix map in arc",
"opt is not None: optParam = ' ' + opt if lmax is",
"' -T ' + opt if lmax is not None: optParam = '",
"= ' -T ' if opt is not None: optParam = ' -T",
"pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke=",
"opt is not None: optParam = ' -T ' + opt if nside",
"scipy import ndimage import healpy as hp from astropy.io import fits import matplotlib.pyplot",
"optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False):",
"random import os, sys from scipy import ndimage import healpy as hp from",
"sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None):",
"b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt",
"plt from scipy.signal import savgol_filter from astropy.io import fits from importlib import reload",
"def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern'",
"using the current date and time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S')",
"FileOut else: file_out = file_name + '_out.fits' # Write the input data to",
"= mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam =",
"', cmd) args = shlex.split(cmd) # print('args ', args) call(args) # Retrieve wavelet",
"hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke,",
"a unique string using the current date and time. # print('mr_filter ', opt)",
"from astropy.io import fits from importlib import reload from pycs.misc.cosmostat_init import * from",
"bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi",
"make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra))",
"InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd = prog",
"'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin,",
"if lmax is not None: optParam = ' -l ' + str(lmax) +",
"remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using the current",
"s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if",
"= hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta",
"np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin):",
"# SKI_SURFACE IN SQUARE DEGREES = 4. * !PI * (360. / (2*!PI))^2",
"- 1 ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2)",
"verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin",
"hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def",
"hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside):",
"verbose: print ('CMD = ', cmd) args = shlex.split(cmd) # print('args ', args)",
"def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k # smoothing with sigma",
"mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map,",
"= ' -l ' + str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose,",
"hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True,",
"= 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a = 1.",
"* def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi",
"nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1)",
"-T ' if opt is not None: optParam = ' -T ' +",
"'.fits' if FileOut is not None: file_out = FileOut else: file_out = file_name",
"opt if lmax is not None: optParam = ' -l ' + str(lmax)",
"prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True,path=path)",
"SQUARE DEGREES = 4. * !PI * (360. / (2*!PI))^2 = 41253 psize",
"else: file_out = file_name + '_out.fits' # Write the input data to a",
"= a * 180.* 60. / np.pi return a def amin2l(a): ar =",
"+ optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p =",
"# smoothing with sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) *",
"mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = '",
"optParam = ' -T ' + opt if lmax is not None: optParam",
"\" + file_out if verbose: print ('CMD = ', cmd) args = shlex.split(cmd)",
"/ (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a = 1. / l",
"lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False)",
"print(\"PROG: \", prog) cmd = prog if isinstance(opt, type(None)): optF=' ' else: optF=",
"not None: file_out = FileOut else: file_out = file_name + '_out.fits' # Write",
"OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin)",
"Retrieve wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out)",
"file names). if remove_files: remove(file_fits) remove(file_out) return result else: return result def mrs_powspec(map,",
"None: file_out = FileOut else: file_out = file_name + '_out.fits' # Write the",
"(and the output file names). if remove_files: remove(file_fits) remove(file_out) return result else: return",
"if FileOut is not None: file_out = FileOut else: file_out = file_name +",
"optParam = ' -n ' + str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\",",
"is not None: optParam = ' -T ' + opt if nside is",
"optParam = ' ' + opt if lmax is not None: optParam =",
"* (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix =",
"optF + \" \" + file_fits + \" \" + file_out if verbose:",
"opt if nside is not None: optParam = ' -n ' + str(nside)",
"' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p",
"verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam =",
"mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def",
"p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None,",
"/ (2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize)",
"progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path)",
"prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam =",
"import fits import matplotlib.pyplot as plt from scipy.signal import savgol_filter from astropy.io import",
"prog if isinstance(opt, type(None)): optF=' ' else: optF= opt if verbose: optF =",
"ar return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke=",
"' if opt is not None: optParam = ' -T ' + opt",
"+ optF + \" \" + file_fits + \" \" + file_out if",
"60.**2. return np.sqrt(psize) def l2amin(l): a = 1. / l a = a",
"def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra))",
"hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def",
"seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae",
"lmax=None, opt=None, verbose=False): optParam = ' -T ' if opt is not None:",
"+ optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map,",
"mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False,",
"optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap,",
"file_out = FileOut else: file_out = file_name + '_out.fits' # Write the input",
"nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke",
"file_out = file_name + '_out.fits' # Write the input data to a fits",
"cmd + \" \" + optF + \" \" + file_fits + \"",
"def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False)",
"41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a = 1. /",
"hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return",
"result = mrs_read(file_out) else: result = readfits(file_out) # Return the mr_transform results (and",
"lmax=lmax) b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None):",
"np import random import os, sys from scipy import ndimage import healpy as",
"a def amin2l(a): ar = a / (180.* 60.) * np.pi l =",
"of a healpix map in arc minutes # SKI_SURFACE IN SQUARE DEGREES =",
"optF + \" -v \" cmd = cmd + \" \" + optF",
"IN SQUARE DEGREES = 4. * !PI * (360. / (2*!PI))^2 = 41253",
"= np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return",
"in arc minutes # SKI_SURFACE IN SQUARE DEGREES = 4. * !PI *",
"verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None,",
"\" + optF + \" \" + file_fits + \" \" + file_out",
"* from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta =",
"healpy as hp from astropy.io import fits import matplotlib.pyplot as plt from scipy.signal",
"Return the pixel size of a healpix map in arc minutes # SKI_SURFACE",
"' -n ' + str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam,",
"g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return",
"- np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted =",
"# Set the ouput file names. file_name = path + 'mr_temp_' + unique_string",
"OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt,",
"print ('CMD = ', cmd) args = shlex.split(cmd) # print('args ', args) call(args)",
"k = hp.ud_grade(mapin, nsideout) return k # smoothing with sigma in arcmin def",
"(ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return",
"hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2),",
"nside, pol=False) return ke def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False)",
"opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names. file_name =",
"progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose,",
"def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return",
"def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is",
"prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = '",
"def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return",
"def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) *",
"g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb=",
"opt if verbose: optF = optF + \" -v \" cmd = cmd",
"not None: optParam = ' -T ' + opt if nside is not",
"as hp from astropy.io import fits import matplotlib.pyplot as plt from scipy.signal import",
"g1,g2 # it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3",
"to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG:",
"= cmd + \" \" + optF + \" \" + file_fits +",
"minutes # SKI_SURFACE IN SQUARE DEGREES = 4. * !PI * (360. /",
"ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b",
"Set the ouput file names. file_name = path + 'mr_temp_' + unique_string file_fits",
"verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T",
"isinstance(opt, type(None)): optF=' ' else: optF= opt if verbose: optF = optF +",
"filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out) # Return",
"minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN,",
"Return the mr_transform results (and the output file names). if remove_files: remove(file_fits) remove(file_out)",
"reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights,",
"mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout)",
"pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab)",
"\" \" + file_out if verbose: print ('CMD = ', cmd) args =",
"hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside = gnside(ke)",
"2, lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside",
"* np.pi l = 1. / ar return l def g2eb(g1,g2): nside =",
"+ str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p",
"# print(\"PROG: \", prog) cmd = prog if isinstance(opt, type(None)): optF=' ' else:",
"ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside",
"return k # smoothing with sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin,",
"def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is",
"pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\",",
"sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow'",
"cmd) args = shlex.split(cmd) # print('args ', args) call(args) # Retrieve wavelet filtered",
"optParam = ' -T ' if opt is not None: optParam = '",
"\" cmd = cmd + \" \" + optF + \" \" +",
"path + 'mr_temp_' + unique_string file_fits = file_name + '.fits' if FileOut is",
"# Return the mr_transform results (and the output file names). if remove_files: remove(file_fits)",
"ndimage import healpy as hp from astropy.io import fits import matplotlib.pyplot as plt",
"fits from importlib import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import *",
"None: optParam = ' -n ' + str(nside) + optParam p = mrs_prog(map,",
"\", prog) cmd = prog if isinstance(opt, type(None)): optF=' ' else: optF= opt",
"kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) =",
"+ \" \" + file_fits + \" \" + file_out if verbose: print",
"if opt is not None: optParam = ' ' + opt if lmax",
"p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None,",
"nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' '",
"verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using the current date",
"def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map,",
"lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True):",
"import * def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec),",
"= ' -n ' + str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose,",
"if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns)",
"verbose=False, path='./',progpath=None): optParam = ' ' if opt is not None: optParam =",
"FileOut is not None: file_out = FileOut else: file_out = file_name + '_out.fits'",
"= datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names. file_name = path +",
"lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map,",
"type(None)): optF=' ' else: optF= opt if verbose: optF = optF + \"",
"DEGREES = 4. * !PI * (360. / (2*!PI))^2 = 41253 psize =",
"nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None,",
"# Return the pixel size of a healpix map in arc minutes #",
"npix = data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside): # Return the",
"bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra,",
"verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = '",
"data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out) # Return the",
"return ke def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab =",
"results (and the output file names). if remove_files: remove(file_fits) remove(file_out) return result else:",
"import matplotlib.pyplot as plt from scipy.signal import savgol_filter from astropy.io import fits from",
"the ouput file names. file_name = path + 'mr_temp_' + unique_string file_fits =",
"return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def",
"def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k",
"'mr_temp_' + unique_string file_fits = file_name + '.fits' if FileOut is not None:",
"return result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p",
"size of a healpix map in arc minutes # SKI_SURFACE IN SQUARE DEGREES",
"OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out) # Return the mr_transform results",
"p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T ' if opt",
"verbose=False): optParam = ' -T ' if opt is not None: optParam =",
"= mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False,",
"' + str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True)",
"def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False)",
"overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return",
"hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi =",
"mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k =",
"p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a =",
"import fits from importlib import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import",
"from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside):",
"opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map,",
"mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is not",
"return p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True)",
"= ', cmd) args = shlex.split(cmd) # print('args ', args) call(args) # Retrieve",
"return a def amin2l(a): ar = a / (180.* 60.) * np.pi l",
"ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin(",
"return result else: return result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose,",
"else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix)",
"string using the current date and time. # print('mr_filter ', opt) unique_string =",
"np.sqrt(psize) def l2amin(l): a = 1. / l a = a * 180.*",
"# print('args ', args) call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix: result",
"return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def",
"is not None: optParam = ' ' + opt if lmax is not",
"+ \" \" + optF + \" \" + file_fits + \" \"",
"sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is",
"data to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) #",
"phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN):",
"bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights)",
"= hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb",
"= 1. / ar return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) =",
"return g1,g2 # it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke)",
"if nside is not None: optParam = ' -n ' + str(nside) +",
"p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T ' if opt is",
"shlex.split(cmd) # print('args ', args) call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix:",
"* !PI * (360. / (2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.)",
"-n ' + str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False,",
"a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None,",
"p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p",
"+ unique_string file_fits = file_name + '.fits' if FileOut is not None: file_out",
"smoothing with sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False)",
"return nside def pixel_size(nside): # Return the pixel size of a healpix map",
"savgol_filter from astropy.io import fits from importlib import reload from pycs.misc.cosmostat_init import *",
"+ 'mr_temp_' + unique_string file_fits = file_name + '.fits' if FileOut is not",
"!PI * (360. / (2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.) *",
"mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T ' if opt is not",
"gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab),",
"map in arc minutes # SKI_SURFACE IN SQUARE DEGREES = 4. * !PI",
"mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique",
"nside = gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False) ab =",
"prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam",
"nside = hp.npix2nside(npix) return nside def pixel_size(nside): # Return the pixel size of",
"mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k",
"(360. / (2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2. return",
"import os, sys from scipy import ndimage import healpy as hp from astropy.io",
"call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result",
"InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True:",
"(g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None,",
"output file names). if remove_files: remove(file_fits) remove(file_out) return result else: return result def",
"' -T ' + opt if nside is not None: optParam = '",
"data) # print(\"PROG: \", prog) cmd = prog if isinstance(opt, type(None)): optF=' '",
"else: return result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return",
"a * 180.* 60. / np.pi return a def amin2l(a): ar = a",
"- np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount",
"# Retrieve wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result =",
"remove(file_out) return result else: return result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\",",
"+ opt if lmax is not None: optParam = ' -l ' +",
"nside def pixel_size(nside): # Return the pixel size of a healpix map in",
"180.* 60. / np.pi return a def amin2l(a): ar = a / (180.*",
"amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return",
"astropy.io import fits from importlib import reload from pycs.misc.cosmostat_init import * from pycs.misc.mr_prog",
"* (360. / (2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2.",
"unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names. file_name = path",
"gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside): # Return",
"mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k # smoothing with sigma in",
"hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta =",
"= 4. * !PI * (360. / (2*!PI))^2 = 41253 psize = 41253.",
"return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae,",
"None: optParam = ' -T ' + opt if lmax is not None:",
"optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None,",
"path='./',progpath=None): optParam = ' ' if opt is not None: optParam = '",
"FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using the current date and",
"date and time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set",
"hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True)",
"str(nside) + optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p",
"return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi -",
"hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix)",
"# print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file",
"SKI_SURFACE IN SQUARE DEGREES = 4. * !PI * (360. / (2*!PI))^2 =",
"1. / ar return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2),",
"opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is",
"(float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a = 1. / l a",
"else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap,",
"ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return",
"import numpy as np import random import os, sys from scipy import ndimage",
"unique_string file_fits = file_name + '.fits' if FileOut is not None: file_out =",
"+ optParam p = mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def",
"hp.npix2nside(npix) return nside def pixel_size(nside): # Return the pixel size of a healpix",
"OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' '",
"get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount",
"hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k # smoothing with",
"hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2): nside =",
"import healpy as hp from astropy.io import fits import matplotlib.pyplot as plt from",
"', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names. file_name",
"hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin,",
"= 1. / l a = a * 180.* 60. / np.pi return",
"title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside =",
"mrs_read(file_out) else: result = readfits(file_out) # Return the mr_transform results (and the output",
"def gnside(data): npix = data.shape[0] nside = hp.npix2nside(npix) return nside def pixel_size(nside): #",
"= optF + \" -v \" cmd = cmd + \" \" +",
"mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T ' if opt is not None:",
"'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.)",
"+ str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \"",
"None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose, opt=optParam, InputFormatisHealpix=False,",
"if OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out) # Return the mr_transform",
"else: prog=progpath+\"mrs_uwttrans -r \" p = mrs_prog(Tmap, prog=prog, verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True,path=path) return",
"if isinstance(opt, type(None)): optF=' ' else: optF= opt if verbose: optF = optF",
"hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength =",
"def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False)",
"hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0] nside",
"+ '_out.fits' # Write the input data to a fits file. if InputFormatisHealpix:",
"\" + file_fits + \" \" + file_out if verbose: print ('CMD =",
"hp from astropy.io import fits import matplotlib.pyplot as plt from scipy.signal import savgol_filter",
"mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam =",
"None: optParam = ' -l ' + str(lmax) + optParam if progpath is",
"lmax is not None: optParam = ' -l ' + str(lmax) + optParam",
"None: optParam = ' ' + opt if lmax is not None: optParam",
"def l2amin(l): a = 1. / l a = a * 180.* 60.",
"np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN)",
"remove(file_fits) remove(file_out) return result else: return result def mrs_powspec(map, verbose=False): p = mrs_prog(map,",
"return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T ' if opt",
"nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2)",
"str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r \" p",
"print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput file names.",
"remove_files: remove(file_fits) remove(file_out) return result else: return result def mrs_powspec(map, verbose=False): p =",
"1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2,",
"opt=None, verbose=False,nside=None): optParam = ' -T ' if opt is not None: optParam",
"with sigma in arcmin def smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) #",
"(g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin crashes.",
"1. / l a = a * 180.* 60. / np.pi return a",
"opt=None, verbose=False): optParam = ' -T ' if opt is not None: optParam",
"' + str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return",
"lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is not None:",
"crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1,",
"(np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix = data.shape[0]",
"' -l ' + str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam,",
"return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T ' if",
"prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string",
"= mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p =",
"l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside,",
"ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside,",
"file_fits = file_name + '.fits' if FileOut is not None: file_out = FileOut",
"= hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab),",
"not None: optParam = ' -T ' + opt if lmax is not",
"bincount def mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN):",
"= hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin crashes. def",
"p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None):",
"lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else:",
"the mr_transform results (and the output file names). if remove_files: remove(file_fits) remove(file_out) return",
"tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax)",
"1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data,",
"optParam = ' -l ' + str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\",",
"l = 1. / ar return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab)",
"weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi",
"' ' if opt is not None: optParam = ' ' + opt",
"+ \" \" + file_out if verbose: print ('CMD = ', cmd) args",
"('CMD = ', cmd) args = shlex.split(cmd) # print('args ', args) call(args) #",
"path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using the",
"result else: return result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False)",
"lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside =",
"' if opt is not None: optParam = ' ' + opt if",
"optParam = ' -l ' + str(lmax) + optParam if progpath is None:",
"is not None: optParam = ' -l ' + str(lmax) + optParam if",
"= np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength =",
"return np.sqrt(psize) def l2amin(l): a = 1. / l a = a *",
"gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False)",
"1,pol=False) ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2",
"* 60.**2. return np.sqrt(psize) def l2amin(l): a = 1. / l a =",
"matplotlib.pyplot as plt from scipy.signal import savgol_filter from astropy.io import fits from importlib",
"verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose,",
"-T ' + opt if nside is not None: optParam = ' -n",
"= np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return",
"= ' -T ' + opt if lmax is not None: optParam =",
"60.) * np.pi l = 1. / ar return l def g2eb(g1,g2): nside",
"the current date and time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0",
"= readfits(file_out) # Return the mr_transform results (and the output file names). if",
"' -l ' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else:",
"astropy.io import fits import matplotlib.pyplot as plt from scipy.signal import savgol_filter from astropy.io",
"hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma",
"41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a",
"/ ar return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2)",
"-l ' + str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False)",
"verbose=False,nside=None): optParam = ' -T ' if opt is not None: optParam =",
"it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1",
"file_out if verbose: print ('CMD = ', cmd) args = shlex.split(cmd) # print('args",
"lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a,",
"the output file names). if remove_files: remove(file_fits) remove(file_out) return result else: return result",
"= np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it",
"= hp.alm2map_spin( (ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./',",
"a = 1. / l a = a * 180.* 60. / np.pi",
"# Write the input data to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data)",
"else: result = readfits(file_out) # Return the mr_transform results (and the output file",
"2) ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside = gnside(ke) ae",
"a / (180.* 60.) * np.pi l = 1. / ar return l",
"hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def",
"nside, pol=False) return ke,kb def g2k(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2)",
"= mrs_prog(map, prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map)",
"gnside(ke) lmax=nside*3 - 1 ae = hp.map2alm(ke, 1, pol=False) ab = hp.map2alm(kb, 1,",
"opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): # Create a unique string using",
"= path + 'mr_temp_' + unique_string file_fits = file_name + '.fits' if FileOut",
"sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def gnside(data): npix",
"prog) cmd = prog if isinstance(opt, type(None)): optF=' ' else: optF= opt if",
"2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside, pol=False) return ke,kb def g2k(g1,g2):",
"cmd = prog if isinstance(opt, type(None)): optF=' ' else: optF= opt if verbose:",
"args = shlex.split(cmd) # print('args ', args) call(args) # Retrieve wavelet filtered data.",
"-l ' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\"",
"OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T '",
"= FileOut else: file_out = file_name + '_out.fits' # Write the input data",
"= file_name + '_out.fits' # Write the input data to a fits file.",
"ke= hp.alm2map(ae, nside, pol=False) return ke def k2g(ke): nside = gnside(ke) ae =",
"file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd",
"print('args ', args) call(args) # Retrieve wavelet filtered data. if OutputFormatisHealpix: result =",
"/ np.pi return a def amin2l(a): ar = a / (180.* 60.) *",
"the input data to a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits,",
"= hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax)",
"0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems that hp.alm2map_spin",
"import savgol_filter from astropy.io import fits from importlib import reload from pycs.misc.cosmostat_init import",
"not None: optParam = ' -l ' + str(lmax) + optParam p =",
"import random import os, sys from scipy import ndimage import healpy as hp",
"if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min,",
"# Create a unique string using the current date and time. # print('mr_filter",
"(180.* 60.) * np.pi l = 1. / ar return l def g2eb(g1,g2):",
"= ' ' if opt is not None: optParam = ' ' +",
"= a / (180.* 60.) * np.pi l = 1. / ar return",
"-l ' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans",
"(ae,ab), nside, 2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False,",
"prog=\"mrs_almrec\", verbose=verbose, opt=optParam, InputFormatisHealpix=False, OutputFormatisHealpix=True) return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if",
"def amin2l(a): ar = a / (180.* 60.) * np.pi l = 1.",
"is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview",
"import ndimage import healpy as hp from astropy.io import fits import matplotlib.pyplot as",
"mrs_read(FN): return hp.read_map(FN) def mrs_write(FN, mapin): hp.write_map(FN, mapin, overwrite=True) def rims(FN): return hp.read_map(FN)",
"as np import random import os, sys from scipy import ndimage import healpy",
"bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return bincount def mrs_read(FN): return hp.read_map(FN) def",
"s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix): return hp.npix2nside(Npix) def",
"str(lmax) + optParam p = mrs_prog(map, prog=\"mrs_almtrans\", verbose=verbose, opt=optParam, OutputFormatisHealpix=False) return p def",
"' ' + opt if lmax is not None: optParam = ' -l",
"else: optF= opt if verbose: optF = optF + \" -v \" cmd",
"2, lmax) return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True,",
"rims(FN): return hp.read_map(FN) def mrs_resize(mapin, nsideout): k = hp.ud_grade(mapin, nsideout) return k #",
"if verbose: print ('CMD = ', cmd) args = shlex.split(cmd) # print('args ',",
"np.pi l = 1. / ar return l def g2eb(g1,g2): nside = gnside(g1)",
"-v \" cmd = cmd + \" \" + optF + \" \"",
"that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 - 1 ae =",
"Create a unique string using the current date and time. # print('mr_filter ',",
"p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt",
"True: lmax=amin2l(lmax_amin) a = mrs_almtrans(map, lmax=lmax) b = mrs_almrec(a, nside=ns) return b def",
"+ '.fits' if FileOut is not None: file_out = FileOut else: file_out =",
"ke def k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae)",
"minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec, nside): pixels=",
"np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 # it seems",
"= np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN) def get_bincount(ra, dec,",
"optF=' ' else: optF= opt if verbose: optF = optF + \" -v",
"ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2,",
"None: optParam = ' -l ' + str(lmax) + optParam p = mrs_prog(map,",
"psize = 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def l2amin(l): a =",
"result def mrs_powspec(map, verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def",
"ab = np.copy(ae) * 0. (g1,g2) = hp.alm2map_spin((ae,ab), 2, lmax=lmax) return g1,g2 #",
"= mrs_read(file_out) else: result = readfits(file_out) # Return the mr_transform results (and the",
"return p def tol(map,lmax_amin,amin=False): ns= gnside(map) lmax=lmax_amin if amin is True: lmax=amin2l(lmax_amin) a",
"mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if opt is not",
"names. file_name = path + 'mr_temp_' + unique_string file_fits = file_name + '.fits'",
"' else: optF= opt if verbose: optF = optF + \" -v \"",
"nsideout): k = hp.ud_grade(mapin, nsideout) return k # smoothing with sigma in arcmin",
"\" \" + optF + \" \" + file_fits + \" \" +",
"os, sys from scipy import ndimage import healpy as hp from astropy.io import",
"= ' -l ' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\"",
"if remove_files: remove(file_fits) remove(file_out) return result else: return result def mrs_powspec(map, verbose=False): p",
"mr_transform results (and the output file names). if remove_files: remove(file_fits) remove(file_out) return result",
"is not None: file_out = FileOut else: file_out = file_name + '_out.fits' #",
"(2*!PI))^2 = 41253 psize = 41253. / (float(nside)**2.*12.) * 60.**2. return np.sqrt(psize) def",
"* 180.* 60. / np.pi return a def amin2l(a): ar = a /",
"opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False): optParam = ' -T",
"return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = ' ' if",
"from scipy.signal import savgol_filter from astropy.io import fits from importlib import reload from",
"if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd =",
"= ' -T ' + opt if nside is not None: optParam =",
"= file_name + '.fits' if FileOut is not None: file_out = FileOut else:",
"def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) *",
"+ file_out if verbose: print ('CMD = ', cmd) args = shlex.split(cmd) #",
"sys from scipy import ndimage import healpy as hp from astropy.io import fits",
"pol=False) ab = hp.map2alm(kb, 1, pol=False) (g1,g2) = hp.alm2map_spin( (ae,ab), nside, 2, lmax)",
"= hp.ud_grade(mapin, nsideout) return k # smoothing with sigma in arcmin def smooth(map,",
"OutputFormatisHealpix=True): # Create a unique string using the current date and time. #",
"= ' ' + opt if lmax is not None: optParam = '",
"a fits file. if InputFormatisHealpix: mrs_write(file_fits, data) else: writefits(file_fits, data) # print(\"PROG: \",",
"not None: optParam = ' ' + opt if lmax is not None:",
"the pixel size of a healpix map in arc minutes # SKI_SURFACE IN",
"scipy.signal import savgol_filter from astropy.io import fits from importlib import reload from pycs.misc.cosmostat_init",
"numpy as np import random import os, sys from scipy import ndimage import",
"nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels,",
"optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose,",
"# it seems that hp.alm2map_spin crashes. def eb2g(ke,kb): nside = gnside(ke) lmax=nside*3 -",
"phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength",
"\" -v \" cmd = cmd + \" \" + optF + \"",
"cmd = cmd + \" \" + optF + \" \" + file_fits",
"smooth(map, sigma): s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def",
"pixels= hp.ang2pix(nside,theta = 0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength",
"hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False) hp.mollview(s,max=max,min=min, title=title,cmap=lut) hp.mollview def get_nside(Npix):",
"p def mrs_smooth(map, opt=None, verbose=False): p = mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return",
"l a = a * 180.* 60. / np.pi return a def amin2l(a):",
"ouput file names. file_name = path + 'mr_temp_' + unique_string file_fits = file_name",
"# 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s=",
"np.pi return a def amin2l(a): ar = a / (180.* 60.) * np.pi",
"opt is not None: optParam = ' -T ' + opt if lmax",
"str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map,",
"* (np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None:",
"data) else: writefits(file_fits, data) # print(\"PROG: \", prog) cmd = prog if isinstance(opt,",
"' + str(lmax) + optParam if progpath is None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans -r",
"= shlex.split(cmd) # print('args ', args) call(args) # Retrieve wavelet filtered data. if",
"= mrs_prog(map, prog=\"mrs_smooth\", verbose=verbose, opt=opt, OutputFormatisHealpix=True) return p def mrs_almtrans(map, lmax=None, opt=None, verbose=False):",
"OutputFormatisHealpix=False) return p def mrs_almrec(map, opt=None, verbose=False,nside=None): optParam = ' -T ' if",
"tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min, title=title,cmap=lut) else: s= hp.smoothing(mapin, sigma=sigma/(360.*60.) * (np.pi*2),pol=False)",
"k2g(ke): nside = gnside(ke) ae = hp.map2alm(ke, 1,pol=False) ab = np.copy(ae) * 0.",
"and time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the",
"is not None: optParam = ' -T ' + opt if lmax is",
"= gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae, nside, pol=False) kb= hp.alm2map(ab, nside,",
"prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None,",
"= hp.nside2npix(nside)) bincount_weighted = np.bincount(pixels, minlength = hp.nside2npix(nside), weights=weights) return np.where(bincount>0.5, bincount_weighted/bincount, hp.UNSEEN)",
"is not None: optParam = ' -l ' + str(lmax) + optParam p",
"= hp.npix2nside(npix) return nside def pixel_size(nside): # Return the pixel size of a",
"0.5*np.pi - np.deg2rad(dec), phi = np.deg2rad(ra)) bincount = np.bincount(pixels, minlength = hp.nside2npix(nside)) return",
"if opt is not None: optParam = ' -T ' + opt if",
"wavelet filtered data. if OutputFormatisHealpix: result = mrs_read(file_out) else: result = readfits(file_out) #",
"readfits(file_out) # Return the mr_transform results (and the output file names). if remove_files:",
"mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None):",
"unique string using the current date and time. # print('mr_filter ', opt) unique_string",
"writefits(file_fits, data) # print(\"PROG: \", prog) cmd = prog if isinstance(opt, type(None)): optF='",
"hp.ud_grade(mapin, nsideout) return k # smoothing with sigma in arcmin def smooth(map, sigma):",
"(np.pi*2),pol=False) # lut='rainbow' # 'inferno' 'gist_stern' def tvs(mapin,min=None,max=None,title=None,sigma=None,lut=None): if sigma is None: hp.mollview(mapin,max=max,min=min,",
"current date and time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 #",
"verbose=False): p = mrs_prog(map, prog=\"mrs_powspec\", verbose=verbose, OutputFormatisHealpix=False) return p def mrs_smooth(map, opt=None, verbose=False):",
"opt=optParam, OutputFormatisHealpix=False,path=path) return p def mrs_uwtrecons(Tmap, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam = '",
"file_fits + \" \" + file_out if verbose: print ('CMD = ', cmd)",
"verbose: optF = optF + \" -v \" cmd = cmd + \"",
"nsideout) return k # smoothing with sigma in arcmin def smooth(map, sigma): s=",
"return l def g2eb(g1,g2): nside = gnside(g1) (ae,ab) = hp.map2alm_spin((g1,g2), 2) ke= hp.alm2map(ae,",
"None: prog=\"mrs_uwttrans\" else: prog=progpath+\"mrs_uwttrans\" p = mrs_prog(map, prog=prog, verbose=verbose, opt=optParam, OutputFormatisHealpix=False,path=path) return p",
"pycs.misc.mr_prog import * def make_healpix_map(ra, dec, weights, nside): pixels= hp.ang2pix(nside,theta = 0.5*np.pi -",
"names). if remove_files: remove(file_fits) remove(file_out) return result else: return result def mrs_powspec(map, verbose=False):",
"b = mrs_almrec(a, nside=ns) return b def mrs_uwttrans(map, lmax=None, opt=None, verbose=False, path='./',progpath=None): optParam",
"time. # print('mr_filter ', opt) unique_string = datetime.now().strftime('%Y.%m.%d_%H.%M.%S') result=0 # Set the ouput",
"optParam = ' ' if opt is not None: optParam = ' '",
"return g1,g2 def mrs_prog(data, prog=\"mrs_powspec\", opt=None, path='./', remove_files=True, verbose=False, FileOut=None, InputFormatisHealpix=True, OutputFormatisHealpix=True): #",
"None: optParam = ' -T ' + opt if nside is not None:",
"amin2l(a): ar = a / (180.* 60.) * np.pi l = 1. /",
"from astropy.io import fits import matplotlib.pyplot as plt from scipy.signal import savgol_filter from"
] |
[
"assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return",
"response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker",
"200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should",
"= requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def",
"headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert (",
"@pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response",
"all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200 assert",
"f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract",
"def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response =",
"None: \"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert",
"def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\"",
"response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) ->",
"( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str)",
"assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" )",
"for cases for all organization catalogs.\"\"\" import json import pytest import requests from",
"test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response =",
"import pytest import requests from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str)",
"= f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs)",
"== \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None:",
"-> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response = requests.get(url) assert response.status_code",
"max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the",
") @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap response.\"\"\"",
"json import pytest import requests from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service:",
"import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs",
"@pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs response.\"\"\" url",
"all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert",
"response = requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store,",
"cases for cases for all organization catalogs.\"\"\" import json import pytest import requests",
"f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache,",
"-> None: \"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url)",
"str) -> None: \"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response =",
"== json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\"",
"requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service:",
"= requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0,",
"= f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap)",
"str) -> None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url)",
"200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should",
"@pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\"",
"for all organization catalogs.\"\"\" import json import pytest import requests from tests import",
"requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\"",
"== 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None:",
"include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200",
"str) -> None: \"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response =",
"return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code ==",
"catalogs.\"\"\" import json import pytest import requests from tests import responses @pytest.mark.contract @pytest.mark.docker",
"def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response",
"@pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\" url =",
"must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap",
"\"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response = requests.get(url) assert response.status_code == 400",
"\"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should",
"url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\")",
"requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service:",
"test cases for cases for all organization catalogs.\"\"\" import json import pytest import",
"@pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap response.\"\"\" url",
"the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200",
"organization catalogs.\"\"\" import json import pytest import requests from tests import responses @pytest.mark.contract",
"== json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url",
"responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs response.\"\"\"",
"assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str)",
"response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) ->",
"200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def",
"response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker",
"response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert response.json()",
"json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache headers.\"\"\" url",
"-> None: \"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url)",
"@pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs response.\"\"\" url =",
"assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service:",
"response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) ->",
"response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\"",
"\"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code ==",
"return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code ==",
"import json import pytest import requests from tests import responses @pytest.mark.contract @pytest.mark.docker def",
"f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract",
"the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200",
"test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response = requests.get(url)",
"from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return",
"requests from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should",
"no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return",
"\"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code",
"test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response",
"pytest import requests from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) ->",
"== 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None:",
"json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url =",
"str) -> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response = requests.get(url) assert",
"None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code",
"response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200 assert response.json()",
"== 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract @pytest.mark.docker",
"cases for all organization catalogs.\"\"\" import json import pytest import requests from tests",
"url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert response.json() ==",
"response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") == \"no-cache, no-store, max-age=0, must-revalidate\" ) @pytest.mark.contract",
"assert response.status_code == 200 assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str)",
"= f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert ( response.headers.get(\"Cache-Control\") ==",
"all organization catalogs.\"\"\" import json import pytest import requests from tests import responses",
"tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the",
"-> None: \"\"\"Should include no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert",
"@pytest.mark.docker def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap response.\"\"\" url =",
"response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include no-cache",
"\"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code",
"@pytest.mark.contract @pytest.mark.docker def test_invalid_filter(docker_service: str) -> None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\"",
"None: \"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert",
"url = f\"{docker_service}/organizationcatalogs?filter=transportportal\" response = requests.get(url) assert response.status_code == 200 assert response.json() ==",
"= requests.get(url) assert response.status_code == 200 assert response.json() == json.loads(responses.all_nap) @pytest.mark.contract @pytest.mark.docker def",
"\"\"\"Contract test cases for cases for all organization catalogs.\"\"\" import json import pytest",
"no-cache headers.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response = requests.get(url) assert response.status_code == 200 assert",
"def test_all_nap_catalogs(docker_service: str) -> None: \"\"\"Should return the all_nap response.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=transportportal\"",
"test_all_catalogs(docker_service: str) -> None: \"\"\"Should return the all_catalogs response.\"\"\" url = f\"{docker_service}/organizationcatalogs\" response",
"None: \"\"\"Should return 400.\"\"\" url = f\"{docker_service}/organizationcatalogs?filter=invalid\" response = requests.get(url) assert response.status_code ==",
"assert response.json() == json.loads(responses.all_catalogs) @pytest.mark.contract @pytest.mark.docker def test_all_catalogs_has_no_cache_headers(docker_service: str) -> None: \"\"\"Should include",
"import requests from tests import responses @pytest.mark.contract @pytest.mark.docker def test_all_catalogs(docker_service: str) -> None:"
] |
[
"taxon_len = max([len(taxon) for taxon in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\"",
"+= \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in assumptions:",
"\"1\"][v] for v in vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon) for",
"= defaultdict(list) all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs",
"\"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len +",
"concept in sorted(all_cogs): buf += \"0\" # ascert cogids = all_cogs[concept] # if",
"taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus +=",
"\"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\"",
"value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx",
"= defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value)",
"csv from pathlib import Path from collections import defaultdict BASE = Path(__file__).parents[1] /",
"NEXUS file form a long-table format CSV. \"\"\" import csv from pathlib import",
"1 for cog in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for",
"taxa: buf = \"\" for concept in sorted(all_cogs): buf += \"0\" # ascert",
"with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"]",
"nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=?",
"row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value in all_cogs.items()} charstates =",
"= [] cur_idx = 1 for cog in sorted(all_cogs): value = all_cogs[cog] k",
"end_idx]) cur_idx = end_idx + 1 matrix = {} for taxon in taxa:",
"% (label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\"",
"+= \"0\" # ascert cogids = all_cogs[concept] # if empty if len(cogs[taxon, concept])",
"cur_idx = 1 for cog in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0]",
"nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for idx, cs in",
"+= \"%s %s\\n\" % (label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus",
"= all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx =",
"\"\"\" import csv from pathlib import Path from collections import defaultdict BASE =",
"1, cs) for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\"",
"value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog,",
"for v in vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon) for taxon",
"cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value in all_cogs.items()} charstates",
"\"%s %s\\n\" % (label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus +=",
"for cog in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub",
"assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" %",
"k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx = cur_idx +",
"4) nexus += \"%s %s\\n\" % (label, vector) nexus += \";\\n\" nexus +=",
"import defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as",
"= all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1], assump[2]) nexus",
"NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus",
"for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon]",
"buf ############ taxon_len = max([len(taxon) for taxon in taxa]) nexus = \"\" nexus",
"defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h:",
"taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list) all_cogs = defaultdict(set)",
"all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1], assump[2]) nexus +=",
"= cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1 matrix",
"nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS",
"in taxa: buf = \"\" for concept in sorted(all_cogs): buf += \"0\" #",
"= [] assumptions = [] cur_idx = 1 for cog in sorted(all_cogs): value",
"vector in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" %",
"if len(cogs[taxon, concept]) == 0: buf += \"?\" * len(cogids) else: vec =",
"in sorted(all_cogs): buf += \"0\" # ascert cogids = all_cogs[concept] # if empty",
"+= \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus +=",
"%s\\n\" % (label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin",
"= buf ############ taxon_len = max([len(taxon) for taxon in taxa]) nexus = \"\"",
"nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in",
"DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx",
"+= \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa),",
"enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in matrix.items(): label",
"= taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" % (label, vector) nexus +=",
"for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\"",
"in data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"],",
"for key, value in all_cogs.items()} charstates = [] assumptions = [] cur_idx =",
"cur_idx, end_idx]) cur_idx = end_idx + 1 matrix = {} for taxon in",
"sorted(all_cogs): buf += \"0\" # ascert cogids = all_cogs[concept] # if empty if",
"form a long-table format CSV. \"\"\" import csv from pathlib import Path from",
"+ 4) nexus += \"%s %s\\n\" % (label, vector) nexus += \";\\n\" nexus",
"from collections import defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\",",
"end_idx + 1 matrix = {} for taxon in taxa: buf = \"\"",
"in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] = buf",
"+= \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] = buf ############ taxon_len =",
"for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus += \"%s",
"assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s =",
"defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for",
"= value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx = cur_idx + len(value)",
"Builds a NEXUS file form a long-table format CSV. \"\"\" import csv from",
"matrix[taxon] = buf ############ taxon_len = max([len(taxon) for taxon in taxa]) nexus =",
"list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list) all_cogs =",
"buf = \"\" for concept in sorted(all_cogs): buf += \"0\" # ascert cogids",
"DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD",
"nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i",
"+ 1, cs) for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus +=",
"nexus += \"%s %s\\n\" % (label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\"",
"v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1], assump[2])",
"\"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";'",
"NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus +=",
"in all_cogs.items()} charstates = [] assumptions = [] cur_idx = 1 for cog",
"\"MATRIX\\n\" for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus +=",
"cog in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in",
"encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data]))",
"buf += \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] = buf ############ taxon_len",
"for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon,",
"+= \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=-",
"= {} for taxon in taxa: buf = \"\" for concept in sorted(all_cogs):",
"= list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list) all_cogs",
"/ \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row",
"sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub)",
"nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in assumptions: v =",
"nexus += \"begin assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus +=",
"as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs",
"= all_cogs[concept] # if empty if len(cogs[taxon, concept]) == 0: buf += \"?\"",
"= [cogid in cogs[taxon, concept] for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v]",
"+= \"?\" * len(cogids) else: vec = [cogid in cogs[taxon, concept] for cogid",
"label = taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" % (label, vector) nexus",
"len(cogids) else: vec = [cogid in cogs[taxon, concept] for cogid in cogids] buf",
"v in vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon) for taxon in",
"= 1 for cog in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\")",
"cs) for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for",
"cur_idx = end_idx + 1 matrix = {} for taxon in taxa: buf",
"charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx,",
"{} for taxon in taxa: buf = \"\" for concept in sorted(all_cogs): buf",
"\"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa =",
"taxon in taxa: buf = \"\" for concept in sorted(all_cogs): buf += \"0\"",
"for concept in sorted(all_cogs): buf += \"0\" # ascert cogids = all_cogs[concept] #",
"# ascert cogids = all_cogs[concept] # if empty if len(cogs[taxon, concept]) == 0:",
"for taxon in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN",
"for row in data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for row in",
"cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in",
"{key: sorted(value) for key, value in all_cogs.items()} charstates = [] assumptions = []",
"value in all_cogs.items()} charstates = [] assumptions = [] cur_idx = 1 for",
"cogs = defaultdict(list) all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"])",
"all_cogs[concept] # if empty if len(cogs[taxon, concept]) == 0: buf += \"?\" *",
"max([len(taxon) for taxon in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus +=",
"/ \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa",
"taxon, vector in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\"",
"matrix.items(): label = taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" % (label, vector)",
"\"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT",
"1 matrix = {} for taxon in taxa: buf = \"\" for concept",
"if empty if len(cogs[taxon, concept]) == 0: buf += \"?\" * len(cogids) else:",
"cogids = all_cogs[concept] # if empty if len(cogs[taxon, concept]) == 0: buf +=",
"nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in matrix.items(): label =",
"in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus",
"taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" % (label, vector) nexus += \";\\n\"",
"= \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i",
"len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus +=",
"format CSV. \"\"\" import csv from pathlib import Path from collections import defaultdict",
"all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx = cur_idx",
"all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key:",
"ascert cogids = all_cogs[concept] # if empty if len(cogs[taxon, concept]) == 0: buf",
"%s\" % (idx + 1, cs) for idx, cs in enumerate(charstates)]) nexus +=",
"* len(cogids) else: vec = [cogid in cogs[taxon, concept] for cogid in cogids]",
"BASE = Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data",
"nexus += \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1], assump[2]) nexus += \"end;\\n\\n\"",
"data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value in all_cogs.items()}",
"\"0\" # ascert cogids = all_cogs[concept] # if empty if len(cogs[taxon, concept]) ==",
"SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs)",
"[cogid in cogs[taxon, concept] for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for",
"empty if len(cogs[taxon, concept]) == 0: buf += \"?\" * len(cogids) else: vec",
"= {key: sorted(value) for key, value in all_cogs.items()} charstates = [] assumptions =",
"cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] =",
"GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1,",
"\"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for idx, cs",
"for sub in value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx])",
"assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1],",
"assumptions = [] cur_idx = 1 for cog in sorted(all_cogs): value = all_cogs[cog]",
"+= \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for idx,",
"in sorted(all_cogs): value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value:",
"\"\" for concept in sorted(all_cogs): buf += \"0\" # ascert cogids = all_cogs[concept]",
"+= \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0]",
"vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon) for taxon in taxa]) nexus",
"[] assumptions = [] cur_idx = 1 for cog in sorted(all_cogs): value =",
"buf += \"0\" # ascert cogids = all_cogs[concept] # if empty if len(cogs[taxon,",
"############ taxon_len = max([len(taxon) for taxon in taxa]) nexus = \"\" nexus +=",
"+= '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\"",
"\";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in assumptions: v",
"+= \"begin assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset",
"concept]) == 0: buf += \"?\" * len(cogids) else: vec = [cogid in",
"(idx + 1, cs) for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus",
"\"\"\" Builds a NEXUS file form a long-table format CSV. \"\"\" import csv",
"buf += \"?\" * len(cogids) else: vec = [cogid in cogs[taxon, concept] for",
"\"begin assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s",
"from pathlib import Path from collections import defaultdict BASE = Path(__file__).parents[1] / \"data\"",
"in cogs[taxon, concept] for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v",
"value = all_cogs[cog] k = value[0].split(\"_\")[0] charstates.append(f\"{k}_ascertainment\") for sub in value: charstates.append(sub) end_idx",
"assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1 matrix = {} for taxon",
"\",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for idx, cs in enumerate(charstates)]) nexus",
"idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector",
"all_cogs.items()} charstates = [] assumptions = [] cur_idx = 1 for cog in",
"+= \"MATRIX\\n\" for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus",
"in enumerate(charstates)]) nexus += \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in matrix.items():",
"cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] = buf ############",
"\"\".join([[\"0\", \"1\"][v] for v in vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon)",
"else: vec = [cogid in cogs[taxon, concept] for cogid in cogids] buf +=",
"key, value in all_cogs.items()} charstates = [] assumptions = [] cur_idx = 1",
"+ 1 matrix = {} for taxon in taxa: buf = \"\" for",
"\"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus",
"file form a long-table format CSV. \"\"\" import csv from pathlib import Path",
"CSV. \"\"\" import csv from pathlib import Path from collections import defaultdict BASE",
"= end_idx + 1 matrix = {} for taxon in taxa: buf =",
"in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value in",
"row in data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for row in data:",
"\"?\" * len(cogids) else: vec = [cogid in cogs[taxon, concept] for cogid in",
"concept] for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in vec])",
"import csv from pathlib import Path from collections import defaultdict BASE = Path(__file__).parents[1]",
"for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key,",
"charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx +",
"len(cogs[taxon, concept]) == 0: buf += \"?\" * len(cogids) else: vec = [cogid",
"vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for assump",
"vec = [cogid in cogs[taxon, concept] for cogid in cogids] buf += \"\".join([[\"0\",",
"in matrix.items(): label = taxon.ljust(taxon_len + 4) nexus += \"%s %s\\n\" % (label,",
"data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list)",
"= max([len(taxon) for taxon in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus",
"== 0: buf += \"?\" * len(cogids) else: vec = [cogid in cogs[taxon,",
"in assumptions: v = all_cogs[assump[0]][0].split(\"_\")[0] nexus += \"\\tcharset %s = %i-%i;\\n\" % (v,",
"Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h))",
"(len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus",
"'\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" %",
"\"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]]))",
"matrix = {} for taxon in taxa: buf = \"\" for concept in",
"open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for",
"\"ielex.csv\", encoding=\"utf-8\") as h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in",
"collections import defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\")",
"for taxon in taxa: buf = \"\" for concept in sorted(all_cogs): buf +=",
"+= \"\\n;\\n\" nexus += \"MATRIX\\n\" for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len",
"sorted(value) for key, value in all_cogs.items()} charstates = [] assumptions = [] cur_idx",
"cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1 matrix =",
"MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx +",
"nexus += \"\\tCHARSTATELABELS\\n\" nexus += \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for",
"len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1 matrix = {} for",
"nexus += \"MATRIX\\n\" for taxon, vector in matrix.items(): label = taxon.ljust(taxon_len + 4)",
"(label, vector) nexus += \";\\n\" nexus += \"END;\\n\\n\" nexus += \"begin assumptions;\\n\" for",
"import Path from collections import defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE",
"h: data = list(csv.DictReader(h)) taxa = sorted(set([row[\"LANGUAGE\"] for row in data])) cogs =",
"nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" %",
"= sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for",
"nexus += \"BEGIN DATA;\\n\" nexus += \"\\tDIMENSIONS NTAX=%i NCHAR=%i;\\n\" % (len(taxa), len(matrix[taxa[0]])) nexus",
"% (len(taxa), len(matrix[taxa[0]])) nexus += '\\tFORMAT DATATYPE=STANDARD MISSING=? GAP=- SYMBOLS=\"01\";' nexus += \"\\tCHARSTATELABELS\\n\"",
"+= \"\\tcharset %s = %i-%i;\\n\" % (v, assump[1], assump[2]) nexus += \"end;\\n\\n\" print(nexus)",
"long-table format CSV. \"\"\" import csv from pathlib import Path from collections import",
"+ len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1 matrix = {}",
"in vec]) matrix[taxon] = buf ############ taxon_len = max([len(taxon) for taxon in taxa])",
"Path from collections import defaultdict BASE = Path(__file__).parents[1] / \"data\" with open(BASE /",
"sub in value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx",
"charstates = [] assumptions = [] cur_idx = 1 for cog in sorted(all_cogs):",
"= Path(__file__).parents[1] / \"data\" with open(BASE / \"ielex.csv\", encoding=\"utf-8\") as h: data =",
"a NEXUS file form a long-table format CSV. \"\"\" import csv from pathlib",
"all_cogs = {key: sorted(value) for key, value in all_cogs.items()} charstates = [] assumptions",
"pathlib import Path from collections import defaultdict BASE = Path(__file__).parents[1] / \"data\" with",
"[] cur_idx = 1 for cog in sorted(all_cogs): value = all_cogs[cog] k =",
"sorted(set([row[\"LANGUAGE\"] for row in data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for row",
"a long-table format CSV. \"\"\" import csv from pathlib import Path from collections",
"= \"\" for concept in sorted(all_cogs): buf += \"0\" # ascert cogids =",
"data])) cogs = defaultdict(list) all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"])",
"end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx = end_idx + 1",
"all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value in all_cogs.items()} charstates = []",
"# if empty if len(cogs[taxon, concept]) == 0: buf += \"?\" * len(cogids)",
"0: buf += \"?\" * len(cogids) else: vec = [cogid in cogs[taxon, concept]",
"row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs = {key: sorted(value) for key, value",
"taxon in taxa]) nexus = \"\" nexus += \"#NEXUS\\n\\n\" nexus += \"BEGIN DATA;\\n\"",
"+= \",\\n\".join([\"\\t\\t%i %s\" % (idx + 1, cs) for idx, cs in enumerate(charstates)])",
"defaultdict(list) all_cogs = defaultdict(set) for row in data: cogs[row[\"LANGUAGE\"], row[\"CONCEPT\"]].append(row[\"COGNATE\"]) all_cogs[row[\"CONCEPT\"]].add(row[\"COGNATE\"]) all_cogs =",
"in value: charstates.append(sub) end_idx = cur_idx + len(value) assumptions.append([cog, cur_idx, end_idx]) cur_idx =",
"cogs[taxon, concept] for cogid in cogids] buf += \"\".join([[\"0\", \"1\"][v] for v in",
"% (idx + 1, cs) for idx, cs in enumerate(charstates)]) nexus += \"\\n;\\n\""
] |
[
"msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\",",
"if lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text =",
"[ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count ==",
"+= add index += 1 add = 0 add_bool=False last = i[3] text",
"= i[3] text += \"\\n%i.%-20s %3d\" % (index, qq2name(memberList,i[2]), i[3]) msg.append(Plain(text=text)) return msg",
"by count desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg = []",
"import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList: list) ->",
"= \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ]",
"= False add = 0 last = -1 for i in lsp_rank: if",
"]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0 add_bool",
"\"select * from dragon where groupId=%d order by count desc\" % group_id lsp_rank",
"Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return [",
"add index += 1 add = 0 add_bool=False last = i[3] text +=",
"0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text",
"execute_sql async def get_rank(group_id: int, memberList: list) -> list: sql = \"select *",
"MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return",
"if lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count",
"== (): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3]",
"text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0 add_bool = False",
"from dragon where groupId=%d order by count desc\" % group_id lsp_rank = await",
"= True else: if add_bool: index += add index += 1 add =",
"execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return",
"desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg = [] text =",
"+= 1 add_bool = True else: if add_bool: index += add index +=",
"= 0 last = -1 for i in lsp_rank: if i[3] == 0:",
"from graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async",
"add += 1 add_bool = True else: if add_bool: index += add index",
"False add = 0 last = -1 for i in lsp_rank: if i[3]",
"\"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else:",
"order by count desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg =",
"if i[3] == 0: break if i[3] == last: add += 1 add_bool",
"list) -> list: sql = \"select * from dragon where groupId=%d order by",
"= 0 add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\" % (index, qq2name(memberList,i[2]),",
"from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList: list) -> list: sql",
"last: add += 1 add_bool = True else: if add_bool: index += add",
"add = 0 last = -1 for i in lsp_rank: if i[3] ==",
"-1 for i in lsp_rank: if i[3] == 0: break if i[3] ==",
"group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if",
"graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList: list)",
"break if i[3] == last: add += 1 add_bool = True else: if",
"add_bool: index += add index += 1 add = 0 add_bool=False last =",
"= [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\", MessageChain.create([",
"]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\",",
"msg.append(Plain(text=text)) text = \"\" index = 0 add_bool = False add = 0",
"from graia.application.message.chain import MessageChain from graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from",
"int, memberList: list) -> list: sql = \"select * from dragon where groupId=%d",
"add = 0 add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\" % (index,",
"== last: add += 1 add_bool = True else: if add_bool: index +=",
"for i in lsp_rank: if i[3] == 0: break if i[3] == last:",
"% group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\"",
"text = \"\" index = 0 add_bool = False add = 0 last",
"dragon where groupId=%d order by count desc\" % group_id lsp_rank = await execute_sql(sql)",
"print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [",
"sql = \"select * from dragon where groupId=%d order by count desc\" %",
"graia.application.message.chain import MessageChain from graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute",
"SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList: list) -> list: sql =",
"in lsp_rank: if i[3] == 0: break if i[3] == last: add +=",
"count desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg = [] text",
"i in lsp_rank: if i[3] == 0: break if i[3] == last: add",
"await execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == ():",
"] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\", MessageChain.create([",
"-> list: sql = \"select * from dragon where groupId=%d order by count",
"else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text)",
"def get_rank(group_id: int, memberList: list) -> list: sql = \"select * from dragon",
"memberList: list) -> list: sql = \"select * from dragon where groupId=%d order",
"if add_bool: index += add index += 1 add = 0 add_bool=False last",
"(): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if",
"0 add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\" % (index, qq2name(memberList,i[2]), i[3])",
"text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text) ])",
"At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList: list) -> list:",
"graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def",
"add_bool = False add = 0 last = -1 for i in lsp_rank:",
"lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\"",
"lsp_rank: if i[3] == 0: break if i[3] == last: add += 1",
"index += 1 add = 0 add_bool=False last = i[3] text += \"\\n%i.%-20s",
"add_bool = True else: if add_bool: index += add index += 1 add",
"lsp_rank = await execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank",
"async def get_rank(group_id: int, memberList: list) -> list: sql = \"select * from",
"Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int,",
"* from dragon where groupId=%d order by count desc\" % group_id lsp_rank =",
"list: sql = \"select * from dragon where groupId=%d order by count desc\"",
"if i[3] == last: add += 1 add_bool = True else: if add_bool:",
"0 add_bool = False add = 0 last = -1 for i in",
"import MessageChain from graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import",
"from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id: int, memberList:",
"\"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0 add_bool = False add =",
"lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text",
"\"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index",
"= \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0 add_bool = False add",
"= -1 for i in lsp_rank: if i[3] == 0: break if i[3]",
"groupId=%d order by count desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank) msg",
"== 0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text))",
"lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text) ])",
"True else: if add_bool: index += add index += 1 add = 0",
"add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\" % (index, qq2name(memberList,i[2]), i[3]) msg.append(Plain(text=text))",
"return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text =",
"0 last = -1 for i in lsp_rank: if i[3] == 0: break",
"else: if add_bool: index += add index += 1 add = 0 add_bool=False",
"1 add_bool = True else: if add_bool: index += add index += 1",
"= \"\" index = 0 add_bool = False add = 0 last =",
"+= 1 add = 0 add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\"",
"last = i[3] text += \"\\n%i.%-20s %3d\" % (index, qq2name(memberList,i[2]), i[3]) msg.append(Plain(text=text)) return",
"[] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text)",
"\"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count == 0:",
"= lsp_rank[0][3] if lsp_champion_count == 0: return [ \"None\", MessageChain.create([ Plain(text=text) ]) ]",
"index = 0 add_bool = False add = 0 last = -1 for",
"get_rank(group_id: int, memberList: list) -> list: sql = \"select * from dragon where",
"MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index =",
"Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0",
"where groupId=%d order by count desc\" % group_id lsp_rank = await execute_sql(sql) print(lsp_rank)",
"0: break if i[3] == last: add += 1 add_bool = True else:",
"i[3] == last: add += 1 add_bool = True else: if add_bool: index",
"lsp_rank == (): return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count =",
"MessageChain from graia.application.message.elements.internal import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql",
"= 0 add_bool = False add = 0 last = -1 for i",
"1 add = 0 add_bool=False last = i[3] text += \"\\n%i.%-20s %3d\" %",
"== 0: break if i[3] == last: add += 1 add_bool = True",
"last = -1 for i in lsp_rank: if i[3] == 0: break if",
"return [ \"None\", MessageChain.create([ Plain(text=text) ]) ] else: lsp_champion_count = lsp_rank[0][3] if lsp_champion_count",
"[ \"None\", MessageChain.create([ Plain(text=text) ]) ] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\"",
"i[3] == 0: break if i[3] == last: add += 1 add_bool =",
"= \"select * from dragon where groupId=%d order by count desc\" % group_id",
"= await execute_sql(sql) print(lsp_rank) msg = [] text = \"啊嘞嘞,从启动到现在都没有人要过涩图的嘛!呜呜呜~\\n人家。。。人家好寂寞的,快来找我玩嘛~\" if lsp_rank ==",
"import Plain from graia.application.message.elements.internal import At from SAGIRIBOT.basics.aio_mysql_excute import execute_sql async def get_rank(group_id:",
"] text = \"目前lsp排行榜:\" msg.append(Plain(text=text)) text = \"\" index = 0 add_bool =",
"import execute_sql async def get_rank(group_id: int, memberList: list) -> list: sql = \"select",
"\"\" index = 0 add_bool = False add = 0 last = -1",
"index += add index += 1 add = 0 add_bool=False last = i[3]"
] |
[
"n = int(input()) n,a1 = divmod(n,10) n,a2 = divmod(n,10) n,a3 = divmod(n,10) print(100*chg(a3)+10*chg(a2)+chg(a1))",
"1 return n n = int(input()) n,a1 = divmod(n,10) n,a2 = divmod(n,10) n,a3",
"n n = int(input()) n,a1 = divmod(n,10) n,a2 = divmod(n,10) n,a3 = divmod(n,10)",
"return n n = int(input()) n,a1 = divmod(n,10) n,a2 = divmod(n,10) n,a3 =",
"if n==1: return 9 elif n==9: return 1 return n n = int(input())",
"def chg(n): if n==1: return 9 elif n==9: return 1 return n n",
"chg(n): if n==1: return 9 elif n==9: return 1 return n n =",
"n==1: return 9 elif n==9: return 1 return n n = int(input()) n,a1",
"9 elif n==9: return 1 return n n = int(input()) n,a1 = divmod(n,10)",
"elif n==9: return 1 return n n = int(input()) n,a1 = divmod(n,10) n,a2",
"n==9: return 1 return n n = int(input()) n,a1 = divmod(n,10) n,a2 =",
"<gh_stars>0 def chg(n): if n==1: return 9 elif n==9: return 1 return n",
"return 1 return n n = int(input()) n,a1 = divmod(n,10) n,a2 = divmod(n,10)",
"return 9 elif n==9: return 1 return n n = int(input()) n,a1 ="
] |
[
"[3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave",
"== 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def",
"0, 0, 0, 5], [4, 0, 0, 0, 4], [3, 4, 5, 4,",
"0, 0, 5], [4, 0, 0, 0, 4], [3, 4, 5, 4, 3],",
"3], ] assert cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6],",
"4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert",
"5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor():",
"cave = Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() == [ [3, 4,",
"3], [4, 0, 0, 0, 4], [5, 0, 0, 0, 5], [4, 0,",
"== 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2():",
"cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines =",
"] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0",
"2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave",
"assert cave.energy_levels() == [ [3, 4, 5, 4, 3], [4, 0, 0, 0,",
"0, 0, 0, 4], [5, 0, 0, 0, 5], [4, 0, 0, 0,",
"= \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\"",
"] assert cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5],",
"cave.energy_levels() == [ [3, 4, 5, 4, 3], [4, 0, 0, 0, 4],",
"2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels()",
"0, 0, 0, 4], [3, 4, 5, 4, 3], ] assert cave.tick() ==",
"[ [3, 4, 5, 4, 3], [4, 0, 0, 0, 4], [5, 0,",
"[3, 4, 5, 4, 3], ] assert cave.tick() == 0 assert cave.energy_levels() ==",
"cave.tick() == 9 assert cave.energy_levels() == [ [3, 4, 5, 4, 3], [4,",
"\"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991",
"def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines =",
"\"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() == [ [3,",
"[4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() ==",
"0, 5], [4, 0, 0, 0, 4], [3, 4, 5, 4, 3], ]",
"4], [3, 4, 5, 4, 3], ] assert cave.tick() == 0 assert cave.energy_levels()",
"4, 5, 4, 3], [4, 0, 0, 0, 4], [5, 0, 0, 0,",
"\"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def",
"assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines",
"11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() == [",
"assert cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656",
"0, 4], [3, 4, 5, 4, 3], ] assert cave.tick() == 0 assert",
"[5, 0, 0, 0, 5], [4, 0, 0, 0, 4], [3, 4, 5,",
"assert cave.tick() == 9 assert cave.energy_levels() == [ [3, 4, 5, 4, 3],",
"[4, 0, 0, 0, 4], [3, 4, 5, 4, 3], ] assert cave.tick()",
"11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9",
"[5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick()",
"== 0 assert cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines)",
"[ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave",
"9 assert cave.energy_levels() == [ [3, 4, 5, 4, 3], [4, 0, 0,",
"6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"])",
"5, 4, 3], ] assert cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4],",
"def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0 assert",
"= test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0 assert cave.tick() == 35",
"import * test_input = \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134",
"[6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert",
"test_input = \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526",
"test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data",
"5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]]",
"cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data =",
"assert cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4],",
"* test_input = \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554",
"== [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\")",
"day11 import * test_input = \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721",
"assert part1(lines) == 1656 def test_part2(): lines = test_input.strip().split(\"\\n\") assert part2(lines) == 195",
"def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick():",
"cave = Cave(lines) assert cave.tick() == 0 assert cave.tick() == 35 def test_part1():",
"0, 0, 4], [3, 4, 5, 4, 3], ] assert cave.tick() == 0",
"lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines = test_input.strip().split(\"\\n\") assert",
"35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines",
"Cave(lines) assert cave.tick() == 0 assert cave.tick() == 35 def test_part1(): lines =",
"cave.tick() == 0 assert cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert",
"Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111",
"0 assert cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) ==",
"= Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\"",
"6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\",",
"[4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave =",
"== [ [3, 4, 5, 4, 3], [4, 0, 0, 0, 4], [5,",
"5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave =",
"19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels()",
"6882881134 4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() ==",
"4, 3], [4, 0, 0, 0, 4], [5, 0, 0, 0, 5], [4,",
"0, 0, 4], [5, 0, 0, 0, 5], [4, 0, 0, 0, 4],",
"Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() == [ [3, 4, 5, 4,",
"cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def",
"0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes():",
"test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines = test_input.strip().split(\"\\n\") assert part2(lines) ==",
"[3, 4, 5, 4, 3], [4, 0, 0, 0, 4], [5, 0, 0,",
"test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0 assert cave.tick()",
"[[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\")",
"[4, 0, 0, 0, 4], [5, 0, 0, 0, 5], [4, 0, 0,",
"5, 4, 3], [4, 0, 0, 0, 4], [5, 0, 0, 0, 5],",
"4846848554 5283751526 \"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2],",
"test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data)",
"[5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ] def test_flashes(): lines = test_input.strip().split(\"\\n\") cave = Cave(lines)",
"4], [5, 0, 0, 0, 5], [4, 0, 0, 0, 4], [3, 4,",
"test_part1(): lines = test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines = test_input.strip().split(\"\\n\")",
"\"\"\" def test_cave_constructor(): cave = Cave([\"12\", \"34\"]) assert cave.energy_levels() == [[1,2], [3,4]] def",
"== 9 assert cave.energy_levels() == [ [3, 4, 5, 4, 3], [4, 0,",
"19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9 assert",
"cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991",
"cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5], [6,1,1,1,6], [5,1,1,1,5], [4,5,6,5,4], ]",
"= Cave(lines) assert cave.tick() == 0 assert cave.tick() == 35 def test_part1(): lines",
"assert cave.tick() == 0 assert cave.tick() == 35 def test_part1(): lines = test_input.strip().split(\"\\n\")",
"\"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() ==",
"4, 3], ] assert cave.tick() == 0 assert cave.energy_levels() == [ [4,5,6,5,4], [5,1,1,1,5],",
"test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0 assert cave.tick() == 35 def",
"lines = test_input.strip().split(\"\\n\") cave = Cave(lines) assert cave.tick() == 0 assert cave.tick() ==",
"4, 5, 4, 3], ] assert cave.tick() == 0 assert cave.energy_levels() == [",
"19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() ==",
"== [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991 11111",
"5], [4, 0, 0, 0, 4], [3, 4, 5, 4, 3], ] assert",
"def test_simple_tick(): test_data = \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave =",
"from day11 import * test_input = \"\"\" 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645",
"0, 4], [5, 0, 0, 0, 5], [4, 0, 0, 0, 4], [3,",
"= \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert cave.tick()",
"assert cave.energy_levels() == [[1,2], [3,4]] def test_simple_tick(): test_data = \"\"\" 11111 19991 19191",
"test_data = \"\"\" 11111 19991 19191 19991 11111 \"\"\".strip().split(\"\\n\") cave = Cave(test_data) assert",
"= test_input.strip().split(\"\\n\") assert part1(lines) == 1656 def test_part2(): lines = test_input.strip().split(\"\\n\") assert part2(lines)",
"= Cave(test_data) assert cave.tick() == 9 assert cave.energy_levels() == [ [3, 4, 5,"
] |
[
"import By class ProductForm: def __init__(self, app): self.app = app self._elements = Elements(app)",
"add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath = \"\"\"//span[contains(@class, \"quantity\")]\"\"\"",
"= \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath = \"\"\"//span[contains(@class, \"quantity\")]\"\"\" return self.app.wd.find_element_by_xpath(xpath)",
"app): self.app = app self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click()",
"self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) +",
"import expected_conditions as EC from selenium.webdriver.common.by import By class ProductForm: def __init__(self, app):",
"self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements:",
"__init__(self, app): self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath)",
"def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath = \"\"\"//span[contains(@class,",
"\"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app = app def add_to_cart_btn(self):",
"EC from selenium.webdriver.common.by import By class ProductForm: def __init__(self, app): self.app = app",
"class Elements: def __init__(self, app): self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name,",
"int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app",
"def __init__(self, app): self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return",
"<gh_stars>0 from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class ProductForm:",
"\"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app = app def add_to_cart_btn(self): xpath",
"app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath =",
"= self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class",
"Elements: def __init__(self, app): self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\"",
"= Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1",
"self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def",
"self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self):",
"app): self.app = app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def",
"def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class,",
"class ProductForm: def __init__(self, app): self.app = app self._elements = Elements(app) def add_product_to_cart(self):",
"__init__(self, app): self.app = app self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text",
"str(count))) class Elements: def __init__(self, app): self.app = app def add_to_cart_btn(self): xpath =",
"add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"),",
"selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class ProductForm: def __init__(self,",
"= app def add_to_cart_btn(self): xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath",
"from selenium.webdriver.common.by import By class ProductForm: def __init__(self, app): self.app = app self._elements",
"Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH,",
"= int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app):",
"xpath = \"\"\"//button[contains(@name, 'add_cart_product')]\"\"\" return self.app.wd.find_element_by_xpath(xpath) def quantity(self): xpath = \"\"\"//span[contains(@class, \"quantity\")]\"\"\" return",
"expected_conditions as EC from selenium.webdriver.common.by import By class ProductForm: def __init__(self, app): self.app",
"ProductForm: def __init__(self, app): self.app = app self._elements = Elements(app) def add_product_to_cart(self): quantity",
"def __init__(self, app): self.app = app self._elements = Elements(app) def add_product_to_cart(self): quantity =",
"quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count)))",
"1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app = app",
"self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app = app def",
"count = int(quantity) + 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self,",
"as EC from selenium.webdriver.common.by import By class ProductForm: def __init__(self, app): self.app =",
"selenium.webdriver.common.by import By class ProductForm: def __init__(self, app): self.app = app self._elements =",
"from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By class ProductForm: def",
"= app self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count =",
"+ 1 self.app.wait.until(EC.text_to_be_present_in_element((By.XPATH, \"\"\"//span[contains(@class, \"quantity\")]\"\"\"), str(count))) class Elements: def __init__(self, app): self.app =",
"By class ProductForm: def __init__(self, app): self.app = app self._elements = Elements(app) def",
"app self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count = int(quantity)",
"self.app = app self._elements = Elements(app) def add_product_to_cart(self): quantity = self._elements.quantity().text self._elements.add_to_cart_btn().click() count"
] |
[
"to django-db-queue for monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\":",
"init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root package and all sub-packages.",
"def get_version(package): \"\"\" Return package version as listed in `__version__` in `init.py`. \"\"\"",
"author = \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f:",
"filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files",
"get_version(package): \"\"\" Return package version as listed in `__version__` in `init.py`. \"\"\" init_py",
"themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath,",
"def get_packages(package): \"\"\" Return root package and all sub-packages. \"\"\" return [ dirpath",
"package = \"django_dbq_exports\" description = \"An extension to django-db-queue for monitoring long running",
"dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for",
"all sub-packages. \"\"\" return [ dirpath for dirpath, dirnames, filenames in os.walk(package) if",
"get_packages(package): \"\"\" Return root package and all sub-packages. \"\"\" return [ dirpath for",
"= \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension to django-db-queue for monitoring",
"open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\")",
"open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as",
"license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True, zip_safe=False, options={\"build\":",
"(dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames in os.walk(package) if",
"in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\",",
"-*- coding: utf-8 -*- from setuptools import setup import re import os import",
"for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package:",
"return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author,",
"`init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1",
"import os import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An",
"requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as listed in `__version__`",
"for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths =",
"f: readme = f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package):",
"= f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return",
"in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme,",
"get_package_data(package): \"\"\" Return all files under the root package, that are not in",
"setup import re import os import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\"",
"that are not in a package themselves. \"\"\" walk = [ (dirpath.replace(package +",
"] filepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename",
"f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as listed in `__version__` in `init.py`.",
"+ os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames in os.walk(package) if not",
"= [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames])",
"dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return",
"= ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root package and",
"return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root",
"os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files under the",
"os import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension",
"package and all sub-packages. \"\"\" return [ dirpath for dirpath, dirnames, filenames in",
"`__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py,",
"filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description,",
"return [ dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ]",
"[ (dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames in os.walk(package)",
"version as listed in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return",
"from setuptools import setup import re import os import sys name = \"django-db-queue-exports\"",
"\"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as",
"package themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep, \"\", 1), filenames) for",
"in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group(",
"readme = f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\"",
"in a package themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep, \"\", 1),",
"\"\"\" Return all files under the root package, that are not in a",
"package version as listed in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read()",
"filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url,",
"description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True, zip_safe=False, options={\"build\": {\"build_base\":",
"-*- from setuptools import setup import re import os import sys name =",
"setuptools import setup import re import os import sys name = \"django-db-queue-exports\" package",
"1), filenames) for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ]",
"Return root package and all sub-packages. \"\"\" return [ dirpath for dirpath, dirnames,",
"os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files under the root package,",
"\"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f: readme =",
"\"django_dbq_exports\" description = \"An extension to django-db-queue for monitoring long running jobs\" url",
") def get_packages(package): \"\"\" Return root package and all sub-packages. \"\"\" return [",
"long running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\"",
"os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath,",
"license = \"BSD\" with open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\") as",
"import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension to",
"sub-packages. \"\"\" return [ dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath,",
"long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True, zip_safe=False, options={\"build\": {\"build_base\": \"tmp_build\"}},",
"\"An extension to django-db-queue for monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls",
"os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base, filenames in",
"extension to django-db-queue for monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls =",
"filepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in",
"dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package):",
"files under the root package, that are not in a package themselves. \"\"\"",
"jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email =",
"import setup import re import os import sys name = \"django-db-queue-exports\" package =",
"if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files under the root",
"sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension to django-db-queue",
"def get_package_data(package): \"\"\" Return all files under the root package, that are not",
"base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths}",
"listed in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ =",
"project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\"",
"= \"django_dbq_exports\" description = \"An extension to django-db-queue for monitoring long running jobs\"",
"for filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license,",
"\"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files under the root package, that",
"filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths} setup(",
"as listed in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__",
"\"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension to django-db-queue for monitoring long",
"re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root package",
"= [ (dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames in",
"= \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license",
"a package themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep, \"\", 1), filenames)",
"not in a package themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep, \"\",",
"coding: utf-8 -*- from setuptools import setup import re import os import sys",
"Return package version as listed in `__version__` in `init.py`. \"\"\" init_py = open(os.path.join(package,",
"root package and all sub-packages. \"\"\" return [ dirpath for dirpath, dirnames, filenames",
"[ dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def",
"os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename)",
"in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base, filenames",
"\"\"\" Return root package and all sub-packages. \"\"\" return [ dirpath for dirpath,",
"for monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author",
"\"\"\" walk = [ (dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath, dirnames,",
"= f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as listed in `__version__` in",
"for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\"",
"\"BSD\" with open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\") as f: requirements",
"are not in a package themselves. \"\"\" walk = [ (dirpath.replace(package + os.sep,",
"as f: readme = f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def",
"#!/usr/bin/env python # -*- coding: utf-8 -*- from setuptools import setup import re",
"= \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f: readme = f.read() with",
"url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True,",
"{\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\")",
"Return all files under the root package, that are not in a package",
"dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all",
"init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def",
"{package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email,",
"long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True, zip_safe=False, options={\"build\": {\"build_base\": \"tmp_build\"}}, )",
"python # -*- coding: utf-8 -*- from setuptools import setup import re import",
"1 ) def get_packages(package): \"\"\" Return root package and all sub-packages. \"\"\" return",
"\"\", 1), filenames) for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\"))",
"django-db-queue for monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)}",
"utf-8 -*- from setuptools import setup import re import os import sys name",
"\"\"\" init_py = open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 )",
"package, that are not in a package themselves. \"\"\" walk = [ (dirpath.replace(package",
"\"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\")",
"running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email",
"in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] def get_package_data(package): \"\"\" Return all files under",
"all files under the root package, that are not in a package themselves.",
"f.read() with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package",
"with open(\"requirements.txt\") as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version",
"['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root package and all",
"f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as listed in",
"with open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\") as f: requirements =",
"open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\"",
"\"\"\" return [ dirpath for dirpath, dirnames, filenames in os.walk(package) if os.path.exists(os.path.join(dirpath, \"__init__.py\"))",
"as f: requirements = f.read().split(\"\\n\") def get_version(package): \"\"\" Return package version as listed",
"walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package),",
"version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[],",
"author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f: readme = f.read()",
"monitoring long running jobs\" url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author =",
"the root package, that are not in a package themselves. \"\"\" walk =",
"= \"An extension to django-db-queue for monitoring long running jobs\" url = \"https://www.dabapps.com/\"",
"\"\"\" Return package version as listed in `__version__` in `init.py`. \"\"\" init_py =",
"filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\",",
"if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base, filenames in walk:",
"# -*- coding: utf-8 -*- from setuptools import setup import re import os",
"project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements, classifiers=[], include_package_data=True, zip_safe=False,",
"dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = []",
"= \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with open(\"README.md\") as f: readme",
"not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base,",
"name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package), install_requires=requirements,",
"= \"BSD\" with open(\"README.md\") as f: readme = f.read() with open(\"requirements.txt\") as f:",
"filename) for filename in filenames]) return {package: filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls,",
"re import os import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description =",
"description = \"An extension to django-db-queue for monitoring long running jobs\" url =",
"= {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license = \"BSD\" with",
"url = \"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\"",
"filenames) for dirpath, dirnames, filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths",
"in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return {package: filepaths} setup( name=name,",
"root package, that are not in a package themselves. \"\"\" walk = [",
"under the root package, that are not in a package themselves. \"\"\" walk",
"= open(os.path.join(package, \"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package):",
"[] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for filename in filenames]) return",
"re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return root package and all sub-packages. \"\"\"",
"\"__init__.py\")) ] filepaths = [] for base, filenames in walk: filepaths.extend([os.path.join(base, filename) for",
"\"__init__.py\")).read() return re.search(\"^__version__ = ['\\\"]([^'\\\"]+)['\\\"]\", init_py, re.MULTILINE).group( 1 ) def get_packages(package): \"\"\" Return",
"filenames in os.walk(package) if not os.path.exists(os.path.join(dirpath, \"__init__.py\")) ] filepaths = [] for base,",
"filepaths} setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package),",
"import re import os import sys name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description",
"and all sub-packages. \"\"\" return [ dirpath for dirpath, dirnames, filenames in os.walk(package)",
"setup( name=name, version=get_version(package), url=url, project_urls=project_urls, license=license, description=description, long_description=readme, long_description_content_type=\"text/markdown\", author=author, author_email=author_email, packages=get_packages(package), package_data=get_package_data(package),",
"name = \"django-db-queue-exports\" package = \"django_dbq_exports\" description = \"An extension to django-db-queue for",
"] def get_package_data(package): \"\"\" Return all files under the root package, that are",
"walk = [ (dirpath.replace(package + os.sep, \"\", 1), filenames) for dirpath, dirnames, filenames",
"\"https://www.dabapps.com/\" project_urls = {\"Source\": \"https://github.com/dabapps/{}\".format(name)} author = \"DabApps\" author_email = \"<EMAIL>\" license ="
] |
[
"Unless required by applicable law or agreed to in writing, software # distributed",
"self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12,",
"Copyright (c) 2015 OpenStack Foundation. # All Rights Reserved. # # Licensed under",
"= mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason =",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"the License. You may obtain # a copy of the License at #",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10 self.ryu_df_adapter.register_table_handler( 10, self.mock_app.packet_in_handler) self.ryu_df_adapter.OF_packet_in_handler(ev)",
"port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock()",
"with the License. You may obtain # a copy of the License at",
"dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1)",
"self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self):",
"'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps",
"0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def",
"import base as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit",
"self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name",
"super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app =",
"ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson)",
"mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)])",
"secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock()",
"use this file except in compliance with the License. You may obtain #",
"language governing permissions and limitations # under the License. import mock from dragonflow.controller.ryu_base_app",
"self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule(",
"that all events are called correctly, both via the notify* functions, as well",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port',",
"implied. See the # License for the specific language governing permissions and limitations",
"TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify that all events are called",
"you may # not use this file except in compliance with the License.",
"= mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port',",
"= mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION =",
"= ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once",
"KIND, either express or implied. See the # License for the specific language",
"self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6)",
"= ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add",
"in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF",
"oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify that",
"file except in compliance with the License. You may obtain # a copy",
"router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock()",
"governing permissions and limitations # under the License. import mock from dragonflow.controller.ryu_base_app import",
"mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port',",
"This unit test has to verify that all events are called correctly, both",
"All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def",
"router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self):",
"permissions and limitations # under the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"these events will be done in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter,",
"self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock()",
"= dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port(",
"= RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port',",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9)",
"self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock()",
"self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3)",
"the # License for the specific language governing permissions and limitations # under",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"base as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"= mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler',",
"test has to verify that all events are called correctly, both via the",
"<reponame>FrankDuan/df_code # Copyright (c) 2015 OpenStack Foundation. # All Rights Reserved. # #",
"required by applicable law or agreed to in writing, software # distributed under",
"applicable law or agreed to in writing, software # distributed under the License",
"ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev =",
"ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port",
"from dragonflow.tests import base as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\"",
"ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev =",
"in compliance with the License. You may obtain # a copy of the",
"or agreed to in writing, software # distributed under the License is distributed",
"= [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4)",
"call these events will be done in the functional tests. \"\"\" def setUp(self):",
"import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify that all",
"2015 OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache",
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"events will be done in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp()",
"= 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)])",
"from ryu. Having ryu call these events will be done in the functional",
"all events are called correctly, both via the notify* functions, as well as",
"secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock()",
"mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler',",
"self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3),",
"secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port(",
"ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason",
"correctly, both via the notify* functions, as well as the events called from",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"Once notification is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock()",
"OpenStack Foundation. # All Rights Reserved. # # Licensed under the Apache License,",
"self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)])",
"= ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport",
"mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def",
"router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4),",
"ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name =",
"\"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter =",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([",
"the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF =",
"import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as tests_base from",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify that all events",
"specific language governing permissions and limitations # under the License. import mock from",
"tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to",
"'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app]",
"as well as the events called from ryu. Having ryu call these events",
"(c) 2015 OpenStack Foundation. # All Rights Reserved. # # Licensed under the",
"ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport',",
"unit test has to verify that all events are called correctly, both via",
"ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local',",
"self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE",
"agreed to in writing, software # distributed under the License is distributed on",
"notification is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id",
"local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2),",
"mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev",
"# Unless required by applicable law or agreed to in writing, software #",
"by applicable law or agreed to in writing, software # distributed under the",
"lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock()",
"License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as tests_base",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1),",
"'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps =",
"well as the events called from ryu. Having ryu call these events will",
"from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify",
"ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name)",
"mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([",
"import RyuDFAdapter from dragonflow.tests import base as tests_base from oslo_config import cfg class",
"RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule',",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"except in compliance with the License. You may obtain # a copy of",
"= mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([",
"notify* functions, as well as the events called from ryu. Having ryu call",
"to in writing, software # distributed under the License is distributed on an",
"the specific language governing permissions and limitations # under the License. import mock",
"self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason =",
"Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"both via the notify* functions, as well as the events called from ryu.",
"lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port test",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"= ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no),",
"mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule(",
"ryu call these events will be done in the functional tests. \"\"\" def",
"# not use this file except in compliance with the License. You may",
"# License for the specific language governing permissions and limitations # under the",
"secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath =",
"the events called from ryu. Having ryu call these events will be done",
"\"\"\" This unit test has to verify that all events are called correctly,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14,",
"mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule(",
"in writing, software # distributed under the License is distributed on an \"AS",
"class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has to verify that all events are",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([",
"self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port',",
"self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11,",
"self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch',",
"'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs):",
"self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock()",
"\"License\"); you may # not use this file except in compliance with the",
"test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10 self.ryu_df_adapter.register_table_handler( 10, self.mock_app.packet_in_handler) self.ryu_df_adapter.OF_packet_in_handler(ev) self.mock_app.assert_has_calls([mock.call.packet_in_handler(ev)])",
"mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name",
"'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args,",
"Reserved. # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev)",
"ryu. Having ryu call these events will be done in the functional tests.",
"not use this file except in compliance with the License. You may obtain",
"self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13)",
"self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8,",
"test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto =",
"[self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5)",
"cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port',",
"]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self):",
"License for the specific language governing permissions and limitations # under the License.",
"be done in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store =",
"will be done in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store",
"ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION",
"self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule(",
"#TODO(oanson) Once notification is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev =",
"verify that all events are called correctly, both via the notify* functions, as",
"added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04",
"'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load",
"called correctly, both via the notify* functions, as well as the events called",
"events are called correctly, both via the notify* functions, as well as the",
"'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def",
"OF ANY KIND, either express or implied. See the # License for the",
"self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15)",
"secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9,",
"port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added,",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"= mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock()",
"ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev)",
"tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter",
"(the \"License\"); you may # not use this file except in compliance with",
"mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD",
"self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6),",
"ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name)",
"the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as",
"# # Unless required by applicable law or agreed to in writing, software",
"called from ryu. Having ryu call these events will be done in the",
"= self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port test def",
"self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10, local_network_id=11)",
"from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as tests_base from oslo_config import",
"self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is",
"True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport",
"secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port(",
"ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self):",
"local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def",
"# Copyright (c) 2015 OpenStack Foundation. # All Rights Reserved. # # Licensed",
"and limitations # under the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from",
"License. You may obtain # a copy of the License at # #",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)])",
"ANY KIND, either express or implied. See the # License for the specific",
"self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port( router_port=10,",
"add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10 self.ryu_df_adapter.register_table_handler(",
"functions, as well as the events called from ryu. Having ryu call these",
"mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10),",
"def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name",
"= mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch',",
"'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load =",
"dragonflow.tests import base as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This",
"done in the functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock()",
"# All Rights Reserved. # # Licensed under the Apache License, Version 2.0",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name",
"mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath",
"See the # License for the specific language governing permissions and limitations #",
"self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7,",
"= mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)])",
"law or agreed to in writing, software # distributed under the License is",
"functional tests. \"\"\" def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock()",
"mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev",
"express or implied. See the # License for the specific language governing permissions",
"dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7,",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"the notify* functions, as well as the events called from ryu. Having ryu",
"test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev =",
"for the specific language governing permissions and limitations # under the License. import",
"mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14,",
"Foundation. # All Rights Reserved. # # Licensed under the Apache License, Version",
"test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10 self.ryu_df_adapter.register_table_handler( 10, self.mock_app.packet_in_handler)",
"via the notify* functions, as well as the events called from ryu. Having",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"RyuDFAdapter from dragonflow.tests import base as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase):",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"compliance with the License. You may obtain # a copy of the License",
"self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport =",
"local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev =",
"self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev)",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"to verify that all events are called correctly, both via the notify* functions,",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12,",
"secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8),",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock()",
"secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg =",
"may # not use this file except in compliance with the License. You",
"either express or implied. See the # License for the specific language governing",
"self.mock_app = mock.Mock(spec=[ 'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule',",
"= mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)])",
"'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load()",
"setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app",
"def setUp(self): super(TestRyuDFAdapter, self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store)",
"this file except in compliance with the License. You may obtain # a",
"self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport =",
"self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification is added, add update_local_port test def test_packet_in_handler(self):",
"**kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2)",
"# under the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import",
"or implied. See the # License for the specific language governing permissions and",
"local_network_id=11) self.ryu_df_adapter.notify_add_security_group_rule( secgroup=12, secgroup_rule=13) self.ryu_df_adapter.notify_remove_security_group_rule( secgroup=14, secgroup_rule=15) self.mock_app.assert_has_calls([ mock.call.update_logical_switch(lswitch=1), mock.call.remove_logical_switch(lswitch=2), mock.call.add_local_port(lport=3), mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5),",
"def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg = mock.Mock() ev.msg.datapath = mock.Mock() ev.msg.datapath.ofproto",
"mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev",
"limitations # under the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests",
"test_notifies(self): self.mock_app.reset_mock() self.ryu_df_adapter.notify_update_logical_switch(lswitch=1) self.ryu_df_adapter.notify_remove_logical_switch(lswitch=2) self.ryu_df_adapter.notify_add_local_port(lport=3) self.ryu_df_adapter.notify_remove_local_port(lport=4) self.ryu_df_adapter.notify_add_remote_port(lport=5) self.ryu_df_adapter.notify_remove_remote_port(lport=6) self.ryu_df_adapter.notify_add_router_port( router=7, router_port=8, local_network_id=9) self.ryu_df_adapter.notify_remove_router_port(",
"as tests_base from oslo_config import cfg class TestRyuDFAdapter(tests_base.BaseTestCase): \"\"\" This unit test has",
"= self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([mock.call.add_local_port(lport=lport)]) lport.assert_has_calls([ mock.call.set_external_value('ofport', ev.msg.desc.port_no), mock.call.set_external_value('is_local', True)]) self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason",
"dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as tests_base from oslo_config import cfg",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"'update_logical_switch', 'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler'",
"update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id = 10 self.ryu_df_adapter.register_table_handler( 10,",
"is added, add update_local_port test def test_packet_in_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.table_id =",
"self).setUp() self.db_store = mock.Mock() cfg.CONF = mock.Mock() self.ryu_df_adapter = RyuDFAdapter(db_store=self.db_store) self.mock_app = mock.Mock(spec=[",
"'remove_logical_switch', 'add_local_port', 'remove_local_port', 'add_remote_port', 'remove_remote_port', 'add_router_port', 'remove_router_port', 'add_security_group_rule', 'remove_security_group_rule', 'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ])",
"Having ryu call these events will be done in the functional tests. \"\"\"",
"mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev)",
"as the events called from ryu. Having ryu call these events will be",
"mock.call.remove_local_port(lport=4), mock.call.add_remote_port(lport=5), mock.call.remove_remote_port(lport=6), mock.call.add_router_port( local_network_id=9, router=7, router_port=8), mock.call.remove_router_port( local_network_id=11, router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13),",
"ev.msg.datapath.ofproto.OFPPR_DELETE self.ryu_df_adapter._port_status_handler(ev) port_name = ev.msg.desc.name lport = self.db_store.get_local_port_by_name(port_name) self.mock_app.assert_has_calls([ mock.call.remove_local_port(lport=lport)]) #TODO(oanson) Once notification",
"def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock() ev = mock.Mock() self.ryu_df_adapter.port_desc_stats_reply_handler(ev) self.mock_app.assert_has_calls([ mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev",
"'switch_features_handler', 'port_desc_stats_reply_handler', 'packet_in_handler' ]) def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"has to verify that all events are called correctly, both via the notify*",
"events called from ryu. Having ryu call these events will be done in",
"mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base as tests_base from oslo_config",
"def dispatcher_load(*args, **kwargs): self.ryu_df_adapter.dispatcher.apps = [self.mock_app] self.ryu_df_adapter.dispatcher.load = dispatcher_load self.ryu_df_adapter.load() def test_notifies(self): self.mock_app.reset_mock()",
"router_port=10), mock.call.add_security_group_rule( secgroup=12, secgroup_rule=13), mock.call.remove_security_group_rule( secgroup=14, secgroup_rule=15)]) def test_switch_features_handler(self): self.mock_app.reset_mock() ev = mock.Mock()",
"under the License. import mock from dragonflow.controller.ryu_base_app import RyuDFAdapter from dragonflow.tests import base",
"are called correctly, both via the notify* functions, as well as the events",
"mock.call.port_desc_stats_reply_handler(ev)]) def test_port_status_handler(self): self.mock_app.reset_mock() ev = mock.Mock() ev.msg.reason = ev.msg.datapath.ofproto.OFPPR_ADD self.ryu_df_adapter._port_status_handler(ev) port_name =",
"= mock.Mock() ev.msg.datapath.ofproto = mock.Mock() ev.msg.datapath.ofproto.OFP_VERSION = 0x04 self.ryu_df_adapter.switch_features_handler(ev) self.mock_app.assert_has_calls([mock.call.switch_features_handler(ev)]) def test_port_desc_stats_reply_handler(self): self.mock_app.reset_mock()"
] |
[
"= [val for key, val in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"]",
"distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\"))",
"= [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or",
"functions.\"\"\" import gzip import logging import os import platform import re import shlex",
"key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) #",
"# In addition form useful information parsed from the # above command line",
"that is licensed under separate terms, # as designated in a particular file",
"MySQL information about libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config):",
"\"commit\": push_rev, \"short\": push_rev[:7] } return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC.",
"not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not found)\") sys.exit(1) #",
"return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the",
"could not be read. OSError: when execute on none-Windows platform. Returns: bool: True",
"above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume",
"stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev =",
"Returns: str: The distribution name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if",
"not stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the",
"the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding",
"in the foregoing, this file, # which is part of MySQL Connector/Python, is",
"%z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version:",
"documentation. The authors of MySQL hereby grant you an # additional permission to",
"useful information parsed from the # above command line parsed_line = _parse_mysql_info_line(mc_val) if",
"\"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not",
"distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.spawn import find_executable from distutils.sysconfig",
"mysql_config tool. Returns: dict: A dict containing the information about the last commit.",
"urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT",
"range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements to",
"warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the",
"should have received a copy of the GNU General Public License # along",
"if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\",",
"file. Returns: tuple: A tuple with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\",",
"for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"',",
"foregoing, this file, # which is part of MySQL Connector/Python, is also subject",
"have a value # in the next element in the list if pre_parsed_line:",
"on Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if",
"import LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom import parse, parseString try:",
"or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")]",
"link the program and your derivative works # with the separately licensed software",
"authors of MySQL hereby grant you an # additional permission to link the",
"if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release",
"ImportError: from urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33 else",
"in a particular file or component or in included license # documentation. The",
"val in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries:",
"And finally the information of ``/etc/os-release`` file. Returns: tuple: A tuple with (`name`,",
"(dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file =",
"try to get the information of ``lsb-release`` command. And finally the information of",
"\"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER =",
"element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_: return element elif id_: if",
"the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": #",
"shlex.split(line) # Find out what kind of argument it is first, # if",
"Try to figure out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32",
"Copyright (c) 2020, Oracle and/or its affiliates. # # This program is free",
"are added. This might of course fail. info = {} for line in",
"is enough # for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key,",
"children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit)",
"import mkpath from distutils.file_util import copy_file from distutils.spawn import find_executable from distutils.sysconfig import",
"= [val for _, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \"",
"# it under the terms of the GNU General Public License, version 2.0,",
"except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\")",
"import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import",
"\"\"\" args = shlex.split(line) # Find out what kind of argument it is",
"get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info:",
"with # MySQL. # # Without limiting anything contained in the foregoing, this",
"FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License, version",
"for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key =",
"if not source_only_dist or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname:",
"A dict containing the information about the last commit. \"\"\" is_git_repo = False",
"product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64 bit",
"Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64",
"# You should have received a copy of the GNU General Public License",
"= [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: #",
"2.0, for more details. # # You should have received a copy of",
"MySQL information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr =",
"= [val for key, val in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs:",
"We always add the raw output from the different \"mysql_config\" # options. And",
"MySQL Connector/Python, is also subject to the # Universal FOSS Exception, version 1.0,",
"MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of the installer is only",
"that they have included with # MySQL. # # Without limiting anything contained",
"'mysql-html.css', ] for file_name in doc_files: # Check if we have file in",
"IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def",
"parsed_line = [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1:",
"Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip()))",
"the separately licensed software that they have included with # MySQL. # #",
"about the last commit. \"\"\" is_git_repo = False if find_executable(\"git\") is not None:",
"Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip",
"= pre_parsed_line.pop(0) if \"=\" in opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\"",
"name and \\ element.getAttribute('Id') == id_: return element elif id_: if element.getAttribute('Id') ==",
"\"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import os import platform import re",
"Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\"",
"distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\"))",
"or in included license # documentation. The authors of MySQL hereby grant you",
"in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\":",
"mc_val) and \"=\" not in mc_val: # Not a Unix command line continue",
"elements: if name and id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id') ==",
"value # in the next element in the list if pre_parsed_line: (type2, opt2)",
"cases, like \"port\", \"socket\", that is enough # for use from Python. info[mc_key]",
"\"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ': raise",
"distribution name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version))",
"mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name",
"dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)):",
"# See the GNU General Public License, version 2.0, for more details. #",
"info[\"libraries\"] = [val for key, val in parsed_line if key in (\"l\", \"library\",)]",
"64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path,",
"for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions. Args: xml_path (str): The",
"if branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev,",
"subprocess import struct import sys import tarfile from datetime import datetime from distutils.errors",
"fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if",
"= dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode =",
"_parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command. Returns: A dictionary containing release",
"# options. And in some cases, like \"port\", \"socket\", that is enough #",
"\"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file,",
"# Universal FOSS Exception, version 1.0, a copy of which can be found",
"be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in the",
"os.path.exists(doc_file): # it might be in build/ doc_file = os.path.join('build', file_name) if not",
"to \" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a",
"program; if not, write to the Free Software Foundation, Inc., # 51 Franklin",
"os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\") as",
"True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\" dom_tree =",
"_, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key",
"if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def",
"xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0]",
"documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html',",
"Returns: bool: True if is a 64 bit library. \"\"\" if os.name !=",
"if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"]))",
"\"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION",
"in doc_files: # Check if we have file in docs/ doc_file = os.path.join('docs',",
"element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True):",
"import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.spawn import",
"end. Returns: str: The distribution name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition)",
"MySQL C API installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version",
"else num for num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information",
"return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written",
"as fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version =",
"\"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not",
"doc_files: # Check if we have file in docs/ doc_file = os.path.join('docs', file_name)",
"= _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else",
"LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key,",
"add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s",
"= value return distro def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command.",
"c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"'",
"header is invalid. IOError: When file could not be read. OSError: when execute",
"uncompressed. Returns the path to the folder of the first unarchived member. Returns",
"be perfect without special knowledge about all possible command lines \"mysql_config\" might output.",
"under separate terms, # as designated in a particular file or component or",
"(bool): Add the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No",
"should be close enough for our usage. \"\"\" args = shlex.split(line) # Find",
"def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions. Args:",
"type2 == \"\" and \"=\" not in opt2: # Value was in the",
"' installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional",
"[\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _",
"Try to be future safe in case new options # are added. This",
"files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css',",
"Public License, version 2.0, for more details. # # You should have received",
"\"\"\" distro = {} if os.path.exists(release_file): with open(release_file) as file_obj: for line in",
"{}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate",
"%s\", \" \".join(info[\"libraries\"])) # Try to figure out the architecture info[\"arch\"] = \"x86_64\"",
"MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now =",
"# We have an option that might have a value # in the",
"!= b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] #",
"tarball. If the tarball has the extension '.gz', it will be first uncompressed.",
"dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip()",
"in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\":",
"\"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info =",
"that might # have a value val = opt1[1:] if val: parsed_line.append((opt1[:1], val))",
"first unarchived member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball)",
"\"x86_64\" if sys.maxsize > 2**32 else \"i386\" # Return a tuple for version",
"have it, create a fake one LOGGER.warning(\"documentation '%s' does not exist; creating\" \"",
"the egg file. The Python version is excluded from the name when source_only_dist",
"not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files:",
"command lines \"mysql_config\" might output. But it should be close enough for our",
"have a value val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else:",
"info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get",
"Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic",
"[] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line =",
"if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000):",
"os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar",
"'') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file",
"parse_qsl except ImportError: from urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize >",
"a value val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could",
"distribution name. First try to get information from ``/etc/lsb-release`` file. If it fails,",
"docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was",
"try: from urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl ARCH =",
"a tarball. Unarchives the given tarball. If the tarball has the extension '.gz',",
"of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is",
"with open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except",
"{} for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key",
"Returns: A dictionary containing release information. \"\"\" distro = {} if os.path.exists(release_file): with",
"# This program is free software; you can redistribute it and/or modify #",
"\"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get",
"This might of course fail. info = {} for line in stdout.splitlines(): re_obj",
"written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as",
"parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"]",
"the output of the lsb_release command. Returns: A dictionary containing release information. \"\"\"",
"release information. \"\"\" distro = {} with open(os.devnull, \"w\") as devnull: try: stdout",
"file_name) if not os.path.exists(doc_file): # it might be in build/ doc_file = os.path.join('build',",
"element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": # If \"--\" and",
"implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See",
"\"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an option",
"git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\")",
"python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the",
"the last commit. \"\"\" is_git_repo = False if find_executable(\"git\") is not None: #",
"= key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution(): \"\"\"Try to determine the",
"= parse(xml_path) if for32: LOGGER.info(\"No elements to add for 32bit msi\") else: LOGGER.info(\"Adding",
"info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN.",
"name usually used for creating the egg file. The Python version is excluded",
"the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #",
"copy_file(doc_file, doc_path) # Windows MSI descriptor parser # Customization utility functions for the",
"Public License, version 2.0, as # published by the Free Software Foundation. #",
"element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties",
"LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not",
"Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check, only install if",
"not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't",
"elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\")",
"0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return",
"from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if",
"it will be useful, but # WITHOUT ANY WARRANTY; without even the implied",
"VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the",
"Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist:",
"# Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if",
"new options # are added. This might of course fail. info = {}",
"except ImportError: from urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33",
"conditions elements to the xml msi descriptor.\"\"\" # Get the Product xml element",
"2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0)",
"Args: xml_path (str): The original xml msi descriptor path. result_path (str): Path to",
"if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config)",
"\".join(info[\"libraries\"])) # Try to figure out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize",
"line in lines: key_value = line.split(\":\") if len(key_value) != 2: continue key =",
"resulting xml. add_vs_redist (bool): Add the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path)",
"for more details. # # You should have received a copy of the",
"_get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element defined on Product.\"\"\" product =",
"member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir:",
"key_value = line.split(\"=\") if len(key_value) != 2: continue key = key_value[0].lower() value =",
"= tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name",
"[ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: # Check if we",
"if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def",
"list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 == \"\" and \"=\"",
"distro[key] = value return distro def linux_distribution(): \"\"\"Try to determine the name of",
"if for32: LOGGER.info(\"No elements to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\")",
"open(mysql_version_h, \"rb\") as fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line:",
"re.search(r\"^-\", mc_val) and \"=\" not in mc_val: # Not a Unix command line",
"the distribution name. Get the distribution name usually used for creating the egg",
"distutils.version import LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom import parse, parseString",
"for num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information about the",
"ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions.",
"# published by the Free Software Foundation. # # This program is also",
"\"\"\"Get MySQL information without using mysql_config tool. Returns: dict: A dict containing the",
"# This program is also distributed with certain software (including # but not",
"product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64)",
"for creating the egg file. The Python version is excluded from the name",
"# Windows MSI descriptor parser # Customization utility functions for the C/py product",
"Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires",
"suitable to' ' run on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>'",
"then it is a # traditional one character option name that might #",
"the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else \"i386\" # Return",
"have included with # MySQL. # # Without limiting anything contained in the",
"when it is given at the end. Returns: str: The distribution name. \"\"\"",
"datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import copy_file",
"the output. Try to be future safe in case new options # are",
"tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the",
"St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import",
"num for num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information about",
"install the Redistributable then run this' ' installer again.\">' ' Installed OR VS14REDIST'",
"affiliates. # # This program is free software; you can redistribute it and/or",
"This program is distributed in the hope that it will be useful, but",
"1.0, a copy of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # #",
"fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c:",
"= line.split(\":\") if len(key_value) != 2: continue key = key_value[0].replace(\" \", \"_\").lower() value",
"along with this program; if not, write to the Free Software Foundation, Inc.,",
"result_path (str): Path to save the resulting xml. add_vs_redist (bool): Add the VS",
"= os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might be in build/ doc_file",
"`docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"),",
"connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool.",
"terms, # as designated in a particular file or component or in included",
"if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 == \"\" and \"=\" not",
"\"\"\"Get the distribution name. Get the distribution name usually used for creating the",
"unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes():",
"\\ element.getAttribute('Id') == id_: return element elif id_: if element.getAttribute('Id') == id_: return",
"== id_: return element elif id_: if element.getAttribute('Id') == id_: return element def",
"'<Condition Message=\"This application requires Visual Studio 2015' ' Redistributable. Please install the Redistributable",
"= proc.returncode == 0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\",",
"Unix command line continue # In addition form useful information parsed from the",
"Get the distribution name usually used for creating the egg file. The Python",
"GNU General Public License, version 2.0, as # published by the Free Software",
"unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball. If the tarball has the",
"only suitable to' ' run on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64",
"distribution name usually used for creating the egg file. The Python version is",
"bit or not. Raises: ValueError: When magic of header is invalid. IOError: When",
"assume all arguments are paths with \"-I\", \"--include\",.. include_dirs = [val for _,",
"= Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not stdout: raise ValueError(\"Error",
"if not os.path.exists(doc_file): # it might be in build/ doc_file = os.path.join('build', file_name)",
"info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release",
"if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not found)\") sys.exit(1)",
"= re_obj.group(1) mc_val = re_obj.group(2) # We always add the raw output from",
"info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file. Returns:",
"= struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine",
"the information about the last commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi,",
"= dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] =",
"line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume all arguments",
"return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return",
"if name and id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_:",
"doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might be in build/",
"version with open(mysql_version_h, \"rb\") as fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\"",
"} return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if",
"to determine the name of the Linux OS distribution name. First try to",
"tuple([int(num) if num.isdigit() else num for num in info[\"version\"].split(\".\")]) return info def get_git_info():",
"additional permission to link the program and your derivative works # with the",
"first uncompressed. Returns the path to the folder of the first unarchived member.",
"tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files:",
"= ( '<Product>' '<!-- Check Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">'",
"\"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no \"=\" handled above) then it",
"files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball. If",
"info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] =",
"(Optional[str]): The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\"",
"information about the last commit. Returns: dict: A dict containing the information about",
"os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\":",
"received a copy of the GNU General Public License # along with this",
"Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA",
"distro = {} with open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\",",
"And in some cases, like \"port\", \"socket\", that is enough # for use",
"return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC`",
"new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close()",
"in case new options # are added. This might of course fail. info",
"to the # Universal FOSS Exception, version 1.0, a copy of which can",
"parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool. Returns: dict: A",
"tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall()",
"02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import os import platform",
"= [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout,",
"\"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo: cmd = [\"git\",",
"dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to add for 32bit msi\") else:",
"= open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name)",
"write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True``",
"The original xml msi descriptor path. result_path (str): Path to save the resulting",
"enough for our usage. \"\"\" args = shlex.split(line) # Find out what kind",
"from distutils.spawn import find_executable from distutils.sysconfig import get_python_version from distutils.version import LooseVersion from",
"the next element in the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if",
"0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015 property",
"last commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not",
"or component or in included license # documentation. The authors of MySQL hereby",
"if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version)",
"A dict containing the information about the last commit. \"\"\" info = {}",
"parser # Customization utility functions for the C/py product msi descriptor def _win_dll_is64bit(dll_file):",
"ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try to",
"of argument it is first, # if starts with \"--\", \"-\" or nothing",
"# # Without limiting anything contained in the foregoing, this file, # which",
"not re.search(r\"^-\", mc_val) and \"=\" not in mc_val: # Not a Unix command",
"OS is 64bit. Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version",
"that might have a value # in the next element in the list",
"ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header",
"id_=None): \"\"\"Get a xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements =",
"num.isdigit() else num for num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git",
"release information. \"\"\" distro = {} if os.path.exists(release_file): with open(release_file) as file_obj: for",
"dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit",
"from distutils.sysconfig import get_python_version from distutils.version import LooseVersion from subprocess import Popen, PIPE",
"information. \"\"\" distro = {} with open(os.devnull, \"w\") as devnull: try: stdout =",
"save the resulting xml. add_vs_redist (bool): Add the VS redistributable requirement. \"\"\" dom_msi",
"C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64",
"os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1],",
"return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro:",
"a Windows DLL is 64 bit or not. Raises: ValueError: When magic of",
"\"=\" not in opt2: # Value was in the next list element parsed_line.append((opt1,",
"the GNU General Public License, version 2.0, as # published by the Free",
"with \"--\", \"-\" or nothing pre_parsed_line = [] for arg in args: re_obj",
"exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy",
"element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and",
"mkpath from distutils.file_util import copy_file from distutils.spawn import find_executable from distutils.sysconfig import get_python_version",
"tool. Returns: dict: A dict containing the information about the last commit. \"\"\"",
"copy_file from distutils.spawn import find_executable from distutils.sysconfig import get_python_version from distutils.version import LooseVersion",
"the GNU General Public License # along with this program; if not, write",
"later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"]",
"= [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll",
"using mysql_config tool. Returns: dict: A dict containing the information about the last",
"is given at the end. Returns: str: The distribution name. \"\"\" name =",
"is an option like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no \"=\"",
"offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) =",
"= (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes",
"certain software (including # but not limited to OpenSSL) that is licensed under",
"might output. But it should be close enough for our usage. \"\"\" args",
"program and your derivative works # with the separately licensed software that they",
"# 64bit Conditional check, only install if OS is 64bit. Used in MSI-64",
"the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to",
"info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return",
"from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val)",
"for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append",
"terms of the GNU General Public License, version 2.0, as # published by",
"= {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C",
"True. The platname will be added when it is given at the end.",
"Visual Studio 2015' ' Redistributable. Please install the Redistributable then run this' '",
"can redistribute it and/or modify # it under the terms of the GNU",
"file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c: #",
"re_obj.group(2) # We always add the raw output from the different \"mysql_config\" #",
"return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\") if",
"``/etc/lsb-release`` file. If it fails, try to get the information of ``lsb-release`` command.",
"the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 == \"\" and",
"open(release_file) as file_obj: for line in file_obj: key_value = line.split(\"=\") if len(key_value) !=",
"def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64 bit or not. Raises:",
"False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml):",
"Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo: cmd",
"some cases, like \"port\", \"socket\", that is enough # for use from Python.",
"if \"=\" in opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1)))",
"False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns:",
"from distutils.version import LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom import parse,",
"above) then it is a # traditional one character option name that might",
"(distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return",
"tarball has the extension '.gz', it will be first uncompressed. Returns the path",
"Without limiting anything contained in the foregoing, this file, # which is part",
"[val for key, val in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] =",
"key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution(): \"\"\"Try to determine the name",
"not. Raises: ValueError: When magic of header is invalid. IOError: When file could",
"path. result_path (str): Path to save the resulting xml. add_vs_redist (bool): Add the",
"_mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\",",
"'%s' does not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file):",
"info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"]))",
"redistribute it and/or modify # it under the terms of the GNU General",
"git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None,",
"find_executable(\"git\") is not None: # Check if it's a Git repository proc =",
"starts with \"--\", \"-\" or nothing pre_parsed_line = [] for arg in args:",
"bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse",
"`docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"),",
"with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version:",
"struct import sys import tarfile from datetime import datetime from distutils.errors import DistutilsInternalError",
"branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info return None def",
"in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using",
"tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for",
"Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility",
"special knowledge about all possible command lines \"mysql_config\" might output. But it should",
"parseString try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW =",
"not in mc_val: # Not a Unix command line continue # In addition",
"mc_val = re_obj.group(2) # We always add the raw output from the different",
"lines: key_value = line.split(\":\") if len(key_value) != 2: continue key = key_value[0].replace(\" \",",
"opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool.",
"sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball. If the tarball",
"gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar",
"' Redistributable. Please install the Redistributable then run this' ' installer again.\">' '",
"msi descriptor path. result_path (str): Path to save the resulting xml. add_vs_redist (bool):",
"ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\")",
"= {} with open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"),",
"(type2, opt2) = pre_parsed_line[0] if type2 == \"\" and \"=\" not in opt2:",
"C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"]",
"Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode ==",
"= \"x86_64\" if sys.maxsize > 2**32 else \"i386\" # Return a tuple for",
"NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from urllib.parse import parse_qsl",
"Find out what kind of argument it is first, # if starts with",
"continue if type1 == \"--\": # If \"--\" and no argument then it",
"'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return",
"magic of header is invalid. IOError: When file could not be read. OSError:",
"product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements: if name and",
"import shlex import subprocess import struct import sys import tarfile from datetime import",
"Value was in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1",
"from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import copy_file from",
"fail. info = {} for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\"))",
"line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1)",
"to figure out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else",
"but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY",
"\"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return info def",
"Connector/Python, is also subject to the # Universal FOSS Exception, version 1.0, a",
"a value # in the next element in the list if pre_parsed_line: (type2,",
"\"\"\"Unarchive a tarball. Unarchives the given tarball. If the tarball has the extension",
"file or component or in included license # documentation. The authors of MySQL",
"bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info() if git_info:",
"libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config,",
"containing the information about the last commit. \"\"\" is_git_repo = False if find_executable(\"git\")",
"is a 64 bit library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only",
"if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor",
"Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product,",
"useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of #",
"out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else \"i386\" #",
"push_rev[:7] } return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True``",
"not os.path.exists(doc_file): # it might be in build/ doc_file = os.path.join('build', file_name) if",
"= fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386",
"Not a Unix command line continue # In addition form useful information parsed",
"file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664,",
"id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions elements",
"platform import re import shlex import subprocess import struct import sys import tarfile",
"of the lsb_release command. Returns: A dictionary containing release information. \"\"\" distro =",
"dict: Containing MySQL information about libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config)",
"and conditions elements to the xml msi descriptor.\"\"\" # Get the Product xml",
"if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\")",
"msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element defined on",
"# documentation. The authors of MySQL hereby grant you an # additional permission",
"= [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit =",
"re_obj.group(1) mc_val = re_obj.group(2) # We always add the raw output from the",
"if a Windows DLL is 64 bit or not. Raises: ValueError: When magic",
"val in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key,",
"requires Visual Studio 2015' ' Redistributable. Please install the Redistributable then run this'",
"platform. Returns: bool: True if is a 64 bit library. \"\"\" if os.name",
"import gzip import logging import os import platform import re import shlex import",
"for line in lines: key_value = line.split(\":\") if len(key_value) != 2: continue key",
"software that they have included with # MySQL. # # Without limiting anything",
"License, version 2.0, for more details. # # You should have received a",
"only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent",
"doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) #",
"command line. This will never be perfect without special knowledge about all possible",
"tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name))",
"output of the lsb_release command. Returns: A dictionary containing release information. \"\"\" distro",
"# 64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!--",
"type1: # We have an option that might have a value # in",
"\"-\" (and no \"=\" handled above) then it is a # traditional one",
"def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball. If the tarball has",
"This program is free software; you can redistribute it and/or modify # it",
"urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl ARCH = \"64-bit\" if",
"name and id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_: return",
"tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz',",
"create a fake one LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\", doc_file)",
"not in opt2: # Value was in the next list element parsed_line.append((opt1, opt2))",
"# # This program is free software; you can redistribute it and/or modify",
"Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of the installer",
"= os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \"",
"\"short\": push_rev[:7] } return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool:",
"val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle",
"always add the raw output from the different \"mysql_config\" # options. And in",
"os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\"",
"be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of",
"which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed",
"or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an option that might",
"if element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_: return element elif id_:",
"in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information about the last commit.",
"The Python version is excluded from the name when source_only_dist is True. The",
"and/or modify # it under the terms of the GNU General Public License,",
"if type2 == \"\" and \"=\" not in opt2: # Value was in",
"\"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\",",
"is excluded from the name when source_only_dist is True. The platname will be",
"Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S",
"= shlex.split(line) # Find out what kind of argument it is first, #",
"if e_magic != b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\",",
"we do not have it, create a fake one LOGGER.warning(\"documentation '%s' does not",
"is licensed under separate terms, # as designated in a particular file or",
"MSI descriptor parser # Customization utility functions for the C/py product msi descriptor",
"traditional one character option name that might # have a value val =",
"0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64",
"not be read. OSError: when execute on none-Windows platform. Returns: bool: True if",
"version is excluded from the name when source_only_dist is True. The platname will",
"\" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file,",
"designated in a particular file or component or in included license # documentation.",
"output from the different \"mysql_config\" # options. And in some cases, like \"port\",",
".split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src",
"import parse_qsl except ImportError: from urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize",
"Git information about the last commit. Returns: dict: A dict containing the information",
"info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse",
"= Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo:",
"info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None):",
"element.getAttribute('Id') == id_: return element elif id_: if element.getAttribute('Id') == id_: return element",
"info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL",
"was written successfully. \"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\")",
"file. The Python version is excluded from the name when source_only_dist is True.",
"# We always add the raw output from the different \"mysql_config\" # options.",
"a Unix command line continue # In addition form useful information parsed from",
"_parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume all arguments are paths with",
"git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src",
"without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR",
"val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1,",
"> 2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0,",
"without special knowledge about all possible command lines \"mysql_config\" might output. But it",
"a copy of the GNU General Public License # along with this program;",
"2015' ' Redistributable. Please install the Redistributable then run this' ' installer again.\">'",
"val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key ==",
"Windows DLL is 64 bit or not. Raises: ValueError: When magic of header",
"with open(mysql_version_h, \"rb\") as fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in",
"[os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit:",
"in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val in parsed_line if key",
"to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml",
"You should have received a copy of the GNU General Public License #",
"\"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def",
"of the installer is only suitable to' ' run on 64 bit operating",
"successfully. \"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src:",
"edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver =",
"\"\"\"Add the architecture dependent properties and conditions. Args: xml_path (str): The original xml",
"info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL",
"program is distributed in the hope that it will be useful, but #",
"a tuple for version instead of a string info[\"version\"] = tuple([int(num) if num.isdigit()",
"LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION:",
"os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h",
"return False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node,",
"0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc =",
"MySQL information without using mysql_config tool. Returns: dict: A dict containing the information",
"LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure out",
"else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi):",
"= \"x86_64\" if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information",
"proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\",",
"LOGGER.info(\"No elements to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist)",
"Studio 2015' ' Redistributable. Please install the Redistributable then run this' ' installer",
"form useful information parsed from the # above command line parsed_line = _parse_mysql_info_line(mc_val)",
"This program is also distributed with certain software (including # but not limited",
"included license # documentation. The authors of MySQL hereby grant you an #",
"API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] =",
"different \"mysql_config\" # options. And in some cases, like \"port\", \"socket\", that is",
"\"\"\"Get a xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name)",
"# which is part of MySQL Connector/Python, is also subject to the #",
"info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit",
"dict containing the information about the last commit. \"\"\" info = {} mysql_version_h",
"of the first unarchived member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name)",
"bit library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\")",
"if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents",
"The distribution name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label))",
"command line continue # In addition form useful information parsed from the #",
"continue # In addition form useful information parsed from the # above command",
"_win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\"",
"file_name in doc_files: # Check if we have file in docs/ doc_file =",
"in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line:",
"include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for",
"raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try",
"line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool. Returns:",
"the information of ``/etc/os-release`` file. Returns: tuple: A tuple with (`name`, `version`, `codename`)",
"get_python_version from distutils.version import LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom import",
"if not, write to the Free Software Foundation, Inc., # 51 Franklin St,",
"it under the terms of the GNU General Public License, version 2.0, as",
"The authors of MySQL hereby grant you an # additional permission to link",
"_add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\") as",
"key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse the output of the",
"parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": # If \"--\" and no",
"/>' '</Property>' '<Condition Message=\"This application requires Visual Studio 2015' ' Redistributable. Please install",
"mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation",
"datetime.now() try: from urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl ARCH",
"elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append",
"git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return",
"a fake one LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\", doc_file) open(doc_file,",
"LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr",
"\"\"\"Check if a Windows DLL is 64 bit or not. Raises: ValueError: When",
"the distribution name usually used for creating the egg file. The Python version",
"64 bit or not. Raises: ValueError: When magic of header is invalid. IOError:",
"# Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\")",
"\"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date:",
">=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will never",
"separate terms, # as designated in a particular file or component or in",
"licensed software that they have included with # MySQL. # # Without limiting",
"distro def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command. Returns: A dictionary",
"(`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"),",
"License, version 2.0, as # published by the Free Software Foundation. # #",
"branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\":",
"\"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date:",
"FOSS Exception, version 1.0, a copy of which can be found at #",
"derivative works # with the separately licensed software that they have included with",
"the xml msi descriptor.\"\"\" # Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0]",
"application requires Visual Studio 2015' ' Redistributable. Please install the Redistributable then run",
"to save the resulting xml. add_vs_redist (bool): Add the VS redistributable requirement. \"\"\"",
"\"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\",",
"or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License,",
"doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [",
"Conditional check, only install if OS is 64bit. Used in MSI-64 ONLY_64bit =",
"when source_only_dist is True. The platname will be added when it is given",
"# MySQL. # # Without limiting anything contained in the foregoing, this file,",
"it is an option like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no",
"lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\") if len(key_value) !=",
"= python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return",
"elements to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving",
"and id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_: return element",
"about all possible command lines \"mysql_config\" might output. But it should be close",
"universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"]",
"and no argument then it is an option like \"--fast\" parsed_line.append(opt1) else: #",
"addition form useful information parsed from the # above command line parsed_line =",
"MySQL version with open(mysql_version_h, \"rb\") as fp: for line in fp.readlines(): if b\"#define",
"is 64bit. Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of",
"the last commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if",
"= os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process = Popen([mysql_config],",
"you an # additional permission to link the program and your derivative works",
"def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file. Returns: A dictionary",
"= NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info:",
"{} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API",
"\"--\", \"-\" or nothing pre_parsed_line = [] for arg in args: re_obj =",
"line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We always add",
"= ( '<Product>' '<Condition Message=\"This version of the installer is only suitable to'",
"[distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version:",
"with this program; if not, write to the Free Software Foundation, Inc., #",
"if not re.search(r\"^-\", mc_val) and \"=\" not in mc_val: # Not a Unix",
"orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in",
"info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else \"i386\" # Return a tuple",
"from datetime import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from",
"else: # If \"-\" (and no \"=\" handled above) then it is a",
"requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to add for 32bit",
"containing the information about the last commit. \"\"\" info = {} mysql_version_h =",
"'</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will never be perfect",
"b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\"",
"= mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not",
").version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION))",
"information using mysql_config tool. Returns: dict: Containing MySQL information about libraries. \"\"\" if",
"stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines()",
"open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"):",
"get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the distribution",
"machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000): #",
"in mc_val: # Not a Unix command line continue # In addition form",
"compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True`` if",
"the name when source_only_dist is True. The platname will be added when it",
"' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual Studio",
"operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a",
"In addition form useful information parsed from the # above command line parsed_line",
"= \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\"",
"will be first uncompressed. Returns the path to the folder of the first",
"execute on none-Windows platform. Returns: bool: True if is a 64 bit library.",
"enough # for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val)",
"to get information from ``/etc/lsb-release`` file. If it fails, try to get the",
"line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode()",
"= first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could",
"= _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro",
"the first unarchived member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) =",
"a particular file or component or in included license # documentation. The authors",
"the # Universal FOSS Exception, version 1.0, a copy of which can be",
"if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We always add the",
"Returns the path to the folder of the first unarchived member. Returns str.",
"last commit. \"\"\" is_git_repo = False if find_executable(\"git\") is not None: # Check",
"os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might be in build/ doc_file =",
"VC_RED_64 = ( '<Product>' '<!-- Check Visual c++ Redistributable is Installed -->' '<Property",
"Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual Studio 2015' ' Redistributable.",
"is invalid. IOError: When file could not be read. OSError: when execute on",
"if we have file in docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file):",
"information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate()",
"as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit:",
"fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion(",
"= re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1, opt1) =",
"works # with the separately licensed software that they have included with #",
"pre_parsed_line.pop(0) continue if type1 == \"--\": # If \"--\" and no argument then",
"dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from",
"at the end. Returns: str: The distribution name. \"\"\" name = [distribution.metadata.name] if",
"do not have it, create a fake one LOGGER.warning(\"documentation '%s' does not exist;",
"be future safe in case new options # are added. This might of",
"first, # if starts with \"--\", \"-\" or nothing pre_parsed_line = [] for",
"def linux_distribution(): \"\"\"Try to determine the name of the Linux OS distribution name.",
"version 2.0, for more details. # # You should have received a copy",
"the # above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": #",
"name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for",
"not, write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth",
"figure out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else \"i386\"",
"to the xml msi descriptor.\"\"\" # Get the Product xml element product =",
"run this' ' installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' ) #",
"= stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\") if len(key_value) != 2:",
"{} if os.path.exists(release_file): with open(release_file) as file_obj: for line in file_obj: key_value =",
"\"=\" not in mc_val: # Not a Unix command line continue # In",
"find_executable from distutils.sysconfig import get_python_version from distutils.version import LooseVersion from subprocess import Popen,",
"mysql_config tool. Returns: dict: Containing MySQL information about libraries. \"\"\" if os.name ==",
"ARCH = \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH ==",
"about the last commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\")",
"\"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\",",
"{}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or",
"information parsed from the # above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key",
"out what kind of argument it is first, # if starts with \"--\",",
"options. And in some cases, like \"port\", \"socket\", that is enough # for",
"a copy of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This",
"elements to the xml msi descriptor.\"\"\" # Get the Product xml element product",
"mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We always add the raw output",
"e_magic != b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0]",
"/etc/lsb-release or /etc/os-release file. Returns: A dictionary containing release information. \"\"\" distro =",
"child xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child =",
"Returns: dict: A dict containing the information about the last commit. \"\"\" info",
"Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not stdout: raise ValueError(\"Error executing",
"cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True)",
"return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions elements to",
"with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\",",
"= {} for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj:",
"command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume all",
"python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the distribution name usually used",
"Linux OS distribution name. First try to get information from ``/etc/lsb-release`` file. If",
"\"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\",",
"and conditions. Args: xml_path (str): The original xml msi descriptor path. result_path (str):",
"now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now))",
"empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path)",
"64 bit library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on",
"argument it is first, # if starts with \"--\", \"-\" or nothing pre_parsed_line",
"then it is an option like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and",
"process.communicate() if not stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) #",
"the given tarball. If the tarball has the extension '.gz', it will be",
"properties and conditions. Args: xml_path (str): The original xml msi descriptor path. result_path",
"<filename>cpydist/utils.py<gh_stars>1-10 # Copyright (c) 2020, Oracle and/or its affiliates. # # This program",
"with certain software (including # but not limited to OpenSSL) that is licensed",
"only install if OS is 64bit. Used in MSI-64 ONLY_64bit = ( '<Product>'",
"\"library-path\",)] info[\"libraries\"] = [val for key, val in parsed_line if key in (\"l\",",
"\"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns: dict:",
"doc_path) # Windows MSI descriptor parser # Customization utility functions for the C/py",
"our usage. \"\"\" args = shlex.split(line) # Find out what kind of argument",
"return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from",
"os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not",
"grant you an # additional permission to link the program and your derivative",
"Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] =",
"was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\")",
"file, # which is part of MySQL Connector/Python, is also subject to the",
"DLL is 64 bit or not. Raises: ValueError: When magic of header is",
"[val for _, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs))",
"# Check if we have file in docs/ doc_file = os.path.join('docs', file_name) if",
"get_git_info(): \"\"\"Get Git information about the last commit. Returns: dict: A dict containing",
"%H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if",
"LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\") as fp: fp.write(dom_msi.toprettyxml())",
"key, val in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"]))",
"element in elements: if name and id_: if element.getAttribute('Name') == name and \\",
"element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in",
"by the Free Software Foundation. # # This program is also distributed with",
"If \"--\" and no argument then it is an option like \"--fast\" parsed_line.append(opt1)",
"future safe in case new options # are added. This might of course",
"have file in docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): # it",
"General Public License, version 2.0, for more details. # # You should have",
"information about libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config",
"NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform()))",
"def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml)",
"IOError: When file could not be read. OSError: when execute on none-Windows platform.",
"close enough for our usage. \"\"\" args = shlex.split(line) # Find out what",
"(8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015",
"``/etc/os-release`` file. Returns: tuple: A tuple with (`name`, `version`, `codename`) \"\"\" distro =",
"safe in case new options # are added. This might of course fail.",
"_parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file. Returns: A dictionary containing",
"doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: # Check",
"commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h):",
"include_dirs = [val for _, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\",",
"num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information about the last",
"the path to the folder of the first unarchived member. Returns str. \"\"\"",
"free software; you can redistribute it and/or modify # it under the terms",
"= fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset",
"from subprocess import Popen, PIPE from xml.dom.minidom import parse, parseString try: from dateutil.tz",
"the program and your derivative works # with the separately licensed software that",
"# traditional one character option name that might # have a value val",
"part of MySQL Connector/Python, is also subject to the # Universal FOSS Exception,",
"version 2.0, as # published by the Free Software Foundation. # # This",
"(\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution",
"line in file_obj: key_value = line.split(\"=\") if len(key_value) != 2: continue key =",
"Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual Studio 2015'",
"GNU General Public License # along with this program; if not, write to",
"\"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command()",
"= line.split(\"=\") if len(key_value) != 2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"')",
"If \"-\" (and no \"=\" handled above) then it is a # traditional",
"info def get_git_info(): \"\"\"Get Git information about the last commit. Returns: dict: A",
"the information of ``lsb-release`` command. And finally the information of ``/etc/os-release`` file. Returns:",
"= os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name:",
"= ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") #",
"stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val =",
"even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.",
"\"\" and \"=\" not in opt2: # Value was in the next list",
"course fail. info = {} for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\",",
"get the information of ``lsb-release`` command. And finally the information of ``/etc/os-release`` file.",
"character option name that might # have a value val = opt1[1:] if",
"MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] =",
"GNU General Public License, version 2.0, for more details. # # You should",
"is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE,",
"descriptor path. result_path (str): Path to save the resulting xml. add_vs_redist (bool): Add",
"# # This program is distributed in the hope that it will be",
"# above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets",
"git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info =",
"in included license # documentation. The authors of MySQL hereby grant you an",
"# Find out what kind of argument it is first, # if starts",
"= gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar =",
"if num.isdigit() else num for num in info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get",
"it fails, try to get the information of ``lsb-release`` command. And finally the",
"return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if",
"push_rev, \"short\": push_rev[:7] } return git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns:",
"none-Windows platform. Returns: bool: True if is a 64 bit library. \"\"\" if",
"in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try",
"a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode",
"as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong",
"# if starts with \"--\", \"-\" or nothing pre_parsed_line = [] for arg",
"({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try to be future safe in",
"return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns: dict: Containing",
"on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def",
"= os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = { \"branch\":",
"label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver = python_version or get_python_version()",
"# IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic in",
"1))) elif type1: # We have an option that might have a value",
"as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler:",
"\"-\" or nothing pre_parsed_line = [] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\",",
"distutils.file_util import copy_file from distutils.spawn import find_executable from distutils.sysconfig import get_python_version from distutils.version",
"name of the Linux OS distribution name. First try to get information from",
"stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not stdout: raise ValueError(\"Error executing command:",
"= child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements to \" \"the",
"the properties and conditions elements to the xml msi descriptor.\"\"\" # Get the",
"version of the installer is only suitable to' ' run on 64 bit",
"from the # above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\":",
"= get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if",
"on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements: if",
"def get_git_info(): \"\"\"Get Git information about the last commit. Returns: dict: A dict",
"libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\"",
"proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if",
"next element in the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2",
"VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to add",
"# Get MySQL version with open(mysql_version_h, \"rb\") as fp: for line in fp.readlines():",
"linux_distribution(): \"\"\"Try to determine the name of the Linux OS distribution name. First",
"== 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64",
"excluded from the name when source_only_dist is True. The platname will be added",
"open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) # Windows",
"might of course fail. info = {} for line in stdout.splitlines(): re_obj =",
"line.split(\":\") if len(key_value) != 2: continue key = key_value[0].replace(\" \", \"_\").lower() value =",
"conditions. Args: xml_path (str): The original xml msi descriptor path. result_path (str): Path",
"if `docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\",",
"\"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info =",
"if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in",
"source_only_dist or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return",
"the information about the last commit. \"\"\" is_git_repo = False if find_executable(\"git\") is",
"distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"),",
"properties and conditions elements to the xml msi descriptor.\"\"\" # Get the Product",
"descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element defined on Product.\"\"\"",
"nothing pre_parsed_line = [] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1,",
"for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given",
"'</Product>' ) # 64bit Conditional check, only install if OS is 64bit. Used",
"is_git_repo = proc.returncode == 0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\",",
"If the tarball has the extension '.gz', it will be first uncompressed. Returns",
"executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try to be",
"'.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file,",
".pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball.",
"# Customization utility functions for the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check",
"for _, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif",
"distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"),",
"Returns: A dictionary containing release information. \"\"\" distro = {} with open(os.devnull, \"w\")",
"while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: # One of",
"\", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution(): \"\"\"Try",
"= stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev",
"pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\"",
"if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\")",
"case new options # are added. This might of course fail. info =",
"only useful on Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic =",
"defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements:",
"utility functions for the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a",
"if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar =",
"\"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name.",
"under the terms of the GNU General Public License, version 2.0, as #",
"key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return distro",
"the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA",
"handled above) then it is a # traditional one character option name that",
"information about the last commit. \"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\",",
"the different \"mysql_config\" # options. And in some cases, like \"port\", \"socket\", that",
"parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _",
"in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version",
"name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver = python_version",
"opt2: # Value was in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue",
"%s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure out the",
"-->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />'",
"output. But it should be close enough for our usage. \"\"\" args =",
"= dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements: if name and id_:",
"extension '.gz', it will be first uncompressed. Returns the path to the folder",
"\"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return",
"(\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val in parsed_line if key in",
"# If \"-\" (and no \"=\" handled above) then it is a #",
"Foundation. # # This program is also distributed with certain software (including #",
"invalid. IOError: When file could not be read. OSError: when execute on none-Windows",
"tarfile from datetime import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath",
"opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": # If \"--\" and no argument",
"git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version))",
"= key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse the output of",
"None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully.",
"in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6)",
"= datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from urllib.parse import parse_qsl except",
"return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version.",
"b\"#define LIBMYSQL_VERSION\" in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) <",
"\".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure out the architecture info[\"arch\"]",
"'<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>'",
"= LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {}",
"ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR",
"using mysql_config tool. Returns: dict: Containing MySQL information about libraries. \"\"\" if os.name",
"on none-Windows platform. Returns: bool: True if is a 64 bit library. \"\"\"",
"2020, Oracle and/or its affiliates. # # This program is free software; you",
"never be perfect without special knowledge about all possible command lines \"mysql_config\" might",
"= [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\"))",
"WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS",
"lsb_release command. Returns: A dictionary containing release information. \"\"\" distro = {} with",
"' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This",
"process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not stdout: raise",
"\"-I\", \"--include\",.. include_dirs = [val for _, val in parsed_line] info[\"include_dirs\"] = include_dirs",
"# # You should have received a copy of the GNU General Public",
"name = [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist",
"separately licensed software that they have included with # MySQL. # # Without",
"else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns:",
"\" \".join(info[\"libraries\"])) # Try to figure out the architecture info[\"arch\"] = \"x86_64\" if",
"else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd())",
"= new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path,",
"= dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding",
"Return a tuple for version instead of a string info[\"version\"] = tuple([int(num) if",
"A PARTICULAR PURPOSE. # See the GNU General Public License, version 2.0, for",
"arguments are paths with \"-I\", \"--include\",.. include_dirs = [val for _, val in",
"msi descriptor.\"\"\" # Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append",
"value return distro def linux_distribution(): \"\"\"Try to determine the name of the Linux",
"distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release",
"# we do not have it, create a fake one LOGGER.warning(\"documentation '%s' does",
"mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not in mc_val: # Not",
"\"--\" and no argument then it is an option like \"--fast\" parsed_line.append(opt1) else:",
"# If \"--\" and no argument then it is an option like \"--fast\"",
"in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\",",
"copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser # Customization utility functions",
"' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual Studio 2015' '",
"tarball. Unarchives the given tarball. If the tarball has the extension '.gz', it",
"git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"]))",
"not have it, create a fake one LOGGER.warning(\"documentation '%s' does not exist; creating\"",
"\"socket\", that is enough # for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s:",
"finally the information of ``/etc/os-release`` file. Returns: tuple: A tuple with (`name`, `version`,",
"\"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate()",
"2**32 else \"i386\" # Return a tuple for version instead of a string",
"of /etc/lsb-release or /etc/os-release file. Returns: A dictionary containing release information. \"\"\" distro",
"OpenSSL) that is licensed under separate terms, # as designated in a particular",
"= re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) #",
"key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val in parsed_line if",
"\"\"\"Parse a command line. This will never be perfect without special knowledge about",
"licensed under separate terms, # as designated in a particular file or component",
"in elements: if name and id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id')",
"systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command",
"def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions elements to the xml",
"or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name)",
"General Public License, version 2.0, as # published by the Free Software Foundation.",
"LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom import parse, parseString try: from",
"VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check Visual c++ Redistributable is Installed",
"Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for",
"{}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args:",
"{ \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info return",
"A tuple with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro:",
"tuple: A tuple with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if",
"== \"\" and \"=\" not in opt2: # Value was in the next",
"name=None, id_=None): \"\"\"Get a xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements",
"pre_parsed_line[0] if type2 == \"\" and \"=\" not in opt2: # Value was",
"if is a 64 bit library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit",
"the tarball has the extension '.gz', it will be first uncompressed. Returns the",
"for key, val in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \"",
"raise DistutilsInternalError(\"Could not Append append elements to \" \"the Windows msi descriptor.\") def",
"not source_only_dist or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname))",
"from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.spawn import find_executable from",
"is a # traditional one character option name that might # have a",
"# Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"]",
"def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the",
"try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines =",
"required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] =",
"anything contained in the foregoing, this file, # which is part of MySQL",
"'<Condition Message=\"This version of the installer is only suitable to' ' run on",
"does not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): #",
"the foregoing, this file, # which is part of MySQL Connector/Python, is also",
"/etc/os-release file. Returns: A dictionary containing release information. \"\"\" distro = {} if",
"add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\") as fp:",
"= product.getElementsByTagName(tag_name) for element in elements: if name and id_: if element.getAttribute('Name') ==",
"Customization utility functions for the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if",
"except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value =",
"if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties",
"found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in the hope",
"in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val",
"'%s' in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without",
"an option like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no \"=\" handled",
"parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH",
"= os.path.join('build', file_name) if not os.path.exists(doc_file): # we do not have it, create",
"try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now()",
"Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' '",
"Check if it's a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate()",
"{}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the",
"\"rb\") as fp: for line in fp.readlines(): if b\"#define LIBMYSQL_VERSION\" in line: version",
"in file_obj: key_value = line.split(\"=\") if len(key_value) != 2: continue key = key_value[0].lower()",
"# Return a tuple for version instead of a string info[\"version\"] = tuple([int(num)",
"info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\"",
"docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might be in",
"library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with",
"# IMAGE_FILE_MACHINE_I386 return False elif machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True",
"\" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml",
"without using mysql_config tool. Returns: dict: A dict containing the information about the",
"{} ({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try to be future safe",
"WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A",
"of the GNU General Public License # along with this program; if not,",
"len(key_value) != 2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value",
"and/or its affiliates. # # This program is free software; you can redistribute",
"os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process",
"If it fails, try to get the information of ``lsb-release`` command. And finally",
"stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev:",
"def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool. Returns: dict: A dict",
"the lsb_release command. Returns: A dictionary containing release information. \"\"\" distro = {}",
"determine the name of the Linux OS distribution name. First try to get",
"if os.path.exists(release_file): with open(release_file) as file_obj: for line in file_obj: key_value = line.split(\"=\")",
"dictionary containing release information. \"\"\" distro = {} if os.path.exists(release_file): with open(release_file) as",
"info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler))",
"0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to",
"\"port\", \"socket\", that is enough # for use from Python. info[mc_key] = mc_val",
"commit. \"\"\" is_git_repo = False if find_executable(\"git\") is not None: # Check if",
"write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info",
"> 2**32 else \"i386\" # Return a tuple for version instead of a",
"Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info() if",
"xml msi descriptor.\"\"\" # Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] #",
"python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def",
"\"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf',",
"option name that might # have a value val = opt1[1:] if val:",
"parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line)",
"stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\") if len(key_value) != 2: continue",
"hereby grant you an # additional permission to link the program and your",
"it might be in build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): #",
"from the different \"mysql_config\" # options. And in some cases, like \"port\", \"socket\",",
"write to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor,",
"product.getElementsByTagName(tag_name) for element in elements: if name and id_: if element.getAttribute('Name') == name",
"'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: # Check if we have",
"tool. Returns: dict: Containing MySQL information about libraries. \"\"\" if os.name == \"nt\":",
"it is a # traditional one character option name that might # have",
"args = shlex.split(line) # Find out what kind of argument it is first,",
"# Value was in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if",
"# IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a",
"successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin:",
"http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in the hope that it will",
"# One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We",
"if `docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\",",
"IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if",
"= os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '')",
"in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml",
"import get_python_version from distutils.version import LooseVersion from subprocess import Popen, PIPE from xml.dom.minidom",
"tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir,",
"True if is a 64 bit library. \"\"\" if os.name != \"nt\": raise",
"path to the folder of the first unarchived member. Returns str. \"\"\" orig_wd",
"32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\",",
"line. This will never be perfect without special knowledge about all possible command",
"it is first, # if starts with \"--\", \"-\" or nothing pre_parsed_line =",
"\"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an option that",
"will never be perfect without special knowledge about all possible command lines \"mysql_config\"",
"knowledge about all possible command lines \"mysql_config\" might output. But it should be",
"_parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro =",
"for line in file_obj: key_value = line.split(\"=\") if len(key_value) != 2: continue key",
"source_only_dist is True. The platname will be added when it is given at",
"OSError: when execute on none-Windows platform. Returns: bool: True if is a 64",
"= key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse",
"<RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application",
"to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes():",
"# along with this program; if not, write to the Free Software Foundation,",
"continue key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return",
"IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine ==",
"Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' '",
"= logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64 = (",
"to OpenSSL) that is licensed under separate terms, # as designated in a",
"usage. \"\"\" args = shlex.split(line) # Find out what kind of argument it",
"perfect without special knowledge about all possible command lines \"mysql_config\" might output. But",
"import sys import tarfile from datetime import datetime from distutils.errors import DistutilsInternalError from",
"mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of",
"output. Try to be future safe in case new options # are added.",
"stderr = process.communicate() if not stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config,",
"Args: mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was written",
"for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ]",
"# don't copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser # Customization",
"if find_executable(\"git\") is not None: # Check if it's a Git repository proc",
"{} with open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull)",
"Oracle and/or its affiliates. # # This program is free software; you can",
"def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element defined on Product.\"\"\" product",
"magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives",
"(0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes",
"LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config):",
"Redistributable. Please install the Redistributable then run this' ' installer again.\">' ' Installed",
"id_: if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the",
"architecture info[\"arch\"] = \"x86_64\" if sys.maxsize > 2**32 else \"i386\" # Return a",
"of the Linux OS distribution name. First try to get information from ``/etc/lsb-release``",
"\"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None,",
"sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8,",
"subject to the # Universal FOSS Exception, version 1.0, a copy of which",
"distributed in the hope that it will be useful, but # WITHOUT ANY",
"= os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None,",
"struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif machine in",
"We have an option that might have a value # in the next",
"USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import os import platform import",
"# have a value val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1)",
"LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not in mc_val:",
") # 64bit Conditional check, only install if OS is 64bit. Used in",
"includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check Visual c++ Redistributable is",
"architecture dependent properties and conditions. Args: xml_path (str): The original xml msi descriptor",
"_append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if",
"then run this' ' installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' )",
"contents of /etc/lsb-release or /etc/os-release file. Returns: A dictionary containing release information. \"\"\"",
"with open(release_file) as file_obj: for line in file_obj: key_value = line.split(\"=\") if len(key_value)",
"for the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL",
"git_info return None def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was",
"the last commit. Returns: dict: A dict containing the information about the last",
"%s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not",
"information. \"\"\" distro = {} if os.path.exists(release_file): with open(release_file) as file_obj: for line",
"software; you can redistribute it and/or modify # it under the terms of",
"\"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\") as fp:",
"(c) 2020, Oracle and/or its affiliates. # # This program is free software;",
"not handle '%s' in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL",
"name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver))",
"push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\":",
"if len(key_value) != 2: continue key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\")",
"an option that might have a value # in the next element in",
"copy of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program",
"permission to link the program and your derivative works # with the separately",
"devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines",
"def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command. Returns: A dictionary containing",
"str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if",
"\"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\",",
"info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns: dict: Containing MySQL",
"hope that it will be useful, but # WITHOUT ANY WARRANTY; without even",
"information from ``/etc/lsb-release`` file. If it fails, try to get the information of",
"a # traditional one character option name that might # have a value",
"\"x86_64\" if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using",
"if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch:",
"return element elif id_: if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log,",
"os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path)",
"platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\"",
"is also subject to the # Universal FOSS Exception, version 1.0, a copy",
"of MySQL hereby grant you an # additional permission to link the program",
"with \"-I\", \"--include\",.. include_dirs = [val for _, val in parsed_line] info[\"include_dirs\"] =",
"None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info return None def write_info_src(version): \"\"\"Generate",
"MySQL hereby grant you an # additional permission to link the program and",
"import find_executable from distutils.sysconfig import get_python_version from distutils.version import LooseVersion from subprocess import",
"_ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append",
"add the raw output from the different \"mysql_config\" # options. And in some",
"string info[\"version\"] = tuple([int(num) if num.isdigit() else num for num in info[\"version\"].split(\".\")]) return",
"it should be close enough for our usage. \"\"\" args = shlex.split(line) #",
"os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser #",
"parse(xml_path) if for32: LOGGER.info(\"No elements to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit",
"= False if find_executable(\"git\") is not None: # Check if it's a Git",
"= Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\")",
"ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit",
"_add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions elements to the xml msi",
"IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic in header\")",
"or /etc/os-release file. Returns: A dictionary containing release information. \"\"\" distro = {}",
"name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\" return",
"import logging import os import platform import re import shlex import subprocess import",
"the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is",
"utility functions.\"\"\" import gzip import logging import os import platform import re import",
"if not stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse",
"os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get",
"the GNU General Public License, version 2.0, for more details. # # You",
"distributed with certain software (including # but not limited to OpenSSL) that is",
"elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key, val in parsed_line if",
"they have included with # MySQL. # # Without limiting anything contained in",
"xml to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\") as fp: fp.write(dom_msi.toprettyxml()) fp.flush()",
"id_: if element.getAttribute('Name') == name and \\ element.getAttribute('Id') == id_: return element elif",
"push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] }",
"as designated in a particular file or component or in included license #",
"in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements",
"docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info()",
"the resulting xml. add_vs_redist (bool): Add the VS redistributable requirement. \"\"\" dom_msi =",
"machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False elif",
"struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header)",
"line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C",
"is first, # if starts with \"--\", \"-\" or nothing pre_parsed_line = []",
"LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path,",
"os.path.exists(doc_file): # we do not have it, create a fake one LOGGER.warning(\"documentation '%s'",
"re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We",
"Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements: if name",
"Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition",
"mc_key == \"include\": # Lets assume all arguments are paths with \"-I\", \"--include\",..",
"or nothing pre_parsed_line = [] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg)",
"yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser # Customization utility functions for",
"IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\"",
"line continue # In addition form useful information parsed from the # above",
"more details. # # You should have received a copy of the GNU",
"opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: #",
"like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no \"=\" handled above) then",
"(including # but not limited to OpenSSL) that is licensed under separate terms,",
"one character option name that might # have a value val = opt1[1:]",
"it is given at the end. Returns: str: The distribution name. \"\"\" name",
"= include_dirs LOGGER.debug(\"include_dirs: %s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val",
"first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return",
"has the extension '.gz', it will be first uncompressed. Returns the path to",
"Free Software Foundation. # # This program is also distributed with certain software",
"distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None,",
"of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU",
"MySQL. # # Without limiting anything contained in the foregoing, this file, #",
"raise ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset)",
"or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic",
"\"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi,",
"\"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure",
"Append append elements to \" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None,",
"e_magic = fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60)",
"stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try:",
"for file_name in doc_files: # Check if we have file in docs/ doc_file",
"Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import",
"not limited to OpenSSL) that is licensed under separate terms, # as designated",
"= value return distro def linux_distribution(): \"\"\"Try to determine the name of the",
"else \"i386\" # Return a tuple for version instead of a string info[\"version\"]",
"and \"=\" not in mc_val: # Not a Unix command line continue #",
"you can redistribute it and/or modify # it under the terms of the",
"try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src =",
"if it's a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo",
"a command line. This will never be perfect without special knowledge about all",
"universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo: cmd = [\"git\", \"log\",",
"get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag",
"datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from urllib.parse import parse_qsl except ImportError:",
"raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER",
"from xml.dom.minidom import parse, parseString try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal())",
"tag_name, name=None, id_=None): \"\"\"Get a xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0]",
"import platform import re import shlex import subprocess import struct import sys import",
"Message=\"This application requires Visual Studio 2015' ' Redistributable. Please install the Redistributable then",
"Public License # along with this program; if not, write to the Free",
"its affiliates. # # This program is free software; you can redistribute it",
"might be in build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): # we",
"\"mysql_config\" # options. And in some cases, like \"port\", \"socket\", that is enough",
"\"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"),",
"_parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\",",
"parsed_line = _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume all arguments are",
"\"\"\"Parse the output of the lsb_release command. Returns: A dictionary containing release information.",
"`version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\",",
"if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1)",
"_parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\",",
"the architecture dependent properties and conditions. Args: xml_path (str): The original xml msi",
"Check if we have file in docs/ doc_file = os.path.join('docs', file_name) if not",
"type1 == \"--\": # If \"--\" and no argument then it is an",
"< MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"]",
"\"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return",
"( '<Product>' '<!-- Check Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' '",
"if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in",
"is not None: # Check if it's a Git repository proc = Popen([\"git\",",
"xml_path (str): The original xml msi descriptor path. result_path (str): Path to save",
"if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd,",
"Returns: dict: A dict containing the information about the last commit. \"\"\" is_git_repo",
"creating the egg file. The Python version is excluded from the name when",
"msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path,",
"import Popen, PIPE from xml.dom.minidom import parse, parseString try: from dateutil.tz import tzlocal",
"\"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an option that might have",
"if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return",
"platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the distribution name usually",
"open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ':",
"and \\ element.getAttribute('Id') == id_: return element elif id_: if element.getAttribute('Id') == id_:",
"import copy_file from distutils.spawn import find_executable from distutils.sysconfig import get_python_version from distutils.version import",
"\"\"\"Get MySQL information using mysql_config tool. Returns: dict: Containing MySQL information about libraries.",
"\"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info return None",
"of the GNU General Public License, version 2.0, as # published by the",
"logging import os import platform import re import shlex import subprocess import struct",
"os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz",
"Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element defined",
"name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if",
"len(key_value) != 2: continue key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key]",
"a xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for",
"to the Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston,",
"descriptor parser # Customization utility functions for the C/py product msi descriptor def",
"as file_obj: for line in file_obj: key_value = line.split(\"=\") if len(key_value) != 2:",
"last commit. Returns: dict: A dict containing the information about the last commit.",
"the Linux OS distribution name. First try to get information from ``/etc/lsb-release`` file.",
"instead of a string info[\"version\"] = tuple([int(num) if num.isdigit() else num for num",
"return raise DistutilsInternalError(\"Could not Append append elements to \" \"the Windows msi descriptor.\")",
"A dictionary containing release information. \"\"\" distro = {} if os.path.exists(release_file): with open(release_file)",
"except ImportError: NOW = datetime.now() try: from urllib.parse import parse_qsl except ImportError: from",
"distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\",",
"tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def",
"'<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line.",
"id_: return element elif id_: if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi,",
"[os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit(",
"= [] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line",
"Parse the output. Try to be future safe in case new options #",
"Raises: ValueError: When magic of header is invalid. IOError: When file could not",
"MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import os import",
"``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\") with",
"2.0, as # published by the Free Software Foundation. # # This program",
"information without using mysql_config tool. Returns: dict: A dict containing the information about",
"\"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution(): \"\"\"Try to",
"``lsb-release`` command. And finally the information of ``/etc/os-release`` file. Returns: tuple: A tuple",
"import parse, parseString try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError:",
"(VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will",
"] for file_name in doc_files: # Check if we have file in docs/",
"property VC_RED_64 = ( '<Product>' '<!-- Check Visual c++ Redistributable is Installed -->'",
"Conditional check, only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check Visual",
"header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_,",
"info[\"version\"] = tuple([int(num) if num.isdigit() else num for num in info[\"version\"].split(\".\")]) return info",
"\"i386\" # Return a tuple for version instead of a string info[\"version\"] =",
"{}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]):",
"pre_parsed_line = [] for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2))",
"\" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\") as",
"\"mysql_config\" might output. But it should be close enough for our usage. \"\"\"",
"options # are added. This might of course fail. info = {} for",
"mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key, val in parsed_line if key",
"{}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file):",
"of a string info[\"version\"] = tuple([int(num) if num.isdigit() else num for num in",
"!= 2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return",
"import subprocess import struct import sys import tarfile from datetime import datetime from",
"API installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h,",
"arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if",
"False if find_executable(\"git\") is not None: # Check if it's a Git repository",
"= subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for",
"usually used for creating the egg file. The Python version is excluded from",
"return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool. Returns: dict:",
"\"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info return None def write_info_src(version):",
"pre_parsed_line.pop(0) if \"=\" in opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\",",
"stdout, stderr = process.communicate() if not stdout: raise ValueError(\"Error executing command: {} ({})\"",
"\" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key, val in",
"shlex import subprocess import struct import sys import tarfile from datetime import datetime",
"\" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure out the architecture",
"info[\"version\"].split(\".\")]) return info def get_git_info(): \"\"\"Get Git information about the last commit. Returns:",
"args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1,",
"with the separately licensed software that they have included with # MySQL. #",
"command. And finally the information of ``/etc/os-release`` file. Returns: tuple: A tuple with",
"distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\",",
"don't copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser # Customization utility",
"re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2)",
"[] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: # One",
"OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\")",
"opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: # One of \"--key=val\", \"-key=val\" or",
"distribution name. Get the distribution name usually used for creating the egg file.",
"value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse the output",
"\"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get",
"info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\",",
"# IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine",
"distro def linux_distribution(): \"\"\"Try to determine the name of the Linux OS distribution",
"# Parse the output. Try to be future safe in case new options",
"raw output from the different \"mysql_config\" # options. And in some cases, like",
"and \"=\" not in opt2: # Value was in the next list element",
"str: The distribution name. \"\"\" name = [distribution.metadata.name] if edition: name.append(edition) if label:",
"\"w\").close() if not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) # Windows MSI",
"in the hope that it will be useful, but # WITHOUT ANY WARRANTY;",
"VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check, only install if OS is",
"is free software; you can redistribute it and/or modify # it under the",
"Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging",
"When magic of header is invalid. IOError: When file could not be read.",
"limiting anything contained in the foregoing, this file, # which is part of",
"stderr=PIPE) stdout, stderr = process.communicate() if not stdout: raise ValueError(\"Error executing command: {}",
"ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of the installer is only suitable",
"arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while",
"\"\"\"Append child xml nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child",
"branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info = {",
"64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check",
"name when source_only_dist is True. The platname will be added when it is",
"distutils.spawn import find_executable from distutils.sysconfig import get_python_version from distutils.version import LooseVersion from subprocess",
"dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element in elements: if name and id_: if",
"only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check Visual c++ Redistributable",
"Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\" Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual",
"is_git_repo = False if find_executable(\"git\") is not None: # Check if it's a",
"from urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl ARCH = \"64-bit\"",
"return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball. Unarchives the given tarball. If the",
"in the next element in the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0]",
"# in the next element in the list if pre_parsed_line: (type2, opt2) =",
"mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns: dict: Containing MySQL information about",
"if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for .pyc",
"written successfully. \"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as",
"in docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might be",
"mc_val: # Not a Unix command line continue # In addition form useful",
"if type1 == \"--\": # If \"--\" and no argument then it is",
"def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files",
"nodes to a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if",
"\"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check,",
"platname will be added when it is given at the end. Returns: str:",
"in opt2: # Value was in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0)",
"# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\"",
"\"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get a xml element",
"in tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb')",
"DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.spawn import find_executable",
"the hope that it will be useful, but # WITHOUT ANY WARRANTY; without",
"about the last commit. Returns: dict: A dict containing the information about the",
"option that might have a value # in the next element in the",
"When file could not be read. OSError: when execute on none-Windows platform. Returns:",
"name. First try to get information from ``/etc/lsb-release`` file. If it fails, try",
"fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine)",
"OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line. This",
"This will never be perfect without special knowledge about all possible command lines",
"can be found at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in",
"this file, # which is part of MySQL Connector/Python, is also subject to",
"the raw output from the different \"mysql_config\" # options. And in some cases,",
"given tarball. If the tarball has the extension '.gz', it will be first",
"append elements to \" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None):",
"subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line",
"\"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout,",
"commit. Returns: dict: A dict containing the information about the last commit. \"\"\"",
"mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not in",
"like \"port\", \"socket\", that is enough # for use from Python. info[mc_key] =",
"\"--include\",.. include_dirs = [val for _, val in parsed_line] info[\"include_dirs\"] = include_dirs LOGGER.debug(\"include_dirs:",
"have received a copy of the GNU General Public License # along with",
"to get the information of ``lsb-release`` command. And finally the information of ``/etc/os-release``",
"\"=\" handled above) then it is a # traditional one character option name",
"\"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info",
"= datetime.now() try: from urllib.parse import parse_qsl except ImportError: from urlparse import parse_qsl",
"ValueError: When magic of header is invalid. IOError: When file could not be",
"machine in (0x8664, 0x2000): # IMAGE_FILE_MACHINE_I386/AMD64 return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child",
"# WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or",
"pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 == \"\" and \"=\" not in",
"sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\") as fp: for line in",
"installer is only suitable to' ' run on 64 bit operating systems.\">' '<![CDATA[Installed",
"_win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64 bit or not. Raises: ValueError:",
"dictionary containing release information. \"\"\" distro = {} with open(os.devnull, \"w\") as devnull:",
"is only suitable to' ' run on 64 bit operating systems.\">' '<![CDATA[Installed OR",
"'%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config",
"source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the distribution name",
"'</Condition>' '</Product>' ) def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will never be",
"copy of the GNU General Public License # along with this program; if",
"# Check if it's a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True)",
"tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name =",
"of header is invalid. IOError: When file could not be read. OSError: when",
"# it might be in build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file):",
"Redistributable then run this' ' installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>'",
"\"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if",
"from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try:",
"parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line) return parsed_line def",
"Unarchives the given tarball. If the tarball has the extension '.gz', it will",
"# # This program is also distributed with certain software (including # but",
"def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config tool. Returns: dict: Containing MySQL information",
"Containing MySQL information about libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if",
"LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or",
"opt2) = pre_parsed_line[0] if type2 == \"\" and \"=\" not in opt2: #",
"\"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not found)\")",
"compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file.",
"a string info[\"version\"] = tuple([int(num) if num.isdigit() else num for num in info[\"version\"].split(\".\")])",
"Please install the Redistributable then run this' ' installer again.\">' ' Installed OR",
"[\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch",
"the Redistributable then run this' ' installer again.\">' ' Installed OR VS14REDIST' '</Condition>'",
"of ``/etc/os-release`` file. Returns: tuple: A tuple with (`name`, `version`, `codename`) \"\"\" distro",
"else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line) return parsed_line",
"r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We always",
"\"--\": # If \"--\" and no argument then it is an option like",
"distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util import copy_file from distutils.spawn",
"'<!-- Check Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\"",
"LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working directory:%s\", result_path, os.getcwd()) with",
"childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements to \"",
"return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The",
"PURPOSE. # See the GNU General Public License, version 2.0, for more details.",
"else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER",
"in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of the installer is",
"doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): # we do not have it,",
"fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if",
"file in docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): # it might",
"from distutils.file_util import copy_file from distutils.spawn import find_executable from distutils.sysconfig import get_python_version from",
"# as designated in a particular file or component or in included license",
"particular file or component or in included license # documentation. The authors of",
"command. Returns: A dictionary containing release information. \"\"\" distro = {} with open(os.devnull,",
"if mc_key == \"include\": # Lets assume all arguments are paths with \"-I\",",
"file could not be read. OSError: when execute on none-Windows platform. Returns: bool:",
"containing release information. \"\"\" distro = {} with open(os.devnull, \"w\") as devnull: try:",
"= struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header = fp.read(6) (_, machine) = struct.unpack(\"<4sH\",",
"OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic",
"useful on Windows\") with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2)",
"None: # Check if it's a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"],",
"Exception, version 1.0, a copy of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception.",
"import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from urllib.parse",
"unarchived member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if",
"fake one LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close()",
"\"\"\" git_info = get_git_info() if git_info: with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version:",
"\"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE)",
"# are added. This might of course fail. info = {} for line",
"next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": # If",
"command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the output. Try to be future",
"LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get",
"version instead of a string info[\"version\"] = tuple([int(num) if num.isdigit() else num for",
"Windows MSI descriptor parser # Customization utility functions for the C/py product msi",
"logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>'",
"dict: A dict containing the information about the last commit. \"\"\" info =",
"it's a Git repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo =",
"and push_rev: git_info = { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7]",
"elements = product.getElementsByTagName(tag_name) for element in elements: if name and id_: if element.getAttribute('Name')",
"arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if",
"stderr)) # Parse the output. Try to be future safe in case new",
"magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER fp.seek(offset) file_header =",
"fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset =",
"fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic != b'MZ': raise ValueError(\"Wrong magic",
"possible command lines \"mysql_config\" might output. But it should be close enough for",
"distutils.sysconfig import get_python_version from distutils.version import LooseVersion from subprocess import Popen, PIPE from",
"vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False,",
"add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions. Args: xml_path",
"the folder of the first unarchived member. Returns str. \"\"\" orig_wd = os.getcwd()",
"details. # # You should have received a copy of the GNU General",
"key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command(): \"\"\"Parse the",
"element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product,",
"info[\"link_dirs\"] = [val for key, val in parsed_line if key in (\"L\", \"library-path\",)]",
"in some cases, like \"port\", \"socket\", that is enough # for use from",
"\"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\"))",
"name. Get the distribution name usually used for creating the egg file. The",
"parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val in",
"os.path.exists(release_file): with open(release_file) as file_obj: for line in file_obj: key_value = line.split(\"=\") if",
"if sys.maxsize > 2**32 else \"i386\" # Return a tuple for version instead",
"egg file. The Python version is excluded from the name when source_only_dist is",
"modify # it under the terms of the GNU General Public License, version",
"add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files for Connector/Python.\"\"\" mkpath(doc_path) if not doc_files: doc_files =",
"\".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key, val in parsed_line",
"parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an option that might have a",
"in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val",
"if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver = python_version or",
"(type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: # One of \"--key=val\", \"-key=val\"",
"# additional permission to link the program and your derivative works # with",
"return \"\".join(name) def get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag",
"= _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro =",
"might have a value # in the next element in the list if",
") def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will never be perfect without",
"file_obj: for line in file_obj: key_value = line.split(\"=\") if len(key_value) != 2: continue",
"== name and \\ element.getAttribute('Id') == id_: return element elif id_: if element.getAttribute('Id')",
"break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] #",
"Type=\"raw\" />' '</Property>' '<Condition Message=\"This application requires Visual Studio 2015' ' Redistributable. Please",
"License # along with this program; if not, write to the Free Software",
"get information from ``/etc/lsb-release`` file. If it fails, try to get the information",
"dict containing the information about the last commit. \"\"\" is_git_repo = False if",
"a node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes",
"= tuple([int(num) if num.isdigit() else num for num in info[\"version\"].split(\".\")]) return info def",
"added. This might of course fail. info = {} for line in stdout.splitlines():",
"file_name) if not os.path.exists(doc_file): # we do not have it, create a fake",
"add_vs_redist (bool): Add the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32:",
"stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] =",
"information of ``lsb-release`` command. And finally the information of ``/etc/os-release`` file. Returns: tuple:",
"'.gz', it will be first uncompressed. Returns the path to the folder of",
"git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True",
"node.\"\"\" dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes =",
"as # published by the Free Software Foundation. # # This program is",
"64bit. Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This version of the",
"os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return",
"if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if",
"# with the separately licensed software that they have included with # MySQL.",
"we have file in docs/ doc_file = os.path.join('docs', file_name) if not os.path.exists(doc_file): #",
"what kind of argument it is first, # if starts with \"--\", \"-\"",
"all possible command lines \"mysql_config\" might output. But it should be close enough",
"info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler: info_bin.write(\"compiler: {}\\n\".format(compiler)) def",
"no \"=\" handled above) then it is a # traditional one character option",
"handle '%s' in '%s'\", opt1, line) return parsed_line def _mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information",
"if edition: name.append(edition) if label: name.append(\"-{}\".format(label)) name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver",
"mysql_config) process = Popen([mysql_config], stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() if not stdout:",
"value = key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution(): \"\"\"Try to determine",
"_append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and",
"2: continue key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value",
"for our usage. \"\"\" args = shlex.split(line) # Find out what kind of",
"= { \"branch\": branch_src.split()[-1], \"date\": None, \"commit\": push_rev, \"short\": push_rev[:7] } return git_info",
"tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation files",
"'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: # Check if we have file",
"Check Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"'",
"# Not a Unix command line continue # In addition form useful information",
"add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions. Args: xml_path (str): The original",
"to the folder of the first unarchived member. Returns str. \"\"\" orig_wd =",
"\"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"),",
"was in the next list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 ==",
"will be added when it is given at the end. Returns: str: The",
"os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process = Popen([mysql_config], stdout=PIPE,",
"child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise",
"descriptor.\"\"\" # Get the Product xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children",
"from the name when source_only_dist is True. The platname will be added when",
"distro = {} if os.path.exists(release_file): with open(release_file) as file_obj: for line in file_obj:",
"64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' ) def _parse_mysql_info_line(line):",
"Software Foundation. # # This program is also distributed with certain software (including",
"== \"libs_r\": info[\"link_dirs\"] = [val for key, val in parsed_line if key in",
"not os.path.exists(doc_file): # we do not have it, create a fake one LOGGER.warning(\"documentation",
"stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr)) # Parse the output.",
"re_obj: mc_key = re_obj.group(1) mc_val = re_obj.group(2) # We always add the raw",
"that it will be useful, but # WITHOUT ANY WARRANTY; without even the",
"git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"]",
"program is also distributed with certain software (including # but not limited to",
"argument then it is an option like \"--fast\" parsed_line.append(opt1) else: # If \"-\"",
"elements to \" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name, name=None, id_=None): \"\"\"Get",
"doc_files: doc_files = [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: #",
"key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return distro def linux_distribution():",
"= key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] = value return distro def",
"for32: LOGGER.info(\"No elements to add for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi,",
"parsed from the # above command line parsed_line = _parse_mysql_info_line(mc_val) if mc_key ==",
"The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now",
"not os.path.exists(doc_file): # don't copy yourself copy_file(doc_file, doc_path) # Windows MSI descriptor parser",
"child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements to \" \"the Windows",
"result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture dependent properties and conditions. Args: xml_path (str):",
"tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break",
"os import platform import re import shlex import subprocess import struct import sys",
"it and/or modify # it under the terms of the GNU General Public",
"in lines: key_value = line.split(\":\") if len(key_value) != 2: continue key = key_value[0].replace(\"",
"( '<Product>' '<Condition Message=\"This version of the installer is only suitable to' '",
"in the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 == \"\"",
"if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get MySQL information using mysql_config",
"== \"--\": # If \"--\" and no argument then it is an option",
"contained in the foregoing, this file, # which is part of MySQL Connector/Python,",
"# Lets assume all arguments are paths with \"-I\", \"--include\",.. include_dirs = [val",
"\"-a\"), stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines:",
"for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not",
"that is enough # for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\",",
"\"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info",
"in line: version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL",
"51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import",
"\"\"\" is_git_repo = False if find_executable(\"git\") is not None: # Check if it's",
"key, val in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for",
"re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1, opt1)",
"about libraries. \"\"\" if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config =",
"\"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0 if is_git_repo: cmd =",
"distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro:",
"Get MySQL version with open(mysql_version_h, \"rb\") as fp: for line in fp.readlines(): if",
"when execute on none-Windows platform. Returns: bool: True if is a 64 bit",
"also distributed with certain software (including # but not limited to OpenSSL) that",
"LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only includes VCPPREDIST2015 property VC_RED_64 =",
"used for creating the egg file. The Python version is excluded from the",
"sys.maxsize > 2**32 else \"i386\" # Return a tuple for version instead of",
"if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz =",
"open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError:",
"import tarfile from datetime import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import",
"Returns str. \"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir)",
"also subject to the # Universal FOSS Exception, version 1.0, a copy of",
"dom_tree = parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes",
"for 32bit msi\") else: LOGGER.info(\"Adding 64bit elements\") _add_64bit_elements(dom_msi, add_vs_redist) LOGGER.info(\"Saving xml to:%s working",
"option like \"--fast\" parsed_line.append(opt1) else: # If \"-\" (and no \"=\" handled above)",
"add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\") _append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path,",
"elif id_: if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add",
"xml element product = dom_msi.getElementsByTagName(\"Product\")[0] # Append children if add_vs_redist: LOGGER.info(\"Adding vc_red_64 element\")",
"the contents of /etc/lsb-release or /etc/os-release file. Returns: A dictionary containing release information.",
"pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in opt1: # One of \"--key=val\",",
"(_, machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return False",
"val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in '%s'\", opt1, line) return",
"True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL",
"\"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return info",
"this' ' installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit",
"if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\"))",
"of MySQL Connector/Python, is also subject to the # Universal FOSS Exception, version",
"= [ 'mysql-connector-python.pdf', 'mysql-connector-python.html', 'mysql-html.css', ] for file_name in doc_files: # Check if",
"if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT = ARCH == \"64-bit\" MYSQL_C_API_MIN_VERSION =",
"\"\"\"Return the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a",
"b'MZ': raise ValueError(\"Wrong magic in header\") fp.seek(60) offset = struct.unpack(\"I\", fp.read(4))[0] # IMAGE_FILE_HEADER",
"this program; if not, write to the Free Software Foundation, Inc., # 51",
"your derivative works # with the separately licensed software that they have included",
"element in the list if pre_parsed_line: (type2, opt2) = pre_parsed_line[0] if type2 ==",
"Add the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements",
"original xml msi descriptor path. result_path (str): Path to save the resulting xml.",
"all arguments are paths with \"-I\", \"--include\",.. include_dirs = [val for _, val",
"in build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): # we do not",
"proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\",",
"= _parse_mysql_info_line(mc_val) if mc_key == \"include\": # Lets assume all arguments are paths",
"key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def _parse_lsb_release_command():",
"Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and",
"again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check, only",
"connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit",
"'<Product>' '<!-- Check Visual c++ Redistributable is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch",
"name that might # have a value val = opt1[1:] if val: parsed_line.append((opt1[:1],",
"an # additional permission to link the program and your derivative works #",
"installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\")",
"license # documentation. The authors of MySQL hereby grant you an # additional",
"OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check, only install if OS",
"== \"include\": # Lets assume all arguments are paths with \"-I\", \"--include\",.. include_dirs",
"open(os.path.join(\"docs\", \"INFO_BIN\"), \"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version))",
"get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive",
"A dictionary containing release information. \"\"\" distro = {} with open(os.devnull, \"w\") as",
"which is part of MySQL Connector/Python, is also subject to the # Universal",
"line.split(\"=\") if len(key_value) != 2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key]",
"2)) parsed_line = [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0) if \"=\" in",
"PARTICULAR PURPOSE. # See the GNU General Public License, version 2.0, for more",
"!= \"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\") as fp:",
"= pre_parsed_line[0] if type2 == \"\" and \"=\" not in opt2: # Value",
"gzip import logging import os import platform import re import shlex import subprocess",
"Popen, PIPE from xml.dom.minidom import parse, parseString try: from dateutil.tz import tzlocal NOW",
"be in build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): # we do",
"\"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"]))",
"open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd)",
"ImportError: NOW = datetime.now() try: from urllib.parse import parse_qsl except ImportError: from urlparse",
"= process.communicate() if not stdout: raise ValueError(\"Error executing command: {} ({})\" \"\".format(mysql_config, stderr))",
"if not os.path.exists(doc_file): # we do not have it, create a fake one",
"it, create a fake one LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\",",
"repository proc = Popen([\"git\", \"--no-pager\", \"branch\"], universal_newlines=True) proc.communicate() is_git_repo = proc.returncode == 0",
"tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare",
"LOGGER.error(\"Invalid MySQL C API installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL",
"if starts with \"--\", \"-\" or nothing pre_parsed_line = [] for arg in",
"\"=\" in opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif",
"version 1.0, a copy of which can be found at # http://oss.oracle.com/licenses/universal-foss-exception. #",
"(str): The original xml msi descriptor path. result_path (str): Path to save the",
"\"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi, \"lib\", \"libmysql.dll\")) LOGGER.debug(\"connc_64bit: {0}\".format(connc_64bit))",
"value val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not",
"def write_info_src(version): \"\"\"Generate docs/INFO_SRC. Returns: bool: ``True`` if `docs/INFO_SRC` was written successfully. \"\"\"",
"64bit Conditional check, only install if OS is 64bit. Used in MSI-64 ONLY_64bit",
"See the GNU General Public License, version 2.0, for more details. # #",
"MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional check, only",
"mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not in mc_val: # Not a",
"{0}\".format(connc_64bit)) info[\"arch\"] = \"x86_64\" if connc_64bit else \"i386\" return info def mysql_c_api_info(mysql_config): \"\"\"Get",
"OS distribution name. First try to get information from ``/etc/lsb-release`` file. If it",
"re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = [] while pre_parsed_line: (type1, opt1) = pre_parsed_line.pop(0)",
"(\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in",
"'</Condition>' '</Product>' ) # 64bit Conditional check, only install if OS is 64bit.",
"Lets assume all arguments are paths with \"-I\", \"--include\",.. include_dirs = [val for",
"return info def get_git_info(): \"\"\"Get Git information about the last commit. Returns: dict:",
"None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value = line.split(\":\") if len(key_value)",
"information about the last commit. \"\"\" is_git_repo = False if find_executable(\"git\") is not",
"have an option that might have a value # in the next element",
"' Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check, only install",
"for version instead of a string info[\"version\"] = tuple([int(num) if num.isdigit() else num",
"\"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file. Returns: A dictionary containing release",
"dependent properties and conditions. Args: xml_path (str): The original xml msi descriptor path.",
"(distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False,",
"= proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except",
"\"\"\" info = {} mysql_version_h = os.path.join(mysql_capi, \"include\", \"mysql_version.h\") if not os.path.exists(mysql_version_h): LOGGER.error(\"Invalid",
"info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short:",
"if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode)",
"import os import platform import re import shlex import subprocess import struct import",
"\"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\",",
"label=\"\", edition=\"\"): \"\"\"Get the distribution name. Get the distribution name usually used for",
"of course fail. info = {} for line in stdout.splitlines(): re_obj = re.search(",
"\"\"\"Get Git information about the last commit. Returns: dict: A dict containing the",
"be read. OSError: when execute on none-Windows platform. Returns: bool: True if is",
"to' ' run on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>'",
"tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read())",
"subprocess import Popen, PIPE from xml.dom.minidom import parse, parseString try: from dateutil.tz import",
"parse, parseString try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW",
"\"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to add for 32bit msi\")",
"\"\".format(mysql_config, stderr)) # Parse the output. Try to be future safe in case",
"LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to figure out the architecture info[\"arch\"] =",
"# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General",
"the Free Software Foundation. # # This program is also distributed with certain",
"parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \"",
"from ``/etc/lsb-release`` file. If it fails, try to get the information of ``lsb-release``",
"tzlocal NOW = datetime.now(tzlocal()) except ImportError: NOW = datetime.now() try: from urllib.parse import",
"to be future safe in case new options # are added. This might",
"' run on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>'",
"xml.dom.minidom import parse, parseString try: from dateutil.tz import tzlocal NOW = datetime.now(tzlocal()) except",
"proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip() except IndexError:",
"{}\\n\".format(compiler)) def _parse_release_file(release_file): \"\"\"Parse the contents of /etc/lsb-release or /etc/os-release file. Returns: A",
"be added when it is given at the end. Returns: str: The distribution",
"Python version is excluded from the name when source_only_dist is True. The platname",
"first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode",
"== id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions",
"new_file tar = tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None):",
"msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64 bit or",
"list element parsed_line.append((opt1, opt2)) pre_parsed_line.pop(0) continue if type1 == \"--\": # If \"--\"",
"value return distro def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command. Returns:",
"= stdout.split(\",\")[0].split(\"=\")[1].strip() return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and",
"install if OS is 64bit. Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition",
"# Without limiting anything contained in the foregoing, this file, # which is",
"{}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"]))",
"sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi, \"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")]",
"def get_magic_tag(): \"\"\"Return the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball):",
"line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API {} or later",
"is Installed -->' '<Property Id=\"VS14REDIST\">' ' <RegistrySearch Id=\"FindRedistVS14\" Root=\"HKLM\"' ' Key=\"SOFTWARE\\\\Microsoft\\\\DevDiv\\\\vc\\\\Servicing\\\\14.0\\\\RuntimeMinimum\"' ' Name=\"Version\"",
"element def _add_64bit_elements(dom_msi, log, add_vs_redist=True): \"\"\"Add the properties and conditions elements to the",
"check, only install if OS is 64bit. Used in MSI-64 ONLY_64bit = (",
"Boston, MA 02110-1301 USA \"\"\"Miscellaneous utility functions.\"\"\" import gzip import logging import os",
"with open(os.path.join(\"docs\", \"INFO_SRC\"), \"w\") as info_src: info_src.write(\"version: {}\\n\".format(version)) if git_info: info_src.write(\"branch: {}\\n\".format(git_info[\"branch\"])) if",
"_parse_mysql_info_line(line): \"\"\"Parse a command line. This will never be perfect without special knowledge",
"software (including # but not limited to OpenSSL) that is licensed under separate",
"= re_obj.group(2) # We always add the raw output from the different \"mysql_config\"",
"LOGGER.error(\"MySQL C API {} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"]",
"parsed_line.append(opt1) else: # If \"-\" (and no \"=\" handled above) then it is",
"published by the Free Software Foundation. # # This program is also distributed",
"fp.read(6) (_, machine) = struct.unpack(\"<4sH\", file_header) if machine == 0x014c: # IMAGE_FILE_MACHINE_I386 return",
"if os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\")",
"# http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in the hope that it",
"with open(dll_file, \"rb\") as fp: # IMAGE_DOS_HEADER e_magic = fp.read(2) if e_magic !=",
"import struct import sys import tarfile from datetime import datetime from distutils.errors import",
"is also distributed with certain software (including # but not limited to OpenSSL)",
"given at the end. Returns: str: The distribution name. \"\"\" name = [distribution.metadata.name]",
"if len(key_value) != 2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] =",
"_ = proc.communicate() git_info = dict(parse_qsl(stdout.replace(\"'\", \"\").replace(\"+\", \"%2B\") .split(\",\")[-1:][0].strip())) try: git_info[\"branch\"] = stdout.split(\",\")[0].split(\"->\")[1].strip()",
"Returns: tuple: A tuple with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\"))",
"``True`` if `docs/INFO_SRC` was written successfully. \"\"\" git_info = get_git_info() if git_info: with",
"check, only includes VCPPREDIST2015 property VC_RED_64 = ( '<Product>' '<!-- Check Visual c++",
"'<Product>' '<Condition Message=\"This version of the installer is only suitable to' ' run",
"\"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\",",
"added when it is given at the end. Returns: str: The distribution name.",
"to:%s working directory:%s\", result_path, os.getcwd()) with open(result_path, \"w+\") as fp: fp.write(dom_msi.toprettyxml()) fp.flush() fp.close()",
"distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro",
"in opt1: # One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1:",
"proc.returncode == 0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"]",
"C API installation \" \"(mysql_version.h not found)\") sys.exit(1) # Get MySQL version with",
"and your derivative works # with the separately licensed software that they have",
"use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if not re.search(r\"^-\",",
"{}\\n\".format(git_info[\"branch\"])) if git_info.get(\"date\"): info_src.write(\"date: {}\\n\".format(git_info[\"date\"])) info_src.write(\"commit: {}\\n\".format(git_info[\"commit\"])) info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False",
"The platname will be added when it is given at the end. Returns:",
"the end. Returns: str: The distribution name. \"\"\" name = [distribution.metadata.name] if edition:",
"_mysql_c_api_info_win(mysql_capi): \"\"\"Get MySQL information without using mysql_config tool. Returns: dict: A dict containing",
"\"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information",
"\"\"\"Try to determine the name of the Linux OS distribution name. First try",
"try to get information from ``/etc/lsb-release`` file. If it fails, try to get",
"\"nt\": raise OSError(\"win_ddl_is64bit only useful on Windows\") with open(dll_file, \"rb\") as fp: #",
"file_obj: key_value = line.split(\"=\") if len(key_value) != 2: continue key = key_value[0].lower() value",
"key_value = line.split(\":\") if len(key_value) != 2: continue key = key_value[0].replace(\" \", \"_\").lower()",
"\"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN`",
"DistutilsInternalError(\"Could not Append append elements to \" \"the Windows msi descriptor.\") def _get_element(dom_msi,",
"Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \"\"\"Miscellaneous",
"at # http://oss.oracle.com/licenses/universal-foss-exception. # # This program is distributed in the hope that",
"is True. The platname will be added when it is given at the",
"mysql_version (Optional[str]): The MySQL version. Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully.",
"component or in included license # documentation. The authors of MySQL hereby grant",
"distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution, source_only_dist=False, platname=None, python_version=None, label=\"\", edition=\"\"):",
"of ``lsb-release`` command. And finally the information of ``/etc/os-release`` file. Returns: tuple: A",
"info_src.write(\"short: {}\\n\".format(git_info[\"short\"])) return True return False def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version",
"%s\", mc_key, mc_val) if not re.search(r\"^-\", mc_val) and \"=\" not in mc_val: #",
"paths with \"-I\", \"--include\",.. include_dirs = [val for _, val in parsed_line] info[\"include_dirs\"]",
"not None: # Check if it's a Git repository proc = Popen([\"git\", \"--no-pager\",",
"creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if not os.path.exists(doc_file): # don't copy yourself",
"dict: A dict containing the information about the last commit. \"\"\" is_git_repo =",
"for key, val in parsed_line if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val",
"\"\"\" orig_wd = os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz'",
"(\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\", \" \".join(info[\"link_dirs\"])) LOGGER.debug(\"libraries: %s\", \" \".join(info[\"libraries\"])) # Try to",
"but not limited to OpenSSL) that is licensed under separate terms, # as",
"read. OSError: when execute on none-Windows platform. Returns: bool: True if is a",
"file. If it fails, try to get the information of ``lsb-release`` command. And",
"One of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have",
"containing release information. \"\"\" distro = {} if os.path.exists(release_file): with open(release_file) as file_obj:",
"`codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return (distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"),",
"\"\"\"Add the properties and conditions elements to the xml msi descriptor.\"\"\" # Get",
"distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def",
"= _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return",
"not Append append elements to \" \"the Windows msi descriptor.\") def _get_element(dom_msi, tag_name,",
"return distro def linux_distribution(): \"\"\"Try to determine the name of the Linux OS",
"== 0 if is_git_repo: cmd = [\"git\", \"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc",
"bool: True if is a 64 bit library. \"\"\" if os.name != \"nt\":",
"opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s' in",
"\"\"\" distro = {} with open(os.devnull, \"w\") as devnull: try: stdout = subprocess.check_output(",
"version. Returns: bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d",
"bool: ``True`` if `docs/INFO_BIN` was written successfully. \"\"\" now = NOW.strftime(\"%Y-%m-%d %H:%M:%S %z\")",
"be first uncompressed. Returns the path to the folder of the first unarchived",
"# Copyright (c) 2020, Oracle and/or its affiliates. # # This program is",
"is 64 bit or not. Raises: ValueError: When magic of header is invalid.",
"Path to save the resulting xml. add_vs_redist (bool): Add the VS redistributable requirement.",
"# This program is distributed in the hope that it will be useful,",
"First try to get information from ``/etc/lsb-release`` file. If it fails, try to",
"for arg in args: re_obj = re.search(r\"^(--|-|)(.*)\", arg) pre_parsed_line.append(re_obj.group(1, 2)) parsed_line = []",
"is part of MySQL Connector/Python, is also subject to the # Universal FOSS",
"def write_info_bin(mysql_version=None, compiler=None): \"\"\"Generate docs/INFO_BIN. Args: mysql_version (Optional[str]): The MySQL version. Returns: bool:",
"return distro def _parse_lsb_release_command(): \"\"\"Parse the output of the lsb_release command. Returns: A",
"\"libs_r\": info[\"link_dirs\"] = [val for key, val in parsed_line if key in (\"L\",",
"will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty",
"= parseString(unparsed_xml) if dom_tree.hasChildNodes(): first_child = dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for",
"one LOGGER.warning(\"documentation '%s' does not exist; creating\" \" empty\", doc_file) open(doc_file, \"w\").close() if",
"not found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\") as fp: for",
"xml msi descriptor path. result_path (str): Path to save the resulting xml. add_vs_redist",
"import parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\" ARCH_64BIT =",
"folder of the first unarchived member. Returns str. \"\"\" orig_wd = os.getcwd() (dstdir,",
"2: continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro",
"edition=\"\"): \"\"\"Get the distribution name. Get the distribution name usually used for creating",
"Free Software Foundation, Inc., # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301",
"of \"--key=val\", \"-key=val\" or \"key=val\" parsed_line.append(tuple(opt1.split(\"=\", 1))) elif type1: # We have an",
"# but not limited to OpenSSL) that is licensed under separate terms, #",
"return git_info branch_src = os.getenv(\"BRANCH_SOURCE\") push_rev = os.getenv(\"PUSH_REVISION\") if branch_src and push_rev: git_info",
"return True def _append_child_from_unparsed_xml(father_node, unparsed_xml): \"\"\"Append child xml nodes to a node.\"\"\" dom_tree",
"\"log\", \"-n\", \"1\", \"--date=iso\", \"--pretty=format:'branch=%D&date=%ad&commit=%H&short=%h'\"] proc = Popen(cmd, stdout=PIPE, universal_newlines=True) stdout, _ =",
"run on 64 bit operating systems.\">' '<![CDATA[Installed OR (VersionNT64 >=600)]]>' '</Condition>' '</Product>' )",
"\"include\": # Lets assume all arguments are paths with \"-I\", \"--include\",.. include_dirs =",
"the extension '.gz', it will be first uncompressed. Returns the path to the",
"import re import shlex import subprocess import struct import sys import tarfile from",
"== \"64-bit\" MYSQL_C_API_MIN_VERSION = (8, 0, 0) LOGGER = logging.getLogger(\"cpydist\") # 64bit Conditional",
"= {} if os.path.exists(release_file): with open(release_file) as file_obj: for line in file_obj: key_value",
"a 64 bit library. \"\"\" if os.name != \"nt\": raise OSError(\"win_ddl_is64bit only useful",
"build/ doc_file = os.path.join('build', file_name) if not os.path.exists(doc_file): # we do not have",
"redistributable requirement. \"\"\" dom_msi = parse(xml_path) if for32: LOGGER.info(\"No elements to add for",
"from urlparse import parse_qsl ARCH = \"64-bit\" if sys.maxsize > 2**33 else \"32-bit\"",
"def _parse_mysql_info_line(line): \"\"\"Parse a command line. This will never be perfect without special",
"to link the program and your derivative works # with the separately licensed",
"datetime import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util import mkpath from distutils.file_util",
"fails, try to get the information of ``lsb-release`` command. And finally the information",
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public",
"lines \"mysql_config\" might output. But it should be close enough for our usage.",
"log, add_vs_redist=True): \"\"\"Add the properties and conditions elements to the xml msi descriptor.\"\"\"",
"father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not Append append elements to \" \"the Windows msi",
"os.name == \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting",
"found)\") sys.exit(1) # Get MySQL version with open(mysql_version_h, \"rb\") as fp: for line",
"(distro.get(\"distrib_id\", \"\"), distro.get(\"distrib_release\", \"\"), distro.get(\"distrib_codename\", \"\")) distro = _parse_lsb_release_command() if distro: return (distro.get(\"distributor_id\",",
"NOW = datetime.now() try: from urllib.parse import parse_qsl except ImportError: from urlparse import",
"MySQL information using mysql_config tool. Returns: dict: Containing MySQL information about libraries. \"\"\"",
"be close enough for our usage. \"\"\" args = shlex.split(line) # Find out",
"= opt1[1:] if val: parsed_line.append((opt1[:1], val)) else: parsed_line.append(opt1) else: LOGGER.warning(\"Could not handle '%s'",
"version = LooseVersion( line.split()[2].replace(b'\"', b'').decode() ).version if tuple(version) < MYSQL_C_API_MIN_VERSION: LOGGER.error(\"MySQL C API",
"as devnull: try: stdout = subprocess.check_output( (\"lsb_release\", \"-a\"), stderr=devnull) except OSError: return None",
"name.append(\"-{}\".format(distribution.metadata.version)) if not source_only_dist or python_version: pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if",
"no argument then it is an option like \"--fast\" parsed_line.append(opt1) else: # If",
"\"w\") as info_bin: info_bin.write(\"build-date: {}\\n\".format(now)) info_bin.write(\"os-info: {}\\n\".format(platform.platform())) if mysql_version: info_bin.write(\"mysql-version: {}\\n\".format(mysql_version)) if compiler:",
"(str): Path to save the resulting xml. add_vs_redist (bool): Add the VS redistributable",
"re import shlex import subprocess import struct import sys import tarfile from datetime",
"are paths with \"-I\", \"--include\",.. include_dirs = [val for _, val in parsed_line]",
"kind of argument it is first, # if starts with \"--\", \"-\" or",
"os.path.join('build', file_name) if not os.path.exists(doc_file): # we do not have it, create a",
"sys import tarfile from datetime import datetime from distutils.errors import DistutilsInternalError from distutils.dir_util",
"!= 2: continue key = key_value[0].replace(\" \", \"_\").lower() value = key_value[1].strip(\"\\t\") distro[key] =",
"if OS is 64bit. Used in MSI-64 ONLY_64bit = ( '<Product>' '<Condition Message=\"This",
"is distributed in the hope that it will be useful, but # WITHOUT",
"%s\", \" \".join(include_dirs)) elif mc_key == \"libs_r\": info[\"link_dirs\"] = [val for key, val",
"file. Returns: A dictionary containing release information. \"\"\" distro = {} if os.path.exists(release_file):",
"_append_child_from_unparsed_xml(product, VC_RED_64) LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add",
"# for use from Python. info[mc_key] = mc_val LOGGER.debug(\"%s: %s\", mc_key, mc_val) if",
"add_vs_redist=True): \"\"\"Add the properties and conditions elements to the xml msi descriptor.\"\"\" #",
"Universal FOSS Exception, version 1.0, a copy of which can be found at",
"might # have a value val = opt1[1:] if val: parsed_line.append((opt1[:1], val)) else:",
"elif type1: # We have an option that might have a value #",
"PIPE from xml.dom.minidom import parse, parseString try: from dateutil.tz import tzlocal NOW =",
"included with # MySQL. # # Without limiting anything contained in the foregoing,",
"FOR A PARTICULAR PURPOSE. # See the GNU General Public License, version 2.0,",
"\"lib\")] info[\"include_dirs\"] = [os.path.join(mysql_capi, \"include\")] # Get libmysql.dll arch connc_64bit = _win_dll_is64bit( os.path.join(mysql_capi,",
"But it should be close enough for our usage. \"\"\" args = shlex.split(line)",
"first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0) father_node.appendChild(childNode) return raise DistutilsInternalError(\"Could not",
"mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL information from %s\", mysql_config) process =",
"information of ``/etc/os-release`` file. Returns: tuple: A tuple with (`name`, `version`, `codename`) \"\"\"",
"os.getcwd() (dstdir, tarball_name) = os.path.split(tarball) if dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file",
"or not. Raises: ValueError: When magic of header is invalid. IOError: When file",
"it will be first uncompressed. Returns the path to the folder of the",
"the installer is only suitable to' ' run on 64 bit operating systems.\">'",
"dom_tree.childNodes[0] if first_child.hasChildNodes(): child_nodes = first_child.childNodes for _ in range(len(child_nodes)): childNode = child_nodes.item(0)",
"pyver = python_version or get_python_version() name.append(\"-py{}\".format(pyver)) if platname: name.append(\"-{}\".format(platname)) return \"\".join(name) def get_magic_tag():",
"stderr=devnull) except OSError: return None lines = stdout.decode(sys.getfilesystemencoding()).splitlines() for line in lines: key_value",
"descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows DLL is 64 bit or not.",
"xml element defined on Product.\"\"\" product = dom_msi.getElementsByTagName(\"Product\")[0] elements = product.getElementsByTagName(tag_name) for element",
"info = {} for line in stdout.splitlines(): re_obj = re.search( r\"^\\s+(?:--)?(\\w+)\\s+\\[\\s*(.*?)\\s*\\]\", line.decode(\"utf-8\")) if",
"dstdir: os.chdir(dstdir) if '.gz' in tarball_name: new_file = tarball_name.replace('.gz', '') gz = gzip.GzipFile(tarball_name)",
"Message=\"This version of the installer is only suitable to' ' run on 64",
"tuple for version instead of a string info[\"version\"] = tuple([int(num) if num.isdigit() else",
"= tarfile.TarFile(tarball_name) tar.extractall() os.unlink(tarball_name) os.chdir(orig_wd) return os.path.abspath(os.path.join(dstdir, tar.getmembers()[0].name)) def add_docs(doc_path, doc_files=None): \"\"\"Prepare documentation",
"the magic tag for .pyc files.\"\"\" return sys.implementation.cache_tag def unarchive_targz(tarball): \"\"\"Unarchive a tarball.",
"the terms of the GNU General Public License, version 2.0, as # published",
"'</Property>' '<Condition Message=\"This application requires Visual Studio 2015' ' Redistributable. Please install the",
"functions for the C/py product msi descriptor def _win_dll_is64bit(dll_file): \"\"\"Check if a Windows",
"xml. add_vs_redist (bool): Add the VS redistributable requirement. \"\"\" dom_msi = parse(xml_path) if",
"\"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if distro: return (distro.get(\"name\",",
"if key in (\"L\", \"library-path\",)] info[\"libraries\"] = [val for key, val in parsed_line",
"General Public License # along with this program; if not, write to the",
"the name of the Linux OS distribution name. First try to get information",
"# Try to figure out the architecture info[\"arch\"] = \"x86_64\" if sys.maxsize >",
"== \"nt\": return _mysql_c_api_info_win(mysql_config) if os.path.isdir(mysql_config): mysql_config = os.path.join(mysql_config, \"bin\", \"mysql_config\") LOGGER.info(\"Getting MySQL",
"tuple with (`name`, `version`, `codename`) \"\"\" distro = _parse_release_file(os.path.join(\"/etc\", \"lsb-release\")) if distro: return",
"for element in elements: if name and id_: if element.getAttribute('Name') == name and",
"continue key = key_value[0].lower() value = key_value[1].rstrip(\"\\n\").strip('\"') distro[key] = value return distro def",
"program is free software; you can redistribute it and/or modify # it under",
"(and no \"=\" handled above) then it is a # traditional one character",
"gzip.GzipFile(tarball_name) tar = open(new_file, 'wb') tar.write(gz.read()) tar.close() tarball_name = new_file tar = tarfile.TarFile(tarball_name)",
"LOGGER.info(\"Adding only_64bit element\") _append_child_from_unparsed_xml(product, ONLY_64bit) def add_arch_dep_elems(xml_path, result_path, for32=False, add_vs_redist=True): \"\"\"Add the architecture",
"[val for key, val in parsed_line if key in (\"l\", \"library\",)] LOGGER.debug(\"link_dirs: %s\",",
"Returns: dict: Containing MySQL information about libraries. \"\"\" if os.name == \"nt\": return",
"installer again.\">' ' Installed OR VS14REDIST' '</Condition>' '</Product>' ) # 64bit Conditional check,",
"{} or later required\" \"\".format(MYSQL_C_API_MIN_VERSION)) sys.exit(1) break info[\"libraries\"] = [\"libmysql\"] info[\"library_dirs\"] = [os.path.join(mysql_capi,",
"distro: return (distro.get(\"distributor_id\", \"\"), distro.get(\"release\", \"\"), distro.get(\"codename\", \"\")) distro = _parse_release_file(os.path.join(\"/etc\", \"os-release\")) if",
"element elif id_: if element.getAttribute('Id') == id_: return element def _add_64bit_elements(dom_msi, log, add_vs_redist=True):",
"return (distro.get(\"name\", \"\"), distro.get(\"version_id\", \"\"), distro.get(\"version_codename\", \"\")) return (\"\", \"\", \"\") def get_dist_name(distribution,",
"limited to OpenSSL) that is licensed under separate terms, # as designated in"
] |
[
".baseeffect import BaseEffect class ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250",
"self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move =",
"= self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\"",
"self.target = action.target self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move =",
"def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move =",
"forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\" ) return",
"action.target self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move",
"ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move",
"scene, action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move = action.a_index def",
"= action.target self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move)",
"self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\" )",
"actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\" ) return True, False,",
"import BaseEffect class ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target",
"self.spd_on_action = 250 self.target = action.target self.move = action.a_index def on_action(self): actor =",
"actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\",",
"250 self.target = action.target self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move",
"action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip(",
"action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move = action.a_index def on_action(self):",
"def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name}",
"self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\" ) return True, False, False",
"on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot",
"= 250 self.target = action.target self.move = action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target)",
"class ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target",
"from .baseeffect import BaseEffect class ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action =",
"__init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move = action.a_index",
"= action.a_index def on_action(self): actor = self.scene.board.get_actor(self.target) forgotten_move = actor.actions.pop(self.move) self.scene.board.new_move = False",
"super().__init__(scene) self.spd_on_action = 250 self.target = action.target self.move = action.a_index def on_action(self): actor",
"BaseEffect class ForgetMoveEffect(BaseEffect): def __init__(self, scene, action): super().__init__(scene) self.spd_on_action = 250 self.target =",
"= actor.actions.pop(self.move) self.scene.board.new_move = False self.scene.board.no_skip( f\"{self.scene.board.get_actor(self.target).name} forgot {forgotten_move['name']}!\", particle=\"\" ) return True,"
] |
[
"1: stack.append((x, y, hx, hy, k3, F31, F32, F33, F34)) # Quadrant #4:",
"@cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a field. \"\"\"",
"return dmp_diff(g, m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c,",
"from a pair of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K)",
"indefinite integral of `f` in `x_j` in `K[X]`. \"\"\" if j < 0",
"K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return",
"return f g = [K.zero]*m for i, c in enumerate(reversed(f)): n = i+1",
"from integer GCD. \"\"\" f = [] while h: g = h %",
"{} for f, k in factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast,",
"_rec_eval_tail(c, i+1, A, u, K) for c in g ] if i <",
"R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of `f` and",
"F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K)",
"= dmp_zero(v) while dup_degree(D) <= B: while True: a += K.one if a",
"K), u, K) sqf = dmp_exquo(f, gcd, u, K) if K.has_Field or not",
"q = dup_inner_gcd(p, h, K) if all or dup_degree(g) > 0: result.append((g, i))",
"%s) x (%s, %s) rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x,",
"_dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F",
"< m: f, g = g, f n, m = m, n R",
"if not u: return dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1 if",
"return dup_content(f, K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else:",
"be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0,",
"dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative: return (-t, -s) else: return",
"K): \"\"\"One bisection step of complex root refinement algorithm. \"\"\" hx, hy =",
"in `K[X]` using Horner scheme. \"\"\" if not u: return dup_eval(f, a, K)",
"def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[x]`.",
"dict(F) for sign, monom in zip(perm, monoms): if sign == -1: G[monom] =",
"i, F: abs(F(a, c) - F(b, d)) < n else: cond = lambda",
"K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of",
"dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return [] h = [f[0]] for",
"[h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over",
"v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F,",
"g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field: raise",
"`K[x]`. \"\"\" if not f: return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f,",
"in I_pos ]) I_pos, I_neg = [], [] F_pos, F_neg = {}, {}",
"Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant #1: ++ F11",
"K) a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return a,",
"K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u,",
"g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm",
"f, k in factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u,",
"K) if not v: R = dup_strip([R]) e = dup_strip([e]) else: R =",
"K)) B = 2*max(abs(c)/lc for c in f) while True: r = randfloat()",
"> 1: stack.append((cx, cy, hx, hy, k1, F11, F12, F13, F14)) # Quadrant",
"y1, dx1, dy1, F1 = r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]):",
"dmp_content(f, u, K) G = dmp_LC(g, K) v = u - 1 h",
"i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw, v,",
"two polynomials in `K[X]`. \"\"\" if not u: return dup_resultant(f, g, K) if",
"cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff,",
"dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free",
"convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real roots not supported over",
"polynomial GCD using subresultants over a ring. \"\"\" if not u: return dup_rr_prs_gcd(f,",
"of two polynomials in `K[X]`. \"\"\" if not u: return dup_resultant(f, g, K)",
"f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial in `K[x]`.",
"F4))) elif k > 1: stack.append((x, y, dx, dy, k, F1, F2, F3,",
"== m: break R = dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r,",
"= args.get('eps') if eps is not None: for i, (x, y, dx, dy,",
"b, c, d = b, a+b, d, c+d i += 1 s, t",
"0 while True: h, _ = dmp_inject(f, u, K, front=True) r = dmp_resultant(g,",
"using subresultants over a ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g, K)",
"u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h,",
"if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass",
"= dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K) c = dmp_mul(d,",
"_, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K)",
"else: h = [ _rec_eval_tail(c, i+1, A, u, K) for c in g",
"dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K) return r def _collins_crt(r,",
"= _dup_sturm_shift(F2, hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K)",
"dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero,",
"= dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c",
"K)**i res = K.quo(res*p, q) return res, R def dup_resultant(f, g, K): \"\"\"Computes",
"dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1 if d <= 0: return",
"- len(A)) e = _rec_eval_tail(f, 0, A, u, K) if u == len(A)-1:",
"roots.append((g, r, k)) if len(factors) > 1: for i, (f1, r1, k1) in",
"s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of",
"or not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u,",
"common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if",
"> 0 and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not",
"g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1",
"K) while h: k = dup_degree(h) R.append(h) lc = dup_LC(g, K) if not",
"monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys,",
"d1))) f1, r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2",
"I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g step = lambda a, b,",
"if K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\")",
"in `K[x]`. \"\"\" if not f: return [] h, Q = [f[0]], [[K.one]]",
"K) result, v = dmp_LC(f, K), u-1 for coeff in f[1:]: result =",
"GCD. \"\"\" f = [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x,",
"\"\"\"Returns square-free decomposition of a polynomial in `K[x]`. \"\"\" if K.has_Field or not",
"u, K) while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc =",
"@cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {}, 0 while f:",
"t = dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative: return (-t, -s)",
"n R = [f, g] d = n - m b = (-K.one)**(d+1)",
"\"\"\"Computes polynomial LCM over a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g,",
"d: q = c else: q = dmp_pow(c, d-1, v, K) c =",
"return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no",
"u, K) gg = dmp_eval(g, x, u, K) v = u - 1",
"dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K),",
"f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g,",
"K = K, K.float_domain() f = dup_convert(f, K0, K) else: raise DomainError(\"isolation of",
"i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for",
"i in xrange(n-1, -1, -1): f[i], a = a*f[i], -a return f def",
"coeff = -coeff if dmp_degree(f, u) <= 0: if args.get('include', False): return f",
"fast, K): \"\"\"Refine a positive root of `f` given an interval `(s, t)`.",
"dmp_pow(dmp_neg(lc, v, K), d, v, K) if not d: q = c else:",
"= t, s negative = False if s < 0: if t <=",
"p = -p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p,",
"// h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r",
"USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors of",
"root on (%s, %s)\" % (s, t)) fast = args.get('fast') if type(n) is",
"sequence by a real number `c`. \"\"\" return [ dup_taylor(f, c, K) for",
"v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) r",
"Algebra Systems and Algorithms for Algebraic Computation, Academic Press, London, 1988, pp. 124-128",
"`K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm",
"[] F_pos, F_neg = {}, {} for f, k in factors: for u,",
"return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive",
"groups = {} for (x, y, dx, dy) in roots: if x in",
"return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm",
"else: s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r = dmp_resultant(f,",
"f and g variable by variable into a large integer. The final step",
"[f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K))",
"K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for f",
"if dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1],",
"= K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not",
"1 or (k1 > 0 and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one,",
"K), a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m,",
"K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1,",
"== n: eps = args.get('eps') if eps is not None: for i, (x,",
"u) if du % 2 and dv % 2: s = -s lc,",
") from random import random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear",
"u, K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and",
"F24)) # Quadrant #3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33",
"= dup_LC(r, K) f, i = q, i + 1 return dup_from_raw_dict(g, K)",
"a pair of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc",
"== [K.one]: return (dup_LC(R[-1], K), R) s, i = 1, 1 p, q",
"@cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from a pair of",
"decomposition of `f` in `K[x]`. Given an univariate polynomial `f` with coefficients in",
"cond = lambda a, b, c, d, i, F: i >= n s,",
"I_neg[i] = (u, v, k) return sorted([ ((-v, -u), k) for (u, v,",
"x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if",
"K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v,",
"F1 = r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2,",
"dmp_degree_in(g, 1, u) B = n*M + m*N D, a = [K.one], -K.one",
"in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u,",
"= _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 == 1: return",
"@cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\"",
"-s lc, i = dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw) q",
"K1, K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff",
"a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s,",
"@cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result",
"return R, B, D h = dmp_prem(f, g, u, K) h = dmp_mul_term(h,",
"if n < m: return dmp_zero(u) deriv, c, v = [], K.one, u-1",
"resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u)",
"a, a+b, c, c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1,",
"((-v, -u), k) for (u, v) in I_neg ] + \\ [ ((",
"[K.one], [] else: return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g,",
"stack = [], [(a, b, c, d, f, k)] F = K.get_field() while",
"_dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K),",
"[] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm",
"two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g,",
"g = dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K),",
"K.get_field() while stack: a, b, c, d, f, k = stack.pop() A =",
"References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation",
"K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1,",
"else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u,",
"= dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F,",
"= K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0,",
"== j: return dmp_diff(g, m, v, K) w, i = v-1, i+1 return",
"u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t =",
"g[s-j] coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K)",
"y, hx, hy, (F31, F32, F33, F34)) # Quadrant #4: +- F41 =",
"this case you will need to switch to another GCD method. The algorithm",
"K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r,",
"t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] = (s, t, m)",
"cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg =",
"the interpolated polynomial is the correct GCD. This gives cofactors of the input",
"dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f, -K.unit, K), s+1 return s,",
"a ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f else: return K.one, f",
"k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast, K)) else:",
"if df > 0 and dg > 0: return None if not (df",
"scheme. \"\"\" if j < 0 or j > u: raise IndexError(\"-%s <=",
"= dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd, K) return",
"not K.has_Field: raise DomainError('computation can be done only in a field') f =",
"return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides",
"dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s, g, K) else: raise",
"dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v) == m: break R",
"K) return sorted([ ((-v, -u), k) for (u, v) in I_neg ] +",
"K) v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i,",
"h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\"",
"2: s = -s lc, i = dup_LC(R[i], K), i+1 p *= b**dv",
"K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_",
"dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h,",
"f = dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0, K1) f =",
"gf_int(a, p), 1, u, K) if dmp_degree(F, v) == n: G = dmp_eval_in(g,",
"= dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K):",
"dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g,",
".. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial GCD, International Symposium on",
"be exactly one root on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a,",
"in factors: g = dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F, **args):",
"K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a",
"= dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h, u, K) return h,",
"= dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u, K) v =",
"a prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p,",
"gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _,",
"= dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s =",
"to `K_1`. \"\"\" if K1 is None: K1 = K0.get_ring() common = K1.one",
"R.append(h) lc = dup_LC(g, K) if not d: q = c else: q",
"gcd, K) return h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011",
"@cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0` from GCD computation",
"of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f,",
"dup_sign_variations(f1, K) k2 = k - k1 - r a2, b2, c2, d2",
"= dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex roots not supported over",
"K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g,",
"f1, r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2 =",
"(u, v, k) in enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]): while",
"result is not None: f, h = result F = [h] + F",
"[] else: return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K):",
"\"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant",
"cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1, K0) c",
"cond, fast, K) return sorted([ ((-v, -u), k) for (u, v) in I_neg",
"v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s,",
"K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real",
"u-1, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0,",
"else: return cont, [ dmp_exquo(c, cont, v, K) for c in f ]",
"m, d = g, h, k, m-k B.append(b) D.append(d) h = dmp_prem(f, g,",
"trivial cases in GCD algorithm over a field. \"\"\" if not (f or",
"in g: common = K1.lcm(common, K0.denom(c)) else: w = v-1 for c in",
"u - 1 n = dmp_degree(f, u) m = dmp_degree(g, u) N =",
"dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f,",
"\"\"\"Returns content and a primitive polynomial over a ring. \"\"\" cont = dmp_ground_content(f,",
"= dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g, u, K0, K1) f",
"= _dmp_ff_trivial_gcd(f, g, u, K) if result is not None: return result fc,",
"h, K) if all or dup_degree(g) > 0: result.append((g, i)) i += 1",
"cfg = [ dmp_exquo(cg, h, v, K) for cg in g ] return",
"dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial at `x_j = a` in",
"j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a, v, K) v,",
"if not f or not g: return R, B, D h = dup_prem(f,",
"return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD",
"u), [], [] for monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms",
"dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial",
"dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial over",
"by interpolation. The final step is to verify if the result is the",
"ring. \"\"\" if not u: return dup_rr_content(f, K) cont, v = K.zero, u-1",
"dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g:",
"= dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u),",
"= n - m b = (-K.one)**(d+1) c = -K.one B, D =",
"f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial in",
"`F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K) if h == [K.one]: return",
"F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args):",
"if d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c",
"@cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over",
"= dup_eval(g, x, K) if ff and gg: h = K.gcd(ff, gg) cff",
"K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1]",
"K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res",
"r, k)) if len(factors) > 1: for i, (f1, r1, k1) in enumerate(roots):",
"b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return",
"p, v, K) for c in f ], u) def dup_monic(f, K): \"\"\"Divides",
"dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes",
"dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict,",
"in an algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [], [] for",
"coefficients by `LC(f)` in `K[x]`. \"\"\" if not f: return f lc =",
"c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n",
"K.zero for c in f: cont = K.gcd(cont, c) if K.is_one(cont): break return",
"None def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in `K[x]`. Given an",
"m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m,",
"K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if not",
"a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g,",
"dup_content(f, K) if not f or K.is_one(cont): return cont, f else: return cont,",
"= i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n),",
"if result is not None: return result fc, f = dmp_primitive(f, u, K)",
"gg = dup_eval(g, x, K) if ff and gg: h = K.gcd(ff, gg)",
"= dup_sign_variations(f, K) if k == 0: return [] if k == 1:",
"f2, (a2, b2, c2, d2), cond, fast, K)) else: stack.append((a2, b2, c2, d2,",
"\"\"\"Compute Sturm sequence at x+I*y in p+I*q direction. \"\"\" C = K.complex_domain() a,",
"F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy",
"return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD",
"dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm",
"dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g ],",
"else: return dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return",
"\"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u,",
"x, K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if",
"% (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K) def",
"args.get('include', False): return coeff, result else: (g, i), rest = result[0], result[1:] g",
"result = _dup_ff_trivial_gcd(f, g, K0) if result is not None: return result K1",
"pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function",
"not g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD =",
"r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg,",
"cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a ring.",
"hy, k3, F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1,",
"dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K)",
"K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else:",
"in `x_0` of a polynomial in `K[X]`. \"\"\" if not u: return dup_diff(f,",
"K1) g = dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1)",
"return dup_monic(f, K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\")",
"= C(p, q), C(x, y) f = dup_convert(f, K, C) f = dup_taylor(f,",
"def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {}, 0 while f: q,",
"q *= lc**(dv*(1+d)) if s < 0: p = -p i = dup_degree(R[-2])",
"break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\")",
"decomposition algorithms, Journal of Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F =",
"K) h = dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def dmp_compose(f, g,",
"F2, F3, F4, dx, dy, K) if k != n: return dup_inner_isolate_complex_roots(f, K)",
"= dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K)",
"def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K): \"\"\"Refine a complex root",
"s, t, negative = dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't refine",
"@cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\"",
"c = c % p if c > p // 2: g.append(c -",
"= dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def",
"def dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\" return",
"while h: k = dup_degree(h) R.append(h) lc = dup_LC(g, K) if not d:",
"u, K0, K1) g = dmp_convert(g, u, K0, K1) h, cff, cfg =",
"k4 == 1: roots.append((cx, y, hx, hy, (F41, F42, F43, F44))) elif k4",
"dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one",
"dup_inner_gcd(f, h, K) all = args.get('all', False) while True: d = dup_diff(p, 1,",
"K1.one if not v: for c in g: common = K1.lcm(common, K0.denom(c)) else:",
"return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), [])",
"1: roots.append((x, cy, hx, hy, (F21, F22, F23, F24))) elif k2 > 1:",
"return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial",
"in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]): h",
"v, K) if not d: q = c else: q = dmp_pow(c, d-1,",
"k2 == 1: return (x, cy, hx, hy, (F21, F22, F23, F24)) #",
"0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond,",
"= _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 == 1: return",
"df = dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f, g, K)",
"K) if K.is_one(lc): return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f,",
"dy1, F2, K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2), k2) roots[i]",
"\"\"\"Returns `True` if `f` is a square-free polynomial in `K[x]`. \"\"\" if not",
"= [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B, D",
"= dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) r =",
"= _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result df",
"if not a: return dup_TC(f, K) result = K.zero for c in f:",
"0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1)",
"K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if",
"`f(a*x)` in `K[x]`. \"\"\" f, n, b = list(f), dup_degree(f), a for i",
"+= 1 s, t = F(a, c), F(b, d) if s <= t:",
"GCD by evaluating polynomials f and g at certain points and computing (fast)",
"K) if dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2] == [K.one]: return",
"eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate",
"K): \"\"\"Computes polynomial LCM over a ring in `K[x]`. \"\"\" fc, f =",
"multiplicity = {} for (_, (x, y, dx, dy, _), k) in roots:",
"t, s negative = False if s < 0: if t <= 0:",
"A*a, A*c, K.one if A >= K.one: f = dup_taylor(f, A, K) b,",
"= m, n R = [f, g] d = n - m v",
"b, c, d, i, F: abs(F(a, c) - F(b, d)) < eps else:",
"dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from a pair of polynomials in",
"\"\"\"Try to eliminate `x_0` from GCD computation in `K[X]`. \"\"\" df = dmp_degree(f,",
"if K1 is None: K1 = K0.get_ring() common = K1.one for c in",
"a, b = [K.one], [] while g: q, r = dup_div(f, g, K)",
"u, K): \"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\" if not K.is_Algebraic:",
"= dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm)",
"factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g",
"u, K) if K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u, K) def",
"h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1,",
"the polynomial GCD by evaluating polynomials f and g at certain points and",
"while True: a += K.one if a == p: raise HomomorphismFailed('no luck') F",
"(s, t) else: return (t, s) def dup_outer_refine_real_root(f, s, t, cond, fast, K):",
"return cont, f else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns",
"u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg,",
"= dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u, K)[-1] c, _, _",
"f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f,",
"u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h,",
"u, K1) h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0)",
"return coeff, result else: (g, i), rest = result[0], result[1:] g = dup_mul_ground(g,",
"F13, F14))) elif k1 > 1: stack.append((cx, cy, hx, hy, k1, F11, F12,",
"x // 2: g -= x f.insert(0, g) h = (h-g) // x",
"be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h,",
"\"\"\" cont, v = dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont,",
"1, u, K) h = dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p,",
"i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]):",
"if n < 0 or m < 0: return dmp_zero(u-1) A = dmp_max_norm(f,",
"u, K) h = dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u,",
"= args.get('all', False) while True: d = dup_diff(p, 1, K) h = dup_sub(q,",
"K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's global bisection algorithm.",
"at least second degree. Unlike factorization, complete functional decompositions of polynomials are not",
"c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes",
"b)` 2. `x**n o x**m = x**m o x**n` 3. `T_n o T_m",
"got %s\" % (u, u, j)) if not j: return dmp_eval(dmp_diff(f, m, u,",
"= dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return",
"K, front=True) r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break else:",
"= _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg, u, K) if",
"n = dmp_degree(f, u) if n < m: return dmp_zero(u) deriv, c, v",
"if m <= 0: return f n = dup_degree(f) if n < m:",
"or dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u-1, K), u-1 for",
"h = dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg,",
"K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a",
"r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else: f,",
"HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from integer",
"_dup_decompose(f, K) if result is not None: f, h = result F =",
"-a return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`.",
"K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u,",
"K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in",
"if s < 0: if t <= 0: f, s, t, negative =",
"polynomial is the correct GCD. This gives cofactors of the input polynomials as",
"while True: h, _ = dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h,",
"def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if",
"16: f = dup_scale(f, A, K) a, c, A = A*a, A*c, K.one",
"not None: return result fc, f = dmp_primitive(f, u, K) gc, g =",
"False) while True: d = dup_diff(p, 1, K) h = dup_sub(q, d, K)",
"K) n = dmp_degree(f, u) m = dmp_degree(g, u) if n < m:",
"v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m, v,",
"g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i ==",
"USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return",
"lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0: p = -p i =",
"D = [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B,",
"h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r =",
"else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s positive",
"enumerate(I_neg[i+1:]): while not (s >= v or t <= u): u, v =",
"A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at `x_j",
"r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g,",
"return [] h = [f[0]] for c in f[1:]: h = dup_mul(h, g,",
"a field') f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while",
"\"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" if not (f",
"u: return dup_ground_to_ring(f, K0, K1) if K1 is None: K1 = K0.get_ring() common",
"_dup_rr_trivial_gcd(f, g, K) if result is not None: return result fc, F =",
"u, K), u, K) sqf = dmp_exquo(f, gcd, u, K) if K.has_Field or",
"F12, F13, F14))) elif k1 > 1: stack.append((cx, cy, hx, hy, k1, F11,",
"if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u,",
"if len(factors) == 1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast,",
"u, K) if dmp_zero_p(h, u): result.append((p, i)) break g, p, q = dmp_inner_gcd(p,",
"r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K):",
"K), v, K) P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u,",
"v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K)",
"if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return",
"k1) multiplicity = {} for (_, (x, y, dx, dy, _), k) in",
"\"\"\"Computes indefinite integral of `f` in `x_j` in `K[X]`. \"\"\" if j <",
"K) if dmp_zero_p(f, u): return K.zero, f if K.has_Field or not K.is_Exact: return",
"not Q: continue P.append(min(Q)) if not P: return None else: return 2.0**(max(P)+1) def",
"= lambda a, b, c, d, i, F: True if args.get('sqf', False): I_pos",
"= dup_div(f, cff, K) if not r: cfg_, r = dup_div(g, h, K)",
"n = dmp_degree(f, u) m = dmp_degree(g, u) if n < m: f,",
"return [f] + F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f`",
"hy, (F21, F22, F23, F24))) elif k2 > 1: stack.append((x, cy, hx, hy,",
"pass return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return",
"K)): return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u,",
"polynomial GCD and cofactors of `f` and `g` in `K[X]`. \"\"\" if not",
"= A*a + b, A*c + d if not dup_eval(f, K.zero, K): return",
"K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of complex roots not supported over",
"in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive",
"u, K.dom): break else: f, s = dmp_compose(f, F, u, K), s+1 return",
"from GCD computation in `K[X]`. \"\"\" df = dmp_degree(f, u) dg = dmp_degree(g,",
"not (s >= v or t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u,",
"dmp_to_dict(f, u), [], [] for monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom)",
"def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or",
"%s expected, got %s\" % (u, u, j)) return _rec_integrate_in(f, m, u, 0,",
"\"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f,",
"K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v =",
"K) if all or dmp_degree(g, u) > 0: result.append((g, i)) i += 1",
"cg, g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1) g =",
"= dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res, p, v, K), q,",
"g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g,",
"K1) r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1, K1, K0)",
"polynomial. \"\"\" cont, v = dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or",
"u): return R, B, D h = dmp_prem(f, g, u, K) h =",
"== [K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f,",
"K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f,",
"K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m, v, K) w, i",
"from the integer image by interpolation. The final step is to verify if",
"= dmp_exquo(g, h, u, K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g,",
"K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is a square-free",
"n < 0 or m < 0: return dmp_zero(u-1) K1 = K0.get_ring() cf,",
"polynomial modulo a constant `p` in `K`. \"\"\" if not u: return dup_trunc(f,",
"final step is to verify if the result is the correct GCD. This",
"F23, F24)) # Quadrant #3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K)",
"u, K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v",
"n = dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u)",
"g, K)[-1] h = dup_monic(h, K) cff = dup_exquo(f, h, K) cfg =",
"J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial",
"else: cond = lambda a, b, c, d, i, F: i >= n",
"j)) return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A,",
"\"\"\" F, i = K.get_field(), 0 while not c or not cond(a, b,",
"dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u,",
"dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j,",
"= _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy,",
"fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i] = (u, v, k) for",
"1: a, b, c, d = a1, b1, c1, d1 else: f =",
"K), dup_sign_variations([ dup_eval(f, hx, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f,",
"= dmp_quo(dmp_mul(res, p, v, K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def",
"= dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return roots else: return",
"g, u, K): \"\"\"Computes subresultant PRS of two polynomials in `K[X]`. \"\"\" return",
"PRS. \"\"\" if not f or not g: return (K.zero, []) R, B,",
"y, hx, hy, (F41, F42, F43, F44))) elif k4 > 1: stack.append((cx, y,",
"a, v, i, j, K) for c in g ], v) @cythonized(\"u\") def",
"exception. In this case you will need to switch to another GCD method.",
"Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3,",
"w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear",
"i in xrange(1, s): coeff = K.zero for j in xrange(0, i): if",
"g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s",
"= dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x = 73794*x *",
"sympy.utilities import ( cythonized, variations ) from random import random as randfloat def",
"K1) g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1)",
"g, K) if result is not None: return result fc, F = dup_primitive(f,",
"fc, F = dup_primitive(f, K) gc, G = dup_primitive(g, K) c = K.gcd(fc,",
"K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if",
"for f, k in factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast, K):",
"f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K) return gcd, f,",
"j, (s, t, m) in enumerate(I_pos[i+1:]): while not (s >= v or t",
"polynomial GCD using subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K)",
"expected, got %s\" % (u, u, j)) return _rec_diff_in(f, m, u, 0, j,",
"polynomial in `x_j` at `a` in `K[X]`. \"\"\" if j > u: raise",
"return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g,",
"args.get('convert'): return common, f else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def",
"* lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0: p = -p i",
"i, v, K) res = dmp_quo(dmp_mul(res, p, v, K), q, v, K) return",
"s, h = dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s, g,",
"dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) coeff",
"= [b], [d] if not f or not g: return R, B, D",
"K) cont, v = K.zero, u-1 for c in f: gc = dmp_rr_ground_content(c,",
"- 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one, v)",
"s = (-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f,",
"u): result.append((p, i)) break g, p, q = dmp_inner_gcd(p, h, u, K) if",
"g, K) f, g = g, r a, b = b, dup_sub_mul(a, q,",
"return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def",
"cont = K.zero for c in f: cont = K.gcd(cont, c) if K.is_one(cont):",
"0 while f: q, r = dup_div(f, h, K) if dup_degree(r) > 0:",
"K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using",
"cond, fast, K): \"\"\"Refine a positive root of `f` given a Mobius transform.",
"break upper = sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda r: r[0])",
"K) g = dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f,",
"dup_LC(g, K), K)]) if not f: return [] h = [f[0]] for c",
"return F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K) if k == 1:",
"\"\"\"Computes polynomial LCM of `f` and `g` in `K[X]`. \"\"\" if not u:",
"K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K),",
"positive root of `f` given a Mobius transform. \"\"\" F, i = K.get_field(),",
"roots, stack = [], [(a, b, c, d, f, k)] F = K.get_field()",
"u, K) h = dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f, h,",
"g, u, K), u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f,",
"over a field. \"\"\" if not f: return K.zero else: return K.one def",
"], K), dup_sign_variations([ dup_eval(f, hx, K) for f in F3 ], K), dup_sign_variations([",
"second degree. Unlike factorization, complete functional decompositions of polynomials are not unique, consider",
"else: return coeff, [] result, i = [], 1 h = dmp_diff(f, 1,",
"disjoint positive root isolation intervals. \"\"\" a, b, c, d = K.one, K.zero,",
"from sympy.utilities import ( cythonized, variations ) from random import random as randfloat",
"if result is not None: return result h = dup_subresultants(f, g, K)[-1] h",
"dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term,",
"Taylor shift `f(x + a)` in `K[x]`. \"\"\" f, n = list(f), dup_degree(f)",
"coeff: prev = coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound",
"= _dup_right_decompose(f, s, K) if h is not None: g = _dup_left_decompose(f, h,",
"order derivative of a polynomial in `K[x]`. \"\"\" if m <= 0: return",
"*= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0: p =",
"q = c else: q = dmp_pow(c, d-1, v, K) c = dmp_exquo(p,",
"[K.one, -a], K) D = dup_trunc(D, p, K) return r def _collins_crt(r, R,",
"= b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f",
"K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of sign variations of `f` in",
"F23, F24, hx, hy, K) if k2 == 1: return (x, cy, hx,",
"if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ:",
"v = dmp_degree(f, u), u-1 if d <= 0: return dmp_zero(v) else: s",
"% 2 and dv % 2: s = -s lc, i = dmp_LC(R[i],",
"cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD =",
"in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can be done only in",
"f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) r",
"K.dom) while True: h, _ = dmp_inject(f, 0, K, front=True) r = dmp_resultant(g,",
"coeff*prev < 0: k += 1 if coeff: prev = coeff return k",
"raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F,",
"ff = dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u, K) v",
"K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm",
"None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a",
"dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC,",
"def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\" if",
"c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT =",
"y, dx, dy, k, F1, F2, F3, F4 = stack.pop() hx, hy =",
"in `Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`, returns their GCD",
"gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c,",
"polynomial at `x_j = a_j, ...` in `K[X]`. \"\"\" if not A: return",
"cases in GCD algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g",
"References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms for",
"1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm",
"return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a",
"in xrange(2, df): if df % s != 0: continue h = _dup_right_decompose(f,",
"B, D h = dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0,",
"u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _, h",
"0: return f n = dup_degree(f) if n < m: return [] deriv,",
"args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots",
"fast, K)) else: stack.append((a1, b1, c1, d1, f1, k1)) if k2 == 0:",
"K)): f = dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K),",
"dup_taylor(f, K.one, K), f a1, b1, c1, d1 = a, a+b, c, c+d",
"y, dx, dy, (F1, F2, F3, F4))) elif k > 1: stack.append((x, y,",
"in `K[X]`. \"\"\" if not u: return dup_diff(f, m, K) if m <=",
"F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c,",
"A = K(int(A)) else: A = K.zero if fast and A > 16:",
"g, m, d = g, h, k, m-k B.append(b) D.append(d) h = dup_prem(f,",
"False): return coeff, result else: (g, i), rest = result[0], result[1:] g =",
"F(b, d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k",
"K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g,",
"if not f or not g: return (K.zero, []) R, B, D =",
"K0) cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0)",
"2) for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg",
"dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import (",
"K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients",
"= dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h =",
"dy, eps, K): \"\"\"Refine a complex root using Wilf's global bisection algorithm. \"\"\"",
"c), F(b, d) if s <= t: return (s, t) else: return (t,",
"F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41,",
"u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m],",
"return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u,",
"u) M = dmp_degree_in(g, 1, u) B = n*M + m*N D, a",
"_ = dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h, u+1, K.dom) if",
"f: return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd = dup_gcd(f,",
"], K), ] return sum(v1 - v0 for v1, v0 in zip(V1, V0))",
"`K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h,",
"def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return",
"f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic and homogeneous polynomials",
"= K.gcd(ff, gg) cff = ff // h cfg = gg // h",
"c) - F(b, d)) < n else: cond = lambda a, b, c,",
"r1, k1) in enumerate(roots): x1, y1, dx1, dy1, F1 = r1 for j,",
"d = n - m v = u - 1 b = dmp_pow(dmp_ground(-K.one,",
"= f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>,",
"`f` and `g` in `Z[X]`, returns their GCD and cofactors, i.e. polynomials `h`,",
"dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" result",
"result is not None: return result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f,",
"in perms: G = dict(F) for sign, monom in zip(perm, monoms): if sign",
"k = K.zero, 0 for coeff in f: if coeff*prev < 0: k",
"def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\"",
"@cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is a square-free polynomial",
"dmp_LC(f, K) G = dmp_LC(g, K) else: if not df: F = dmp_LC(f,",
"K.is_QQ: K0, K = K, K.float_domain() f = dup_convert(f, K0, K) else: raise",
"if k4 == 1: roots.append((cx, y, hx, hy, (F41, F42, F43, F44))) elif",
"if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u",
"in `x_j` of a polynomial in `K[X]`. \"\"\" if j < 0 or",
"not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f, K),",
"dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm",
"k1, k2 = f2, f1, k2, k1 if k1 == 0: continue if",
"I_neg ] + I_pos) _, factors = dup_sqf_list(f, K) if len(factors) == 1:",
"if not squarefree: for i, r in enumerate(upper): upper[i] = (r, multiplicity[r]) for",
"if K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\")",
"Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K) F42 = F2 F43 =",
"[e] d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K) d",
"dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): h",
"common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u,",
"if not a: return dmp_TC(f, K) result, v = dmp_LC(f, K), u-1 for",
"= dmp_degree_in(g, 1, u) B = n*M + m*N D, a = [K.one],",
"def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a ring in `K[x]`. \"\"\"",
"[] for c in f: c = c % p if c >",
"b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ],",
"a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n, b =",
"field. \"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns content and a primitive",
"(F11, F12, F13, F14))) elif k1 > 1: stack.append((cx, cy, hx, hy, k1,",
"K) if df == 0 or dg == 0: return [gcd], f, g",
"if i == j: return dmp_eval(g, a, v, K) v, i = v-1,",
"return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f,",
"a = a*f[i], -a return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition",
"return [] if k == 1: roots = [dup_inner_refine_real_root( f, (a, b, c,",
"= r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2,",
"= dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f,",
"return f def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)`",
"dy)) del group[i] break upper = sorted(upper, key=lambda r: r[0]) lower = sorted(lower,",
"else: (g, i), rest = result[0], result[1:] g = dup_mul_ground(g, coeff, K) return",
"else: stack.append((a1, b1, c1, d1, f1, k1)) if k2 == 0: continue if",
"F44, hx, hy, K) if k4 == 1: return (cx, y, hx, hy,",
"p, K) q = dup_mul_ground(q, c, K) h = dup_add(h, q, K) return",
"i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m,",
"deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i ==",
"dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo,",
"elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f,",
"all coefficients by `LC(f)` in `K[x]`. \"\"\" if not f: return f lc",
"0: continue q = t + a - K.log(f[j], 2) Q.append(q // (j",
"return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in",
"_, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors",
"hx, hy, (F21, F22, F23, F24))) elif k2 > 1: stack.append((x, cy, hx,",
"for c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce",
"= F(a, c), F(b, d) if s <= t: return (s, t) else:",
"inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K) if",
"a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not None:",
"for c in f) while True: r = randfloat() if r < 0.5:",
"xrange(0, n): if f[i] >= 0: continue a, Q = K.log(-f[i], 2), []",
"DomainError(\"isolation of real roots not supported over %s\" % K) if dup_degree(f) <=",
"`K[X]` polynomial modulo a constant `p` in `K`. \"\"\" if not u: return",
"2*B+r roots, stack = [], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y,",
"gf_int(a, p), 1, u, K) if dmp_degree(G, v) == m: break R =",
"dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo,",
"1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast, K)) else: stack.append((a1, b1,",
"p = K(nextprime(p)) while not (a % p) or not (b % p):",
"polynomial GCD of `f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0]",
"R = [f, g] d = n - m b = (-K.one)**(d+1) c",
"dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f) m",
"g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff",
"return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial",
"I_neg ] + \\ [ (( u, v), k) for (u, v) in",
"K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant #1: ++",
"F, K) return x, y, dx, dy, F def dup_refine_complex_root(f, x, y, dx,",
"dup_primitive(f, K) gc, g = dup_primitive(g, K) c = K.lcm(fc, gc) h =",
"\"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if K1 is None: K1",
"subresultants over a field. \"\"\" if not u: return dup_ff_prs_gcd(f, g, K) result",
"else: return coeff, [] result, i = [], 1 h = dup_diff(f, 1,",
"h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1,",
"in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else: return",
"= dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg",
"K) f = dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f, u, K)",
"over a ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K) gc,",
"v, K), dmp_pow(c, m-k, v, K), v, K) f, g, m, d =",
"F, eps, K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute",
"hx, hy = dx/2, dy/2 cx, cy = x + hx, y +",
"if k2 == 1: return (x, cy, hx, hy, (F21, F22, F23, F24))",
"F = dmp_LC(f, K) G = dmp_LC(g, K) else: if not df: F",
"K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in",
"a primitive polynomial over a ring. \"\"\" cont = dmp_ground_content(f, u, K) if",
"2: g.append(c - p) else: g.append(c) else: g = [ c % p",
"cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial",
"zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if",
"in f) while True: r = randfloat() if r < 0.5: break x,",
"\"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u) m =",
"dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u)",
"multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K)",
"None: return result fc, f = dmp_primitive(f, u, K) gc, g = dmp_primitive(g,",
"= v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for",
"GCD. This gives cofactors of the input polynomials as a side effect. References",
"K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[X]`. \"\"\" if not",
"and `g` in `K[X]`. \"\"\" if not u: return dup_lcm(f, g, K) if",
"def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm sequence by a real",
"c, d), cond, fast, K) def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine",
"lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)` in",
"u, K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if not u: return",
"dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg,",
"> 0 and dg > 0: return None if not (df or dg):",
"r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in `K[X]`, useful",
"dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\"",
"and a primitive polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return",
"// 2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K)",
"K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2, df): if df %",
"for f in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in",
"k2) roots[i] = (f1, (x1, y1, dx1, dy1, F1), k1) multiplicity = {}",
"Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if not",
"k = dup_degree(h) R.append(h) lc = dup_LC(g, K) if not d: q =",
"r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P *= p",
"dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a",
"u, K): \"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\" if not u:",
"coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont",
"dmp_degree(g, u) > 0: result.append((g, i)) i += 1 if not args.get('include', False):",
"cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f,",
"dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g,",
"dup_sign_variations([ dup_eval(f, hx, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, hy,",
"= dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f) g = { s",
"c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K)",
"a, b, c, d, i, F: i >= 1 for i, (u, v,",
"the result is the correct GCD. This gives cofactors as a side effect.",
"v) in I_neg ] + I_pos) _, factors = dup_sqf_list(f, K) if len(factors)",
"a, b, c, d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K)",
"K): \"\"\"Square-free norm of `f` in `K[X]`, useful over algebraic domains. \"\"\" if",
"= dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative: return (-t, -s) else:",
"lambda a, b, c, d, i, F: True if args.get('sqf', False): I_pos =",
"K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw,",
"_rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return",
"K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v, K) f,",
"K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\" if not u: return",
"= K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K)",
"A = dup_root_lower_bound(f, K) if A is not None: A = K(int(A)) else:",
"== 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast, K)) else: stack.append((a1,",
"..., f_n` are monic and homogeneous polynomials of at least second degree. Unlike",
"1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors of `f` and",
"g, p, u, K): \"\"\"Compute resultant of `f` and `g` modulo a prime",
"or not K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\")",
"K.one for b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i",
"G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h,",
"`f` in `F[x]`. Given an univariate, square-free polynomial `f(x)` returns the associated Sturm",
"K): \"\"\"Returns square-free part of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u):",
"not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return common,",
"dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if",
"`f` in `K[x]`. \"\"\" prev, k = K.zero, 0 for coeff in f:",
"j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i = v-1,",
"K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[X]`. \"\"\" if not",
"2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One bisection step of",
"if not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg x",
"F22, F23, F24, hx, hy, K) if k2 == 1: return (x, cy,",
"( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive root",
"dmp_exquo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h,",
"list(f), dup_degree(f) for i in xrange(n, 0, -1): for j in xrange(0, i):",
"`(f_1, f_2, ..., f_n)`, where:: f = f_1 o f_2 o ... f_n",
"in f: gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if K.is_one(cont):",
"K) h = dmp_subresultants(f, g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc,",
"x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h,",
"F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy, F,",
"_, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c h =",
"u, K) G = dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G,",
"dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\" if not",
"dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a polynomial",
"dmp_compose(f, F, u, K), s+1 return s, f, r def dup_sqf_part(f, K): \"\"\"Returns",
"[], K.one, u-1 for i in xrange(0, m): c, n = c*K(n), n-1",
"if not A: return f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e",
"p), 1, u, K) if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a,",
"# Quadrant #1: ++ F11 = Fx F12 = _dup_sturm_shift(F2, hx, K) F13",
"`f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f,",
"return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g,",
"K) k2 = dup_sign_variations(f2, K) if k1 < k2: a1, a2, b1, b2",
"if k2 == 1: roots.append((x, cy, hx, hy, (F21, F22, F23, F24))) elif",
"if not u: return dup_trunc(f, p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c,",
"dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\"",
"K), v, K) r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p,",
"for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u,",
"monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms),",
"for (u, v, k) in I_pos ]) def _dup_inner_sturm(f, p, q, x, y,",
"n = i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c,",
"K): \"\"\"Computes polynomial LCM over a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f,",
"dup_eval(f, hy, K) for f in F4 ], K), ] V0 = [",
"= dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1.0 / bound else:",
"dup_eval(f, hx, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K)",
"v, k) in enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]): while not",
"if k1 == 1: return (cx, cy, hx, hy, (F11, F12, F13, F14))",
"d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using",
"u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial",
"while True: d = dmp_diff(p, 1, u, K) h = dmp_sub(q, d, u,",
"= dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K):",
"gg: h = K.gcd(ff, gg) cff = ff // h cfg = gg",
"b2, c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real",
"u): return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g, u, K) if",
"\"\"\" if not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u,",
"for i, (x, y, dx, dy) in enumerate(group): if y == _max: upper.append((x,",
"dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return",
"u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u)",
"(F21, F22, F23, F24))) elif k2 > 1: stack.append((x, cy, hx, hy, k2,",
"k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v,",
"dmp_zero_p(f, u): return K.zero, f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u,",
"%s expected, got %s\" % (u, u, j)) return _rec_eval_in(f, a, u, 0,",
"dup_degree(f) if d <= 0: return K.zero else: s = (-1)**((d*(d-1)) // 2)",
"of `f` and `g` in `K[X]`. \"\"\" if not u: return dup_lcm(f, g,",
"not supported over %s\" % K) if s == t: return (s, t)",
"u, K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" zero_f",
"A, u, K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1], K) else:",
"dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating rectangles for",
"R) if R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s, i = 1,",
"= f, g step = lambda a, b, c, d, i, F: i",
"= dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return x, y, dx, dy,",
"return dup_TC(f, K) result = K.zero for c in f: result *= a",
"cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h",
"b, c, d, i, F: abs(F(a, c) - F(b, d)) < n else:",
"LCM over a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f,",
"return [] eps, fast = args.get('eps'), args.get('fast') if eps is not None: cond",
"[ (( u, v), k) for (u, v) in I_pos ]) I_pos, I_neg",
"*= a result += c return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K):",
"s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] =",
"g, K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else:",
"q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K)",
"pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation can be done only in",
"ring. \"\"\" cont = K.zero for c in f: cont = K.gcd(cont, c)",
"hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero,",
"rest def dup_extract(f, g, K): \"\"\"Extracts common content from a pair of polynomials",
"else: return None def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K): \"\"\"Refine",
"dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC,",
"K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2), k2) roots[i] = (f1,",
"v) == m: break R = dmp_zz_modular_resultant(F, G, p, v, K) e =",
"cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and",
"in `K[X]`. \"\"\" df = dmp_degree(f, u) dg = dmp_degree(g, u) if df",
"d), cond, fast, K)] else: roots, stack = [], [(a, b, c, d,",
"def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\" if not",
"`K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff = dup_LC(f, K) f =",
"<NAME>, <NAME>, Evaluation of the heuristic polynomial GCD, International Symposium on Symbolic and",
"K.is_ZZ: raise DomainError(\"real root refinement not supported over %s\" % K) if s",
"1 p, q = K.one, K.one for b, d in zip(B, D)[:-1]: du",
"deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m,",
"_dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return the exact number of zeros",
"u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u,",
"\"\"\"Evaluate a polynomial at `x_0 = a` in `K[X]` using Horner scheme. \"\"\"",
"not g: return (K.zero, []) R, B, D = dup_inner_subresultants(f, g, K) if",
"K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real roots not supported over %s\"",
"GCD algorithm over a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g,",
"f[j+1] += a*f[j] return f def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation",
"g: return (K.zero, []) R, B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1])",
"], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral of",
"c in f) while True: r = randfloat() if r < 0.5: break",
"or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K) def",
"if x in groups: groups[x].append((x, y, dx, dy)) else: groups[x] = [(x, y,",
"will be signaled by raising an exception. In this case you will need",
"h def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if",
"dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack = [], [] F1 =",
"= dup_strip([ C.imag(c) for c in f ]) seq = [u, v] while",
"K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([",
"f1, k2, k1 if k1 == 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root(",
"\"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result",
"= dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u)",
"s = -s lc, i = dup_LC(R[i], K), i+1 p *= b**dv *",
"def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of `f` and `g` in",
"on Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp.",
"f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all",
"c, d, i, F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast,",
"F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for f in F3 ], K),",
"cond, fast, K) return sorted([ (-v, -u) for (u, v) in I_neg ]",
"coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f,",
"return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive",
"= dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h,",
"K.one: f = dup_taylor(f, A, K) b, d = A*a + b, A*c",
"if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K)",
"if j > u: raise IndexError(\"-%s <= j < %s expected, got %s\"",
"dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K):",
"monic and homogeneous polynomials of at least second degree. Unlike factorization, complete functional",
"v = u - 1 n = dmp_degree(f, u) m = dmp_degree(g, u)",
"def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at `x_0 = a` in",
"`K[X]`. \"\"\" if j > u: raise IndexError(\"-%s <= j < %s expected,",
"F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f =",
"for monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1],",
"\"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f:",
"K.zero, f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return",
"return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of",
"coeff = -coeff if dup_degree(f) <= 0: if args.get('include', False): return f else:",
"dup_eval(f, K.zero, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K)",
"x, y, dx, dy, F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K)",
"dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo,",
"return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1],",
"K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f,",
"K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a",
"cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff,",
"K) g, p, q = dmp_inner_gcd(f, h, u, K) all = args.get('all', False)",
"dup_exquo(F, g, K) return s, t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative",
"m: return dmp_zero(u) deriv, c, v = [], K.one, u-1 for i in",
"_dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 == 1: roots.append((cx, cy,",
"zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)):",
"cfg = dmp_exquo(g, h, u, K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f,",
"= _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 == 1: roots.append((cx,",
"polynomial GCD in `Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`, returns",
"K) if K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1]",
"m, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g,",
"if not f: return [] h = [f[0]] for c in f[1:]: h",
"k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 == 1:",
"= K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K):",
"g.append(c) else: g = [ c % p for c in f ]",
"k) in enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]): while not (s",
"-u), k) for (u, v, k) in I_neg ] + \\ [ ((",
"verify if the result is the correct GCD. This gives cofactors as a",
"(ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f,",
"in I_neg ] + \\ [ (( u, v), k) for (u, v,",
"dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f, g,",
"dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if",
"result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest @cythonized(\"u,i\") def",
"c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes",
"is the correct GCD. This gives cofactors of the input polynomials as a",
"u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K)",
"x**m o x**n` 3. `T_n o T_m = T_m o T_n` where `T_n`",
"r: r[0]) lower = sorted(lower, key=lambda r: r[0]) if not squarefree: for i,",
"K): \"\"\"Extracts common content from a pair of polynomials in `K[x]`. \"\"\" fc",
"v, k) in I_pos ]) def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute",
"Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if",
"K): \"\"\"Computes indefinite integral of `f` in `x_0` in `K[X]`. \"\"\" if not",
"root of `f` given an interval `(s, t)`. \"\"\" if s == t:",
"< m: return dmp_zero(u) deriv, c, v = [], K.one, u-1 for i",
"a, v, K) result = dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def",
"- r a2, b2, c2, d2 = b, a+b, d, c+d if k2",
"K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff =",
"\"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f,",
"F, u, K), s+1 return s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free",
"zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f,",
"coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) else: coeff, f",
"K) if k == 0: return [] if k == 1: roots =",
"F = K.get_field() while stack: a, b, c, d, f, k = stack.pop()",
"p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g,",
"except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try:",
"[f[0]] for c in f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h,",
"K) if result is not None: return result df = dmp_degree(f, u) dg",
"return result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg,",
"[d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B, D h =",
"return dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1 if d <= 0:",
"if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g,",
"u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g = dup_mirror(f,",
"1: return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u,",
"@cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials",
"K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not args.get('convert'): return",
"a, u, K) return _rec_diff_eval(f, m, a, u, 0, j, K) def dup_half_gcdex(f,",
"\"\"\"Compute the number of sign variations of `f` in `K[x]`. \"\"\" prev, k",
"dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd,",
"K) coeff = -coeff if dup_degree(f) <= 0: if args.get('include', False): return f",
"K), u-1 for i, c in enumerate(reversed(f)): n = i+1 for j in",
"h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff,",
"dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h,",
"(dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def",
"x, y, dx, dy, k, F1, F2, F3, F4 = stack.pop() hx, hy",
"`f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K) if h ==",
"F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u, K) try:",
"for f in F ] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K):",
"dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if du",
"f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm,",
"g, u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle",
"in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F4 ],",
"= gg // h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1]",
"two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g,",
"`K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree,",
"in `K[x]`. Given an univariate polynomial `f` with coefficients in a field of",
"dx, dy, _), k) in roots: multiplicity[(x, y, dx, dy)] = k roots",
"c, v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\")",
"< u - len(A) + 1: return h else: return dup_eval(h, A[-u+i-1], K)",
"j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\"",
"u, K): return (dmp_LC(R[-1], K), R) s, i, v = 1, 1, u-1",
"= u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ],",
"x in groups: groups[x].append((x, y, dx, dy)) else: groups[x] = [(x, y, dx,",
"K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K)",
"if not u: return dup_lcm(f, g, K) if K.has_Field or not K.is_Exact: return",
"u, K)): f = dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u,",
"K) else: h = [ _rec_eval_tail(c, i+1, A, u, K) for c in",
"= dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K)",
"0, -1): for j in xrange(0, i): f[j+1] += a*f[j] return f def",
"%s expected, got %s\" % (u, u, j)) return _rec_diff_in(f, m, u, 0,",
"k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 == 1:",
"cfg = dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g,",
"= x + hx, y + hy F1, F2, F3, F4 = F",
"Symposium on Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995,",
"(dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u,",
"a primitive polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f,",
"g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r",
"dmp_diff(f, 1, u, K), u, K) sqf = dmp_exquo(f, gcd, u, K) if",
"h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff,",
"given precision. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring()",
"= dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h, u): k = dmp_degree(h,",
"args.get('eps') if eps is not None: for i, (x, y, dx, dy, F)",
"dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[x]`. \"\"\" if",
"a ring. \"\"\" cont = K.zero for c in f: cont = K.gcd(cont,",
"[], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f,",
"K): \"\"\"Square-free norm of `f` in `K[x]`, useful over algebraic domains. \"\"\" if",
"0: return None if not (df or dg): F = dmp_LC(f, K) G",
"a, b, c, d, i, F: abs(F(a, c) - F(b, d)) < n",
"K) all = args.get('all', False) while True: d = dup_diff(p, 1, K) h",
"h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff = dup_exquo(f, h,",
"m, j, u, K): \"\"\"m-th order derivative in `x_j` of a polynomial in",
"return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`.",
"F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K) F42 = F2",
"algorithm is purely heuristic which means it may fail to compute the GCD.",
"result.append((p, i)) break g, p, q = dmp_inner_gcd(p, h, u, K) if all",
"over a field. \"\"\" if not (f or g): return [], [], []",
"dup_monic(h, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return",
"t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] = (s, t, m)",
"args.get('include', False): return f else: return coeff, [] result, i = [], 1",
"hy, k1, F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx,",
"\"\"\" if not f: return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u,",
"dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else:",
"dx, dy, F, K): \"\"\"One bisection step of complex root refinement algorithm. \"\"\"",
"hx, hy, (F11, F12, F13, F14))) elif k1 > 1: stack.append((cx, cy, hx,",
"= K.zero for c in f: result *= a result += c return",
"F = (F1, F2, F3, F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f,",
"def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of `f` and `g` modulo",
"t) F = K.get_field() a, c = F.numer(s), F.denom(s) b, d = F.numer(t),",
"a field. \"\"\" if not (f or g): return [], [], [] elif",
"expected, got %s\" % (u, u, j)) if not j: return dmp_eval(dmp_diff(f, m,",
"dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[X]`.",
"d), F(b, d) f, g = dup_taylor(f, K.one, K), f a1, b1, c1,",
"@cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n =",
"group[i] break upper = sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda r:",
"g, K) if dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2] == [K.one]:",
"b = -lc * c**(m-k) f, g, m, d = g, h, k,",
"0, u, K) h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u,",
"if coeff: prev = coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper",
"if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg,",
"if dmp_zero_p(f, u): return cont for c in f[1:]: cont = dmp_gcd(cont, c,",
"gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u,",
"cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1, K0)",
"] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1 ],",
"polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f,",
"or dmp_one_p(cont, v, K): return cont, f else: return cont, [ dmp_exquo(c, cont,",
"\"\"\" if not A: return f if dmp_zero_p(f, u): return dmp_zero(u - len(A))",
"dy, F, K) return x, y, dx, dy, F def dup_refine_complex_root(f, x, y,",
"K) < 0: f = dup_neg(f, K) f = list(reversed(f)) for i in",
"k == 0: return [] if k == 1: roots = [dup_inner_refine_real_root( f,",
"Given univariate polynomials `f` and `g` in `Z[x]`, returns their GCD and cofactors,",
"enumerate(group): if y == _max: upper.append((x, y, dx, dy)) del group[i] break _min",
"g, K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" if",
"t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s,",
"q) return res, R def dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials",
"K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K):",
"dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B",
"dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x = a` in `K[x]` using",
"K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u, K)",
"dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m",
"from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add,",
"[-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return",
"K) h = dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u, K)",
"V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1 ], K),",
"not u: return dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1 if d",
"of coefficients over a ring. \"\"\" if not u: return dup_rr_content(f, K) cont,",
"q, r = dup_div(f, h, K) if dup_degree(r) > 0: return None else:",
"K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one while P <= B: p",
"if f[i] >= 0: continue a, Q = K.log(-f[i], 2), [] for j",
"else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle",
"cy, K) # Quadrant #1: ++ F11 = Fx F12 = _dup_sturm_shift(F2, hx,",
"u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if",
"(u, v, k) return sorted([ ((-v, -u), k) for (u, v, k) in",
"gc = f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc)",
"(fast) integer GCD of those evaluations. The polynomial GCD is recovered from the",
"for c in f: cont = K.gcd(cont, c) if K.is_one(cont): break return cont",
"if n < m: return [] deriv, c = [], K.one for i",
"= g, r a, b = b, dup_sub_mul(a, q, b, K) a =",
"in `K[X]`. \"\"\" if not u: return dup_sqf_list(f, K, **args) if K.has_Field or",
"y + hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy =",
"A*a + b, A*c + d if not dup_eval(f, K.zero, K): roots.append((F(b, d),",
"v1, v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx, dy,",
"root isolating rectangles for all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K))",
"= dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G, p, u, K)",
"= dup_add(h, q, K) return h def dup_compose(f, g, K): \"\"\"Evaluate functional composition",
"c+d if not dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1) k =",
"return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial",
"algebraic domains. \"\"\" if not u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise",
"a, K) if not a: return dmp_TC(f, K) result, v = dmp_LC(f, K),",
"(-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K),",
"K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\")",
"return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD",
"return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result is",
"in p+I*q direction. \"\"\" C = K.complex_domain() a, b = C(p, q), C(x,",
"complex roots not supported over %s\" % K) squarefree = args.get('sqf', False) if",
"if not u: return dup_ground_to_ring(f, K0, K1) if K1 is None: K1 =",
"dup_LC(f, K) < 0: f = dup_neg(f, K) f = list(reversed(f)) for i",
"dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f` and",
"(K.zero, []) R, B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0:",
"a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result is not None:",
"if k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b,",
"not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def",
"] return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant",
"cofactors of the input polynomials as a side effect. References ========== .. [Liao95]",
"y, dx, dy)) else: groups[x] = [(x, y, dx, dy)] upper, lower =",
"K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of sign variations of `f`",
"dg = dmp_degree(g, u) if df > 0 and dg > 0: return",
"dx, dy, F, eps, K): \"\"\"Refine a complex root until the desired precision",
"K) gc, g = dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f,",
"K), s+1 return s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part of",
"F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm",
"is to verify if the result is the correct GCD. This gives cofactors",
"K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order",
"f, g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm",
"else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients",
"g, [], [K.one] else: return dup_neg(g, K), [], [-K.one] elif not g: if",
"dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f,",
"dup_root_lower_bound(f, K) if A is not None: A = K(int(A)) else: A =",
"polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse,",
"not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1, 1,",
"origin. \"\"\" return [ dup_mirror(f, K) for f in F ] def _dup_inner_zeros(F1,",
"for f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in",
"u, K) g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) + 29",
"\"\"\"Returns content and a primitive polynomial over a field. \"\"\" return K.one, f",
"= dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u)",
"h = dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0, u, K)",
"u, K0) if result is not None: return result K1 = K0.get_ring() cf,",
"roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using",
"K.has_Field: raise DomainError('computation can be done only in a field') a, b =",
"v or t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast,",
"return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns",
"R, B, D h = dmp_prem(f, g, u, K) h = dmp_mul_term(h, b,",
"def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a ring.",
"K)): c = -c h = dup_mul_ground(h, c, K) cff = dup_exquo(f, h,",
"h: result.append((p, i)) break g, p, q = dup_inner_gcd(p, h, K) if all",
"an exception. In this case you will need to switch to another GCD",
"u) or dmp_zero_p(g, u): return R, B, D h = dmp_prem(f, g, u,",
"= dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u,",
"else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass",
"or not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f,",
">= 1 for i, (u, v, k) in enumerate(I_pos): for j, (s, t,",
"f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm) +",
"in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K) else:",
"return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial",
"f ], u) def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`.",
"f = dup_convert(f, K, C) f = dup_taylor(f, b, C) f = dup_scale(f,",
"= dup_sign_variations(f, K) if k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root(",
"of a polynomial in `K[x]`. \"\"\" if m <= 0: return f n",
"= dmp_subresultants(f, g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K)",
"K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" cont",
"u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h,",
"dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg =",
"field. \"\"\" if not f: return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f,",
"dx, dy) in enumerate(group): if y == _max: upper.append((x, y, dx, dy)) del",
"c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r",
"dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K)",
"k) in I_pos ]) def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm",
"F33, F34, hx, hy, K) if k3 == 1: roots.append((x, y, hx, hy,",
"m, a, j, u, K): \"\"\"Differentiate and evaluate a polynomial in `x_j` at",
"the input polynomials as a side effect. References ========== .. [Liao95] <NAME>, <NAME>,",
"while True: r = randfloat() if r < 0.5: break x, y, dx,",
"v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a, v,",
"n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v) ==",
"common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral",
"f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f,",
"h cfg = gg // h h = _dup_zz_gcd_interpolate(h, x, K) h =",
"\"\"\" if not f: return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K)",
"dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\") def",
"while g: q, r = dup_div(f, g, K) f, g = g, r",
"gg // h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_,",
"f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v,",
"= dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors I_pos =",
"<= 0: f, s, t, negative = dup_mirror(f, K), -t, -s, True else:",
"in a field') f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)]",
"n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K):",
"r = dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd, K)",
"h = dmp_prem(f, g, u, K) h = [ dmp_exquo(ch, b, v, K)",
"c, K): \"\"\"Shift origin of a Sturm sequence by a real number `c`.",
"def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s positive roots. \"\"\" n,",
"q, K) return h def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in",
"cont = dup_content(f, K) if not f or K.is_one(cont): return cont, f else:",
"f[1:]: h = dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0, u,",
"if len(roots) == n: eps = args.get('eps') if eps is not None: for",
"x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h,",
"\"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else: return",
"k == 1: roots = [dup_inner_refine_real_root( f, (a, b, c, d), cond, fast,",
"supported over %s\" % K) if dup_degree(f) <= 0: return [] eps, fast",
"K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f,",
"dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral of `f` in `x_j` in",
"return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free",
"T_m o T_n` where `T_n` and `T_m` are Chebyshev polynomials. References ========== ..",
"in xrange(0, i): f[j+1] += a*f[j] return f def dup_transform(f, p, q, K):",
"dup_mul(h, g, K) h = dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def",
"2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for",
"dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v, K) f, g, m, d",
"return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ],",
"result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest def",
"(b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G",
"`F[x]`. Given an univariate, square-free polynomial `f(x)` returns the associated Sturm sequence `f_0(x),",
"return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f,",
"coefficients over a field. \"\"\" if not f: return K.zero else: return K.one",
"K) cff = [ dmp_exquo(cf, h, v, K) for cf in f ]",
"= factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg",
"dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p` in `K`. \"\"\"",
"are not unique, consider examples: 1. `f o g = f(x + b)",
"K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 =",
"i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m,",
"i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in",
"functional composition `f(g)` in `K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g,",
"n: return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y, dx, dy, (F1,",
"return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common",
"c+d i += 1 s, t = F(a, c), F(b, d) if s",
"[] for j in xrange(i+1, n): if f[j] <= 0: continue q =",
"in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for",
"y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1, F2,",
"_min = min([ r[1] for r in group ]) for i, (x, y,",
"hy, K) for f in F4 ], K), ] V0 = [ dup_sign_variations([",
"in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2 while not ((x2 >=",
"d)) < eps else: cond = lambda a, b, c, d, i, F:",
"c, d, f, k)] F = K.get_field() while stack: a, b, c, d,",
"f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f,",
"dmp_strip([ dmp_rem(c, p, u-1, K) for c in f ], u) @cythonized(\"u,v\") def",
"y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack = [], []",
"\"\"\"Flip the direction of a Sturm sequence at its origin. \"\"\" return [",
"`f` with coefficients in a field of characteristic zero, returns tuple `(f_1, f_2,",
"m, u, K): \"\"\"Computes indefinite integral of `f` in `x_0` in `K[X]`. \"\"\"",
"p, u, K) except HomomorphismFailed: continue if K.is_one(P): r = R else: r",
"y, dx, dy, F, K) return x, y, dx, dy, F def dup_refine_complex_root(f,",
"h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) h",
"dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return x,",
"+ a - K.log(f[j], 2) Q.append(q // (j - i)) t += 1",
"dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero,",
"in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K),",
"\"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g) if",
"for coeff in f: if coeff*prev < 0: k += 1 if coeff:",
"transform. \"\"\" F, i = K.get_field(), 0 while not c or not cond(a,",
"result = K.zero for c in f: result *= a result += c",
"K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD",
"a ring in `K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc, g =",
"K), dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes",
"`K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u,",
"b, c, d, i, F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond,",
"v, K) cff = [ dmp_exquo(cf, h, v, K) for cf in f",
"dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u,",
"c in f: gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if",
"0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n =",
"p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c",
"for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 =",
"v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h, g,",
"exactly one root on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b,",
"i, (x, y, dx, dy) in enumerate(group): if y == _min: lower.append((x, y,",
"else: return (t, s) def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a",
"1: roots.append((x, y, dx, dy, (F1, F2, F3, F4))) elif k > 1:",
"ring. \"\"\" if not (f or g): return [], [], [] elif not",
"if A >= K.one: f = dup_taylor(f, A, K) b, d = A*a",
"d, i, F: abs(F(a, c) - F(b, d)) < n else: cond =",
"K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\" if not u: return",
"b = [K.one], [] while g: q, r = dup_div(f, g, K) f,",
"dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import",
"m = dmp_degree(g, u) if n < 0 or m < 0: return",
"dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg",
"i += 1 s, t = F(a, c), F(b, d) if s <=",
"cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g step =",
"p, q = dup_inner_gcd(f, h, K) all = args.get('all', False) while True: d",
"roots using continued fractions approach. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f,",
"from integer GCD. \"\"\" f = [] while not dmp_zero_p(h, v): g =",
"K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the",
"polynomial in `K[X]`. \"\"\" if not u: return dup_diff(f, m, K) if m",
"polynomials f and g at certain points and computing (fast) integer GCD of",
"not (f or g): return [], [], [] elif not f: return dup_monic(g,",
"USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f,",
"@cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`, useful over algebraic",
"primitive polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K)",
"K) f = list(reversed(f)) for i in xrange(0, n): if f[i] >= 0:",
"for coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c, n =",
"K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u,",
"v), d+1, v, K) c = dmp_ground(-K.one, v) B, D = [b], [d]",
"cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff",
"r = n // s for i in xrange(1, s): coeff = K.zero",
"k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if k != n:",
"y, dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy,",
"v, K)): return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u,",
"a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u,",
"in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1])",
"dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free",
"dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g ], v)",
"= dup_div(f, h, K) if dup_degree(r) > 0: return None else: g[i] =",
"in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def",
"g = dmp_exquo_ground(g, gcd, u, K) return gcd, f, g def dup_mirror(f, K):",
"K): \"\"\"Evaluate a polynomial at `x = a` in `K[x]` using Horner scheme.",
"= dup_degree(f) if n < m: return [] deriv, c = [], K.one",
"dup_extract(f, g, K) if df == 0 or dg == 0: return [gcd],",
"r = dmp_zero(v) while dup_degree(D) <= B: while True: a += K.one if",
"\"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return result",
"True: h, _ = dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h, u+1,",
"dup_div(f, h, K) if not r: cfg_, r = dup_div(g, h, K) if",
"K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of",
"dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du % 2 and",
"if K.is_one(P): r = R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p,",
"in enumerate(I_pos[i+1:]): while not (s >= v or t <= u): u, v",
"= quo(f, h) and cfg = quo(g, h) The algorithm is purely heuristic",
"\"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`,",
"dup_to_raw_dict(f) g = { s : K.one } r = n // s",
"order derivative in `x_0` of a polynomial in `K[X]`. \"\"\" if not u:",
"else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and a",
"g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g,",
"\"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in",
"u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f,",
"K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1",
"def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n, a",
"dup_strip([R]) e = dup_strip([e]) else: R = [R] e = [e] d =",
"K) p = dmp_pow(dmp_neg(lc, v, K), d, v, K) if not d: q",
"not None: return result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K)",
"< 0 or j > u: raise IndexError(\"-%s <= j < %s expected,",
"c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m,",
"= K.zero for c in f: cont = K.gcd(cont, c) if K.is_one(cont): break",
"for dense recursive polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import (",
"= dmp_eval(r, a, v, K) if not v: R = dup_strip([R]) e =",
"None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0` from GCD",
"abs(F(a, c) - F(b, d)) < eps else: cond = lambda a, b,",
"roots not supported over %s\" % K) if dup_degree(f) <= 0: return []",
"df = dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f,",
"f and g at certain points and computing (fast) integer GCD of those",
"1], len(monoms), repetition=True) for perm in perms: G = dict(F) for sign, monom",
"else: groups[x] = [(x, y, dx, dy)] upper, lower = [], [] for",
"K): \"\"\"Try to eliminate `x_0` from GCD computation in `K[X]`. \"\"\" df =",
"], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F2 ], K), dup_sign_variations([",
"dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R,",
"p, u, K) try: R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed:",
"= dup_mul_ground(f, common, K0) if not args.get('convert'): return common, f else: return common,",
"in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return",
"cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u,",
"t: s, t = t, s negative = False if s < 0:",
"h, K) if not r: cfg_, r = dup_div(g, h, K) if not",
"= -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems",
"%s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K)",
"dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating rectangles for all quadrants. \"\"\"",
"c**(m-k) f, g, m, d = g, h, k, m-k B.append(b) D.append(d) h",
"K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[X]`. \"\"\" if",
"c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff,",
"= dmp_exquo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX = 6 def",
"roots not supported over %s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero, x,",
"K): \"\"\"Refine a complex root using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ",
"<NAME>, <NAME>, Computer Algebra Systems and Algorithms for Algebraic Computation, Academic Press, London,",
"correct GCD. This gives cofactors as a side effect. References ========== .. [Liao95]",
"u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K),",
"= dup_LC(f, K) f = dup_to_raw_dict(f) g = { s : K.one }",
"A*c + d if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f",
"Quebec, Canada, 1995, pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g, K)",
"random import random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e.",
"h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r =",
"multiplicity[r]) for i, r in enumerate(lower): lower[i] = (r, multiplicity[r]) return upper, lower",
"dup_degree(f) m = dup_degree(g) if n < m: f, g = g, f",
"cff_, r = dup_div(f, h, K) if not r: cfg_, r = dup_div(g,",
"K), p) d = dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K)",
"K) res = dmp_quo(dmp_mul(res, p, v, K), q, v, K) return res, R",
"K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u,",
"return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h,",
"K) a, b, c, d = b, a+b, d, c+d i += 1",
"= k roots = multiplicity.keys() groups = {} for (x, y, dx, dy)",
"refinement algorithm. \"\"\" hx, hy = dx/2, dy/2 cx, cy = x +",
"fail to compute the GCD. This will be signaled by raising an exception.",
"in `K[x]`. \"\"\" if not f: return f if K.is_negative(dup_LC(f, K)): f =",
"= dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v, K), v,",
"else: coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f =",
"transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if not f: return [] h,",
"y, dx, dy, F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K) def",
"h, u, K) if all or dmp_degree(g, u) > 0: result.append((g, i)) i",
"b1, c1, d1 = a, a+b, c, c+d if not dup_eval(f, K.zero, K):",
"D h = dup_prem(f, g, K) h = dup_mul_ground(h, b, K) while h:",
"u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to",
"sign variations of `f` in `K[x]`. \"\"\" prev, k = K.zero, 0 for",
"if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return",
"a Sturm sequence at its origin. \"\"\" return [ dup_mirror(f, K) for f",
"..., f_n)`, where:: f = f_1 o f_2 o ... f_n = f_1(f_2(...",
"cofactors of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact:",
"c, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return",
"-G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f,",
"= dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du % 2 and dv %",
"polynomial at `x_0 = a` in `K[X]` using Horner scheme. \"\"\" if not",
"f in F4 ], K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K)",
"for sign, monom in zip(perm, monoms): if sign == -1: G[monom] = -G[monom]",
"K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while h:",
"K): \"\"\"Returns content and a primitive polynomial over a field. \"\"\" return K.one,",
"r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v, K) D",
"g, K) if df == 0 or dg == 0: return [gcd], f,",
"K) for f in F4 ], K), ] V0 = [ dup_sign_variations([ dup_eval(f,",
"interval `(s, t)`. \"\"\" if s == t: return (s, t) F =",
"p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if",
"dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if",
"sum(v1 - v0 for v1, v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f,",
"j < %s expected, got %s\" % (u, u, j)) return _rec_integrate_in(f, m,",
"the desired precision is reached. \"\"\" while dx >= eps and dy >=",
"= [], K.one, u-1 for i in xrange(0, m): c, n = c*K(n),",
"return F(b, d), F(b, d) f, g = dup_taylor(f, K.one, K), f a1,",
"univariate polynomials `f` and `g` in `Z[X]`, returns their GCD and cofactors, i.e.",
"dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a field",
"key=lambda r: r[0]) if not squarefree: for i, r in enumerate(upper): upper[i] =",
"a pair of polynomials in `K[x]`. \"\"\" fc = dup_content(f, K) gc =",
"0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K)",
"v0 for v1, v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y,",
"= dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g,",
"K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f else:",
"= K.one, K.one for b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv",
"by a real number `c`. \"\"\" return [ dup_taylor(f, c, K) for f",
"t)`. \"\"\" if s == t: return (s, t) F = K.get_field() a,",
"_rec_diff_eval(f, m, a, u, 0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended",
"K) if k == 1: roots.append((x, y, dx, dy, (F1, F2, F3, F4)))",
"f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f,",
"R = [R] e = [e] d = K.invert(dup_eval(D, a, K), p) d",
"return result fc, F = dup_primitive(f, K) gc, G = dup_primitive(g, K) c",
"`f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD:",
"a ring. \"\"\" if not u: return dup_rr_content(f, K) cont, v = K.zero,",
"dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of `f` and `g` modulo a",
"1 h = dmp_diff(f, 1, u, K) g, p, q = dmp_inner_gcd(f, h,",
"u: raise IndexError(\"-%s <= j < %s expected, got %s\" % (u, u,",
"dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import",
"s, t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f` in",
"or dmp_degree(g, u) > 0: result.append((g, i)) i += 1 if not args.get('include',",
"K) return h def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`.",
"]) v = dup_strip([ C.imag(c) for c in f ]) seq = [u,",
"by interpolation. The evaluation proces reduces f and g variable by variable into",
"u, K) if result is not None: return result df = dmp_degree(f, u)",
"u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a polynomial",
"F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy,",
"========== .. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial GCD, International Symposium",
"`K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g, K) J, (f, g) =",
"sqf = dmp_exquo(f, gcd, u, K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf,",
"not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return",
"`g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K)",
"dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s, i, v = 1, 1,",
"functional decompositions of polynomials are not unique, consider examples: 1. `f o g",
"x, y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack = [],",
"s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] = (s, t,",
"1.0 / bound else: return None def dup_inner_refine_real_root(f, (a, b, c, d), cond,",
"K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" cont = K.zero for",
"not P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower",
"and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g,",
"K0.get_ring() common = K1.one for c in f: common = K1.lcm(common, K0.denom(c)) if",
"k3 == 1: return (x, y, hx, hy, (F31, F32, F33, F34)) #",
"= a2, a1, b2, b1 c1, c2, d1, d2 = c2, c1, d2,",
"u-1 for i, c in enumerate(reversed(f)): n = i+1 for j in xrange(1,",
"dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise,",
"= K.gcd(cont, c) if K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns GCD",
"are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal",
"u, K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\")",
"c, d, i, F: i >= 1 for i, (u, v, k) in",
"def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in `K[X]`, useful over algebraic",
"= dup_mul_ground(h, gcd, K) return h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x))",
"c, v = [], K.one, u-1 for i in xrange(0, m): c, n",
"F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy,",
"u, K), a, u, K) return _rec_diff_eval(f, m, a, u, 0, j, K)",
"v, K) for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns",
"in `K[X]`. \"\"\" if j > u: raise IndexError(\"-%s <= j < %s",
"r def dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial in `K[x]`. \"\"\"",
"f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) h,",
"in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common,",
"K) h, r = dup_div(g, cfg, K) if not r: cff_, r =",
"dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial in `K[x]`. \"\"\" if not",
"over a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if",
"K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\"",
"prev, k = K.zero, 0 for coeff in f: if coeff*prev < 0:",
"_collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\"",
"u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g,",
"for j, (s, t, m) in enumerate(I_neg[i+1:]): while not (s >= v or",
"cff, K) if not r: cfg_, r = dup_div(g, h, K) if not",
"K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f` and `g` in",
"efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n, b = list(f), dup_degree(f), a",
"q = t + a - K.log(f[j], 2) Q.append(q // (j - i))",
"p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm",
"K0) if result is not None: return result K1 = K0.get_ring() cf, f",
"s : K.one } r = n // s for i in xrange(1,",
"K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if not",
"K1) r = dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m * cg**n, K1)",
"Computer Algebra Systems and Algorithms for Algebraic Computation, Academic Press, London, 1988, pp.",
"p+I*q direction. \"\"\" C = K.complex_domain() a, b = C(p, q), C(x, y)",
"y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one,",
"F42, F43, F44))) elif k4 > 1: stack.append((cx, y, hx, hy, k4, F41,",
"g, u, K): \"\"\"Try to eliminate `x_0` from GCD computation in `K[X]`. \"\"\"",
"0 or dg == 0: return [gcd], f, g f_norm = dup_max_norm(f, K)",
"_max: upper.append((x, y, dx, dy)) del group[i] break _min = min([ r[1] for",
"in roots: if x in groups: groups[x].append((x, y, dx, dy)) else: groups[x] =",
"else: roots, stack = [], [(a, b, c, d, f, k)] F =",
"h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c",
"f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h, c, 0, K) return",
"m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1,",
"def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v =",
"while True: h, _ = dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h,",
"over a ring. \"\"\" if not (f or g): return [], [], []",
"K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return h,",
"dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u) for",
"a, b = C(p, q), C(x, y) f = dup_convert(f, K, C) f",
"not ((x2 >= x1+dx1 or x2+dx2 <= x1) and (y2 >= y1+dy1 or",
"\"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f) g =",
"args.get('fast') if type(n) is not int: cond = lambda a, b, c, d,",
"@cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v",
"bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain() f",
"dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC,",
"dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v = dmp_LC(f,",
"f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic and homogeneous polynomials of at",
"K) h = dup_mul_ground(h, b, K) while h: k = dup_degree(h) R.append(h) lc",
"result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if i ==",
"( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub,",
"K): \"\"\"Refine a complex root until the desired precision is reached. \"\"\" while",
"K) return sorted([ (-v, -u) for (u, v) in I_neg ] + I_pos)",
"in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result is not None:",
"v, K) if not v: R = dup_strip([R]) e = dup_strip([e]) else: R",
"K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 ==",
"RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime from sympy.utilities import ( cythonized,",
"else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is",
"K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[x]`. \"\"\" if K.has_Field",
"= dup_LC(f, K) f = dup_monic(f, K) else: coeff, f = dup_primitive(f, K)",
"`LC(f)` in `K[x]`. \"\"\" if not f: return f lc = dup_LC(f, K)",
"// abs(dmp_ground_LC(g, u, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff =",
"primitive polynomial over a ring. \"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont):",
"s, f, K) t = dup_exquo(F, g, K) return s, t, h def",
"elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f,",
"= dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v,",
"d, i, F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K)",
"j > u: raise IndexError(\"-%s <= j < %s expected, got %s\" %",
"F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K)",
"K) result = dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a,",
"f: continue if not s-j in g: continue fc, gc = f[n+j-i], g[s-j]",
"= m, n R = [f, g] d = n - m b",
"u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\")",
"evaluation proces reduces f and g variable by variable into a large integer.",
"== 0: return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g,",
"multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return",
"= dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k))",
"g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g,",
"F2, F3, F4))) elif k > 1: stack.append((x, y, dx, dy, k, F1,",
"return dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f,",
"Systems and Algorithms for Algebraic Computation, Academic Press, London, 1988, pp. 124-128 \"\"\"",
"dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\" if m",
"c, v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return",
"= (s, t, m) I_neg[i] = (u, v, k) return sorted([ ((-v, -u),",
"r = R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v,",
"(dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s, i, v",
"quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c",
"g, k in factors: g = dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g,",
"`K[X]` polynomial modulo a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p,",
"return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s positive roots.",
"Horner scheme. \"\"\" if j < 0 or j > u: raise IndexError(\"-%s",
"in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw",
"else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition",
"n, m = m, n R = [f, g] d = n -",
"= dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f,",
"\\ [ (( u, v), k) for (u, v, k) in I_pos ])",
"return [ dup_mirror(f, K) for f in F ] def _dup_inner_zeros(F1, F2, F3,",
"K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative of a polynomial in",
"= dup_monic(f, K) else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f",
"cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont for c",
"in `Q[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if n",
"return coeff, [] result, i = [], 1 h = dmp_diff(f, 1, u,",
"else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial",
"Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K)",
"K) for f in F4 ], K), ] return sum(v1 - v0 for",
"= dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h, u, K) h =",
"(-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively",
"K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0)",
"F = dmp_content(f, u, K) G = dmp_LC(g, K) v = u -",
"= dup_root_lower_bound(f, K) if A is not None: A = K(int(A)) else: A",
"dup_sign_variations(f, K) if k == 1: a, b, c, d = a1, b1,",
"dup_exquo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial",
"in `K[x]` using subresultant PRS. \"\"\" if not f or not g: return",
"dy)] upper, lower = [], [] for group in groups.values(): while len(group) >",
"in F ] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return the",
"j < %s expected, got %s\" % (u, u, j)) return _rec_eval_in(f, a,",
"dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\" if not",
"def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f)",
"`Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`, returns their GCD and",
"K.zero, u-1 for c in f: gc = dmp_rr_ground_content(c, v, K) cont =",
"cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0)",
"= dup_taylor(f, A, K) b, d = A*a + b, A*c + d",
"zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return",
"eps and dy >= eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f, x,",
"polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K):",
"dx, dy, F def dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine a",
"if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) coeff = -coeff if",
"= dup_div(f, h, K) if not r: h = dup_mul_ground(h, gcd, K) return",
"of coefficients in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f, K)",
"efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n, a = list(f), dup_degree(f), -K.one",
"cont, [ dmp_exquo(c, cont, v, K) for c in f ] @cythonized(\"u\") def",
"if dmp_degree(f, u) <= 0: if args.get('include', False): return f else: return coeff,",
"dy, F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K,",
"g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K):",
"return x, y, dx, dy, F def dup_refine_complex_root(f, x, y, dx, dy, eps,",
"\"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return",
"from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import",
"enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return roots",
"for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not",
"s <= t: return (s, t) else: return (t, s) def dup_outer_refine_real_root(f, s,",
"origin of a Sturm sequence by a real number `c`. \"\"\" return [",
"K)): f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf",
"direction. \"\"\" C = K.complex_domain() a, b = C(p, q), C(x, y) f",
"K1.one for c in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f",
"return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K):",
"gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c,",
"k)] F = K.get_field() while stack: a, b, c, d, f, k =",
"] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm sequence at its",
"a ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f,",
"= dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) else: coeff, f =",
"if not u: return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ:",
"content and a primitive polynomial over a ring. \"\"\" cont = dmp_ground_content(f, u,",
"of real roots not supported over %s\" % K) if dup_degree(f) <= 0:",
"of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def",
"= K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one while P <= B:",
"x, v, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = []",
"A > 16: f = dup_scale(f, A, K) a, c, A = A*a,",
"= dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f, h, u, K) cfg",
"K): \"\"\"Refine a positive root of `f` given a Mobius transform. \"\"\" F,",
"continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast,",
"@cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of `f` and `g`",
"a, v, K) if not v: R = dup_strip([R]) e = dup_strip([e]) else:",
"K), R) s, i, v = 1, 1, u-1 p = dmp_one(v, K)",
"for u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g =",
"= r2 while not ((x2 >= x1+dx1 or x2+dx2 <= x1) and (y2",
"dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if du % 2 and dv",
"= _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 == 1: return",
"`cfg` such that:: h = gcd(f, g), cff = quo(f, h) and cfg",
"K.one, K.one for b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv =",
"GCD of coefficients in `K[X]`. \"\"\" if not u: return dup_content(f, K) if",
"= dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond,",
"K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k =",
"\"\"\" if not K.has_Field: raise DomainError('computation can be done only in a field')",
"perm in perms: G = dict(F) for sign, monom in zip(perm, monoms): if",
"@cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to",
"// abs(dup_LC(g, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f,",
"+ rest def dup_extract(f, g, K): \"\"\"Extracts common content from a pair of",
"dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u) def dup_monic(f,",
"dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem,",
"`K[X]`. \"\"\" if not u: return dup_integrate(f, m, K) if m <= 0",
"\"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation",
"+ 2) for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg",
"u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else:",
"dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K):",
"df = dup_degree(f) for s in xrange(2, df): if df % s !=",
"dup_mul_ground(f, common, K0) if not args.get('convert'): return common, f else: return common, dup_convert(f,",
"F2, F3, F4 = stack.pop() hx, hy = dx/2, dy/2 cx, cy =",
"u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result",
"v, K), v, K) _, p, q = dmp_inner_gcd(p, q, v, K) if",
"`K[x]` polynomial modulo a constant `p` in `K`. \"\"\" if K.is_ZZ: g =",
"def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`.",
"True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\")",
"= [], [] F_pos, F_neg = {}, {} for f, k in factors:",
"g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except",
"k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)) continue",
"dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K),",
"<= 0: return f n = dmp_degree(f, u) if n < m: return",
"u, K) if all or dmp_degree(g, u) > 0: result.append((g, i)) i +=",
"1, u, K), u, K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r,",
"not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u -",
"if not df: F = dmp_LC(f, K) G = dmp_content(g, u, K) else:",
"= dmp_degree(g, u) if df > 0 and dg > 0: return None",
"root of `f` given a Mobius transform. \"\"\" F, i = K.get_field(), 0",
"F3, F4, dx, dy, K) if k != n: return dup_inner_isolate_complex_roots(f, K) if",
"g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g,",
"dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one],",
"F2, F3, F4, hx, hy, K): \"\"\"Return the exact number of zeros in",
"g, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[x]`. \"\"\" return",
"% s != 0: continue h = _dup_right_decompose(f, s, K) if h is",
"def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a field.",
"K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff = -coeff if dup_degree(f)",
"`f` and `g` modulo a prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f,",
"return common, f else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f,",
"== 1: roots.append((cx, cy, hx, hy, (F11, F12, F13, F14))) elif k1 >",
"k2 == 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2,",
"\"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f,",
"g, u, K) else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K):",
"K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`.",
"**args) else: roots = [] _, factors = dup_sqf_list(f, K) for g, k",
"= _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r =",
"a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B: while True:",
"in `x_0` in `K[X]`. \"\"\" if not u: return dup_integrate(f, m, K) if",
"return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns",
"hx, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for",
"def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K) f",
"== 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast, K)) else: stack.append((a2,",
"g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and",
"e = [e] d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d,",
"v, i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f,",
"K) except HomomorphismFailed: continue if K.is_one(P): r = R else: r = dmp_apply_pairs(r,",
"(s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K) def dup_refine_real_root(f,",
"functional composition `f(g)` in `K[X]`. \"\"\" if not u: return dup_compose(f, g, K)",
"k1 - r a2, b2, c2, d2 = b, a+b, d, c+d if",
"complex root refinement algorithm. \"\"\" hx, hy = dx/2, dy/2 cx, cy =",
"cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a",
"@cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a field in",
"dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc,",
"m <= 0: return f n = dmp_degree(f, u) if n < m:",
"if not u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g),",
"of `f` and `g` modulo a prime `p`. \"\"\" if not u: return",
"can be done only in an algebraic domain') F, monoms, polys = dmp_to_dict(f,",
"j in xrange(0, i): f[j+1] += a*f[j] return f def dup_transform(f, p, q,",
"return f n = dmp_degree(f, u) if n < m: return dmp_zero(u) deriv,",
"dx1, dy1, F1, K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1,",
"@cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\"",
"i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v,",
"x, u, K) gg = dmp_eval(g, x, u, K) v = u -",
"f, (a, b, c, d), cond, fast, K)] else: roots, stack = [],",
"in enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r in enumerate(lower): lower[i] =",
"= 1, 1, u-1 p = dmp_one(v, K) q = dmp_one(v, K) for",
"K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" if not u:",
"[], [K.one] else: return dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f,",
"dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c,",
">= eps and dy >= eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f,",
"x2, y2, dx2, dy2, F2 = r2 while not ((x2 >= x1+dx1 or",
"`f` given an interval `(s, t)`. \"\"\" if s == t: return (s,",
"of `f` in `x_0` in `K[X]`. \"\"\" if not u: return dup_integrate(f, m,",
"algorithm. \"\"\" hx, hy = dx/2, dy/2 cx, cy = x + hx,",
"if y == _min: lower.append((x, y, dx, dy)) del group[i] break upper =",
"t, m) I_neg[i] = (u, v, k) return sorted([ ((-v, -u), k) for",
"v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v, K)",
"h, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K)",
"= dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2]",
"dup_convert(f, K, C) f = dup_taylor(f, b, C) f = dup_scale(f, a, C)",
"a: return dmp_TC(f, K) result, v = dmp_LC(f, K), u-1 for coeff in",
"f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial",
"len(roots) == n: eps = args.get('eps') if eps is not None: for i,",
"at `x_0 = a` in `K[X]` using Horner scheme. \"\"\" if not u:",
"g, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" result =",
"d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K) d =",
"dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if",
"not u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return f h =",
"= [], K.one for i in xrange(0, m): c, n = c*K(n), n-1",
"R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular",
"return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a",
"def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0` from GCD computation in",
"f, h = result F = [h] + F else: break return [f]",
"if R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s, i = 1, 1",
"= dup_sign_variations(f, K) if k == 1: a, b, c, d = a1,",
"\"\"\"Evaluate a polynomial at `x_j = a_j, ...` in `K[X]`. \"\"\" if not",
"x, y, dx, dy, F, K): \"\"\"One bisection step of complex root refinement",
"hx, y + hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy",
"i in xrange(n-1, -1, -1): f[i], b = b*f[i], b*a return f def",
"q) b = -lc * c**(m-k) f, g, m, d = g, h,",
"integral of `f` in `x_0` in `K[X]`. \"\"\" if not u: return dup_integrate(f,",
"dup_inner_gcd(p, h, K) if all or dup_degree(g) > 0: result.append((g, i)) i +=",
"if not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m =",
"dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1, 1, K),",
"G = dmp_content(g, u, K) else: F = dmp_content(f, u, K) G =",
"field') a, b = [K.one], [] while g: q, r = dup_div(f, g,",
"f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of",
"\"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m, v, K) w, i =",
"dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in `K[x]`. Given an univariate polynomial",
"f, n, a = list(f), dup_degree(f), -K.one for i in xrange(n-1, -1, -1):",
"u - 1 h = dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf,",
"computes the polynomial GCD by evaluating polynomials f and g at certain points",
"<= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f,",
"(dup_LC(R[-1], K), R) s, i = 1, 1 p, q = K.one, K.one",
"dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from",
"-c h = dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K) cfg =",
"s, t = t, s negative = False if s < 0: if",
"s == t: return (s, t) F = K.get_field() a, c = F.numer(s),",
"u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else: f, s = dmp_compose(f, F,",
"p, u-1, K) for c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p,",
"u, K): \"\"\"Evaluate a polynomial at `x_j = a_j, ...` in `K[X]`. \"\"\"",
"or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K)",
"R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of",
"= dup_mul_ground(g, coeff, K) return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u,",
"v, K) _, p, q = dmp_inner_gcd(p, q, v, K) if s <",
"K) if result is not None: return result fc, F = dup_primitive(f, K)",
"(cx, y, hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots in (%s,",
"if not u: return dup_content(f, K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f,",
"GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result is not",
"]) for i, (x, y, dx, dy) in enumerate(group): if y == _min:",
"u, K1, K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0)",
"over a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f,",
"K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f,",
"_dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not",
"u, K): \"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\" if not u:",
"K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K),",
"square-free part of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f",
"i, F: abs(F(a, c) - F(b, d)) < eps else: cond = lambda",
"* cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def",
"i): f[j+1] += a*f[j] return f def dup_transform(f, p, q, K): \"\"\"Evaluate functional",
"v = u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c",
"is not None: g = _dup_left_decompose(f, h, K) if g is not None:",
"dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return x,",
"d = g, h, k, m-k B.append(b) D.append(d) h = dup_prem(f, g, K)",
"dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict,",
"_rec_eval_in(c, a, v, i, j, K) for c in g ], v) @cythonized(\"u\")",
"* f(p/q)` in `K[x]`. \"\"\" if not f: return [] h, Q =",
"%s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 =",
"x, y, dx, dy, F def dup_refine_complex_root(f, x, y, dx, dy, eps, K):",
"K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a polynomial in",
"dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc)",
"for c in f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v,",
"characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`, where:: f = f_1 o",
"> 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R)",
"lc, i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K),",
"0 and dg > 0: return None if not (df or dg): F",
"[-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD",
"if a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1,",
"== j: return dmp_eval(g, a, v, K) v, i = v-1, i+1 return",
"elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD:",
"du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u)",
"len(f), K.one, [] if dup_LC(f, K) < 0: f = dup_neg(f, K) f",
"F, **args) else: roots = [] _, factors = dup_sqf_list(f, K) for g,",
"a, b, c, d, i, F: i >= n s, t = dup_outer_refine_real_root(f,",
"F2), k2) roots[i] = (f1, (x1, y1, dx1, dy1, F1), k1) multiplicity =",
"= dup_convert(h, K1, K0) c = dup_LC(h, K0) h = dup_monic(h, K0) cff",
"cont for c in f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont,",
"and gg: h = K.gcd(ff, gg) cff = ff // h cfg =",
"== _min: lower.append((x, y, dx, dy)) del group[i] break upper = sorted(upper, key=lambda",
"_dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a field.",
"K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients",
"dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f,",
"_dup_sturm_shift(F2, hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1",
"number of zeros in the given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f,",
"roots[i] = (f1, (x1, y1, dx1, dy1, F1), k1) multiplicity = {} for",
"in enumerate(group): if y == _max: upper.append((x, y, dx, dy)) del group[i] break",
"h, K) all = args.get('all', False) while True: d = dup_diff(p, 1, K)",
"K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if",
"lc = dup_LC(f, K) if K.is_one(lc): return f else: return dup_quo_ground(f, lc, K)",
"in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite",
"while dup_degree(D) <= B: while True: a += K.one if a == p:",
"K): \"\"\"Computes functional decomposition of `f` in `K[x]`. Given an univariate polynomial `f`",
"return R, B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two",
"- m b = (-K.one)**(d+1) c = -K.one B, D = [b], [d]",
"K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of",
"= 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD",
"zero, returns tuple `(f_1, f_2, ..., f_n)`, where:: f = f_1 o f_2",
"t) if s > t: s, t = t, s negative = False",
"0: result.append((g, i)) i += 1 if not args.get('include', False): return coeff, result",
"f, k)] F = K.get_field() while stack: a, b, c, d, f, k",
"`K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd",
"if not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg",
"= stack.pop() hx, hy = dx/2, dy/2 cx, cy = x + hx,",
"F(b, d) if s <= t: return (s, t) else: return (t, s)",
"// h cfg = gg // h h = _dup_zz_gcd_interpolate(h, x, K) h",
"h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0) h =",
"= dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f,",
"-1): f[i], a = a*f[i], -a return f def dup_scale(f, a, K): \"\"\"Evaluate",
"g, K0) if result is not None: return result K1 = K0.get_ring() cf,",
"k) for (u, v) in I_pos ]) I_pos, I_neg = [], [] F_pos,",
"h % x if g > x // 2: g -= x f.insert(0,",
"Fx F12 = _dup_sturm_shift(F2, hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy,",
"f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from a",
"1, K), 1 k1 = dup_sign_variations(f1, K) k2 = k - k1 -",
"if not u: return dup_rr_content(f, K) cont, v = K.zero, u-1 for c",
"h, u, K) return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x,",
"not j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f, m,",
"for c in f: result *= a result += c return result @cythonized(\"u,v\")",
"The polynomial GCD is recovered from the integer image by interpolation. The final",
"c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u,",
"True: r = randfloat() if r < 0.5: break x, y, dx, dy",
"h, u, K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K):",
"j in xrange(0, i): if not n+j-i in f: continue if not s-j",
"polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else:",
"stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate",
"a, C) u = dup_strip([ C.real(c) for c in f ]) v =",
"elif k > 1: stack.append((x, y, dx, dy, k, F1, F2, F3, F4))",
"h, r = dup_div(f, cff, K) if not r: cfg_, r = dup_div(g,",
"K) f, g, m, d = g, h, k, m-k B.append(b) D.append(d) h",
"return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f,",
"return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root",
"enumerate(I_pos[i+1:]): while not (s >= v or t <= u): u, v =",
"dy, F, eps, K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args):",
"of `f` in `K[x]`. Given an univariate polynomial `f` with coefficients in a",
"u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u,",
"algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g,",
"[f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q",
"cg), K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic",
"-coeff if dmp_degree(f, u) <= 0: if args.get('include', False): return f else: return",
"c, c+d if not dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1) k",
"+ m*N D, a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <=",
"1, u, K) g, p, q = dmp_inner_gcd(f, h, u, K) all =",
"@cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a",
"dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if",
"= dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K) return gcd, f, g",
"if k == 1: roots.append((x, y, dx, dy, (F1, F2, F3, F4))) elif",
"result = _dmp_ff_trivial_gcd(f, g, u, K) if result is not None: return result",
"F(b, d)) < n else: cond = lambda a, b, c, d, i,",
"or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g, u,",
"a positive root of `f` given a Mobius transform. \"\"\" F, i =",
"[b], [d] if not f or not g: return R, B, D h",
"= dmp_zeros(m, u-1, K), u-1 for i, c in enumerate(reversed(f)): n = i+1",
"R, B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero,",
"-= x f.insert(0, g) h = (h-g) // x return f @cythonized(\"i,df,dg\") def",
"- F(b, d)) < n else: cond = lambda a, b, c, d,",
"sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued fractions approach. \"\"\"",
"K) k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if k !=",
"K.exquo((-lc)**d, q) b = -lc * c**(m-k) f, g, m, d = g,",
"else: stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args):",
"> 0: return None else: g[i] = dup_LC(r, K) f, i = q,",
"x**m = x**m o x**n` 3. `T_n o T_m = T_m o T_n`",
"= a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if not",
"in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order",
"g, p, q = dup_inner_gcd(f, h, K) all = args.get('all', False) while True:",
"def dup_sign_variations(f, K): \"\"\"Compute the number of sign variations of `f` in `K[x]`.",
"dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real roots not",
"= dmp_zero(v), K.one, K.one while P <= B: p = K(nextprime(p)) while not",
">= v or t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step,",
"dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f,",
"K): \"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0]",
"= dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg,",
"K) D = dup_trunc(D, p, K) return r def _collins_crt(r, R, P, p,",
"y1, dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2),",
"g] d = n - m b = (-K.one)**(d+1) c = -K.one B,",
"r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd,",
"f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial",
"return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm sequence by",
"recursive polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip,",
"K) def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a field.",
"to verify if the interpolated polynomial is the correct GCD. This gives cofactors",
"for j in xrange(0, i): if not n+j-i in f: continue if not",
"c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K):",
"K) return a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`.",
"h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f,",
"k > 1: stack.append((x, y, dx, dy, k, F1, F2, F3, F4)) while",
"s = -s lc, i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b,",
"not None: return result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1)",
"f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif",
"content and a primitive polynomial over a ring. \"\"\" if dmp_zero_p(f, u): return",
"K) coeff = -coeff if dmp_degree(f, u) <= 0: if args.get('include', False): return",
"i = K.get_field(), 0 while not c or not cond(a, b, c, d,",
"coeff = K.zero for j in xrange(0, i): if not n+j-i in f:",
"K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff = -coeff if dup_degree(f) <= 0:",
"cases in GCD algorithm over a ring. \"\"\" if not (f or g):",
"[K.zero]*m for i, c in enumerate(reversed(f)): n = i+1 for j in xrange(1,",
"j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a,",
"cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K)",
"gcd, K) g = dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\") def",
"u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m = dmp_degree(g, u)",
"h return None def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in `K[x]`.",
"def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT for Collins's resultant algorithm.",
"K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" if not u:",
"dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g, u, K0, K1) f =",
"= dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K)",
"a1, b2, b1 c1, c2, d1, d2 = c2, c1, d2, d1 f1,",
"sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers in `K[X]`.",
"in enumerate(reversed(f)): n = i+1 for j in xrange(1, m): n *= i+j+1",
"ring. \"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else:",
"K) for f in F ] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy,",
"(f1, r1, k1) in enumerate(roots): x1, y1, dx1, dy1, F1 = r1 for",
"K1.lcm(common, K0.denom(c)) else: w = v-1 for c in g: common = K1.lcm(common,",
"= dup_mul_ground(h, b, K) while h: k = dup_degree(h) R.append(h) lc = dup_LC(g,",
"of a Sturm sequence by a real number `c`. \"\"\" return [ dup_taylor(f,",
"= dmp_degree(f, u) dg = dmp_degree(g, u) if df > 0 and dg",
"v, K) for c in f ], u) def dup_monic(f, K): \"\"\"Divides all",
"dx, dy) in enumerate(group): if y == _min: lower.append((x, y, dx, dy)) del",
"dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2, y2,",
"dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p` in `K`.",
"@cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field",
"g, i = {}, 0 while f: q, r = dup_div(f, h, K)",
"= n - m v = u - 1 b = dmp_pow(dmp_ground(-K.one, v),",
"dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD:",
"dup_rr_content(f, K) cont, v = K.zero, u-1 for c in f: gc =",
"= dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement not",
"fc, f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K) c",
"g, p, q = dmp_inner_gcd(f, h, u, K) all = args.get('all', False) while",
"real root's approximating interval to the given precision. \"\"\" if K.is_QQ: (_, f),",
"i, F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f",
"++ F11 = Fx F12 = _dup_sturm_shift(F2, hx, K) F13 = F3 F14",
"dy2, F2 = r2 while not ((x2 >= x1+dx1 or x2+dx2 <= x1)",
"(a1, b1, c1, d1), cond, fast, K)) else: stack.append((a1, b1, c1, d1, f1,",
"f(p/q)` in `K[x]`. \"\"\" if not f: return [] h, Q = [f[0]],",
"tuple `(f_1, f_2, ..., f_n)`, where:: f = f_1 o f_2 o ...",
"K.is_ZZ: g = [] for c in f: c = c % p",
"u) dw = dmp_degree(R[i+1], u) if du % 2 and dv % 2:",
"s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u,",
"\"\"\"Returns GCD of coefficients over a field. \"\"\" if not f: return K.zero",
"associated Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x)",
"\"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if not u: return",
"break _min = min([ r[1] for r in group ]) for i, (x,",
"else: raise DomainError(\"isolation of complex roots not supported over %s\" % K) F1",
"`LC(f)` in `K[X]`. \"\"\" if not u: return dup_monic(f, K) if dmp_zero_p(f, u):",
"h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck')",
"df == 0 or dg == 0: return [gcd], f, g f_norm =",
"cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from",
"correct GCD. This gives cofactors of the input polynomials as a side effect.",
"= dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p, i)) break g, p,",
"if K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\")",
"if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff = -coeff if dup_degree(f) <=",
"gg) cff = ff // h cfg = gg // h h =",
"_rec_eval_tail(f, 0, A, u, K) if u == len(A)-1: return e else: return",
"== n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v)",
"polynomial in `K[X]`. \"\"\" if j < 0 or j > u: raise",
"points and computing (fast) integer GCD of those evaluations. The polynomial GCD is",
"= -B+r, -B-r, 2*B+r, 2*B+r roots, stack = [], [] F1 = _dup_inner_sturm(f,",
"else: q = dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q, v, K)",
"= _dup_ff_trivial_gcd(f, g, K) if result is not None: return result h =",
"K), s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm",
"fast, K)] else: roots, stack = [], [(a, b, c, d, f, k)]",
"= dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h,",
"algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u)",
"= dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)),",
"not f: return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd =",
"if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f,",
"= dup_degree(f) if d <= 0: return K.zero else: s = (-1)**((d*(d-1)) //",
"= _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 == 1: roots.append((cx,",
"_), k) in roots: multiplicity[(x, y, dx, dy)] = k roots = multiplicity.keys()",
"= dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B = n*M +",
"= dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k == 0: continue",
"if not (f or g): return [], [], [] elif not f: return",
"len(factors) > 1: for i, (f1, r1, k1) in enumerate(roots): x1, y1, dx1,",
"u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K),",
"trivial cases in GCD algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f, u)",
"cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont,",
"_collins_crt, (P, p, K), v, K) P *= p return r @cythonized(\"u,n,m\") def",
"u, K) if u == len(A)-1: return e else: return dmp_strip(e, u -",
"u, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\" if",
"roots. \"\"\" n, t, P = len(f), K.one, [] if dup_LC(f, K) <",
"dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h",
"== 1: return (cx, y, hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no",
"+ 2) for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K)",
"primitive polynomial. \"\"\" cont, v = dmp_content(f, u, K), u-1 if dmp_zero_p(f, u)",
"n): if f[i] >= 0: continue a, Q = K.log(-f[i], 2), [] for",
"eps is not None: cond = lambda a, b, c, d, i, F:",
"K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f` and `g` in",
"def dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if K.has_Field or",
"A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f,",
"return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content",
"p, q = dmp_inner_gcd(p, q, v, K) if s < 0: p =",
"return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K):",
"if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u,",
"polynomial GCD and cofactors of `f` and `g` in `K[x]`. \"\"\" if K.has_Field",
"for coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv",
"c in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce",
"1, K) k2 = dup_sign_variations(f2, K) if k1 < k2: a1, a2, b1,",
"dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k == 0: continue if",
"of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g,",
"j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2",
"by `LC(f)` in `K[X]`. \"\"\" if not u: return dup_monic(f, K) if dmp_zero_p(f,",
"True: d = dup_diff(p, 1, K) h = dup_sub(q, d, K) if not",
"gcd, u, K) g = dmp_exquo_ground(g, gcd, u, K) return gcd, f, g",
"g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant",
"= K.get_field(), 0 while not c or not cond(a, b, c, d, i,",
"K): f = dup_rshift(f, 1, K) a, b, c, d = b, a+b,",
"group[i] break _min = min([ r[1] for r in group ]) for i,",
"v, K) r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a],",
"len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return []",
"p for c in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u,",
"K) g = dmp_exquo_ground(g, gcd, u, K) return gcd, f, g def dup_mirror(f,",
"- k1 - r a2, b2, c2, d2 = b, a+b, d, c+d",
"C.real(c) for c in f ]) v = dup_strip([ C.imag(c) for c in",
"if coeff*prev < 0: k += 1 if coeff: prev = coeff return",
"constant `p` in `K`. \"\"\" if K.is_ZZ: g = [] for c in",
"eps is not None: for i, (x, y, dx, dy, F) in enumerate(roots):",
"= lambda a, b, c, d, i, F: i >= n s, t",
"(x, y, dx, dy) in enumerate(group): if y == _min: lower.append((x, y, dx,",
"polynomial at `x_j = a` in `K[X]` using Horner scheme. \"\"\" if j",
"= dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v) == n: G",
"dmp_zero(v), K.one, K.one while P <= B: p = K(nextprime(p)) while not (a",
"homogeneous polynomials of at least second degree. Unlike factorization, complete functional decompositions of",
"of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f,",
"res = dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res, R def dup_resultant(f,",
"dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in",
"K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], []",
"= _dup_rr_trivial_gcd(f, g, K) if result is not None: return result df =",
"London, 1988, pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation can be done",
"dmp_quo(dmp_mul(res, p, v, K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f,",
"v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1]",
"in GCD algorithm over a ring. \"\"\" if not (f or g): return",
"return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f,",
"return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g ],",
"(s, t) F = K.get_field() a, c = F.numer(s), F.denom(s) b, d =",
"i == j: return dmp_eval(g, a, v, K) v, i = v-1, i+1",
"0, K, front=True) r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break",
"// 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in",
"dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _ =",
"monom in zip(perm, monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u,",
"K), f a1, b1, c1, d1 = a, a+b, c, c+d if not",
"dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div,",
"a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v,",
"\"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c,",
"zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return",
"roots: if x in groups: groups[x].append((x, y, dx, dy)) else: groups[x] = [(x,",
"USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0]",
"dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u), k) for (u, v) in",
"v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s,",
"2*B+r, 2*B+r roots, stack = [], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x,",
"def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a field in `K[X]`.",
"= dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else: f, s",
"polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K):",
"(g - b)` 2. `x**n o x**m = x**m o x**n` 3. `T_n",
"return s, t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f`",
"D = [b], [d] if not f or not g: return R, B,",
"dup_sign_variations(f2, K) if k1 < k2: a1, a2, b1, b2 = a2, a1,",
"= dmp_eval(g, x, u, K) v = u - 1 if not (dmp_zero_p(ff,",
"K) if negative: return (-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f,",
"= K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th",
"u, K): \"\"\"Computes polynomial LCM over a ring in `K[X]`. \"\"\" fc, f",
"not None: return 1.0 / bound else: return None def dup_inner_refine_real_root(f, (a, b,",
"q), C(x, y) f = dup_convert(f, K, C) f = dup_taylor(f, b, C)",
"= dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0)",
"return (K.zero, []) R, B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) >",
"= [ c % p for c in f ] return dup_strip(g) @cythonized(\"u\")",
"q = dup_mul_ground(q, c, K) h = dup_add(h, q, K) return h def",
"u, K) coeff = -coeff if dmp_degree(f, u) <= 0: if args.get('include', False):",
"return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued fractions approach.",
"j, (s, t, m) in enumerate(I_neg[i+1:]): while not (s >= v or t",
"< eps else: cond = lambda a, b, c, d, i, F: True",
"False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots =",
"dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd, K) return h,",
"break else: f, s = dup_taylor(f, -K.unit, K), s+1 return s, f, r",
"_dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q",
"dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)],",
"= dx/2, dy/2 cx, cy = x + hx, y + hy Fx",
"k != n: return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y, dx,",
"m, d = g, h, k, m-k B.append(b) D.append(d) h = dup_prem(f, g,",
"u, K): \"\"\"Computes indefinite integral of `f` in `x_j` in `K[X]`. \"\"\" if",
"g, u, K1) h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u,",
"K) c = dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c,",
"n - m b = (-K.one)**(d+1) c = -K.one B, D = [b],",
"0, K.dom) while True: h, _ = dmp_inject(f, 0, K, front=True) r =",
"K.zero, K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if k1",
"algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of",
"cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`.",
"`K[X]`. \"\"\" if not u: return dup_lcm(f, g, K) if K.has_Field or not",
"@cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral of `f` in",
"content from a pair of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u,",
"K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if not",
"return dup_eval(f, a, K) if not a: return dmp_TC(f, K) result, v =",
"f n = dmp_degree(f, u) if n < m: return dmp_zero(u) deriv, c,",
"LCM of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact:",
"K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r,",
"y, hx, hy, k4, F41, F42, F43, F44)) if len(roots) == n: eps",
"dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p,",
"= [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c,",
"USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return",
"F4 ], K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for f",
"K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j,",
"0 for coeff in f: if coeff*prev < 0: k += 1 if",
"\"\"\" while dx >= eps and dy >= eps: x, y, dx, dy,",
"(s, t, m) I_neg[i] = (u, v, k) return sorted([ ((-v, -u), k)",
"= _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx,",
"if not args.get('convert'): return common, f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\")",
"not c or not cond(a, b, c, d, i, F): A = dup_root_lower_bound(f,",
"try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u,",
"return s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial",
"dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf, h, v, K) for cf",
"= K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K),",
"_, p, q = dmp_inner_gcd(p, q, v, K) if s < 0: p",
"dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground,",
"Press, London, 1988, pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation can be",
"ff // h cfg = gg // h h = _dup_zz_gcd_interpolate(h, x, K)",
"all = args.get('all', False) while True: d = dmp_diff(p, 1, u, K) h",
"of `f` in `F[x]`. Given an univariate, square-free polynomial `f(x)` returns the associated",
"u, K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return",
"returns the associated Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) =",
"= dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u, K) h = dmp_subresultants(f,",
"a Mobius transform. \"\"\" F, i = K.get_field(), 0 while not c or",
"F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 =",
"i, c in enumerate(reversed(f)): n = i+1 for j in xrange(1, m): n",
"trivial cases in GCD algorithm over a field. \"\"\" zero_f = dmp_zero_p(f, u)",
"gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u - 1 n =",
"y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K)",
"using Horner scheme. \"\"\" if j < 0 or j > u: raise",
"K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f,",
"a large integer. The final step is to verify if the interpolated polynomial",
"gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from",
"u, K) h = dmp_subresultants(f, g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc,",
"h, K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes",
"dup_add(h, q, K) return h def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)`",
"[(x, y, dx, dy)] upper, lower = [], [] for group in groups.values():",
"return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in `K[X]`.",
"n = c*K(n), n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v,",
"and A > 16: f = dup_scale(f, A, K) a, c, A =",
"and dy >= eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f, x, y,",
"K1 is None: K1 = K0.get_ring() common = K1.one for c in f:",
"not u: return dup_lcm(f, g, K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f,",
"K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a ring in `K[x]`.",
"elif not K.is_ZZ: raise DomainError(\"isolation of real roots not supported over %s\" %",
"\"\"\" if not u: return dup_rr_content(f, K) cont, v = K.zero, u-1 for",
"d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be exactly one",
"**args) if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f =",
"return (s, t) else: return (t, s) def dup_outer_refine_real_root(f, s, t, cond, fast,",
"in f ], u) def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in",
"in g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial",
"i in xrange(n, 0, -1): for j in xrange(0, i): f[j+1] += a*f[j]",
"F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F2 ], K),",
"in F4 ], K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for",
"in xrange(n-1, -1, -1): f[i], a = a*f[i], -a return f def dup_scale(f,",
"K): return cont, f else: return cont, [ dmp_exquo(c, cont, v, K) for",
"dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm",
"not cond(a, b, c, d, i, F): A = dup_root_lower_bound(f, K) if A",
"= dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u, K) try: R",
"K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _, h =",
"[] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return",
"= 2*max(abs(c)/lc for c in f) while True: r = randfloat() if r",
"= False if s < 0: if t <= 0: f, s, t,",
"_dup_ff_trivial_gcd(f, g, K) if result is not None: return result h = dup_subresultants(f,",
"K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f,",
"tools for dense recursive polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import",
"g = h % x if g > x // 2: g -=",
"u, K) v = u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg,",
"== 1: roots = [dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)]",
"+ 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f)",
"if not v: R = dup_strip([R]) e = dup_strip([e]) else: R = [R]",
"F: abs(F(a, c) - F(b, d)) < n else: cond = lambda a,",
"if result is not None: return result K1 = K0.get_ring() cf, f =",
"F3, F4, hx, hy, K): \"\"\"Return the exact number of zeros in the",
"= _dmp_ff_trivial_gcd(f, g, u, K0) if result is not None: return result K1",
"g.append(c - p) else: g.append(c) else: g = [ c % p for",
"K) h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r",
"return K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if",
"roots, stack = [], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K)",
"at x+I*y in p+I*q direction. \"\"\" C = K.complex_domain() a, b = C(p,",
"(F41, F42, F43, F44)) raise RefinementFailed(\"no roots in (%s, %s) x (%s, %s)",
"dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero,",
"K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg,",
"dmp_degree(f, u) m = dmp_degree(g, u) if n < m: f, g =",
"= _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 == 1: roots.append((x,",
"Evaluation of the heuristic polynomial GCD, International Symposium on Symbolic and Algebraic Computation",
"g: q, r = dup_div(f, g, K) f, g = g, r a,",
"K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K)",
"1, K) g, p, q = dup_inner_gcd(f, h, K) all = args.get('all', False)",
"@cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if",
"cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f,",
"c % p for c in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f,",
"1: _max = max([ r[1] for r in group ]) for i, (x,",
"`g` in `Z[X]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and",
"v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in",
"], K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for f in",
"g ] if i < u - len(A) + 1: return h else:",
"v, K) w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i,",
"b*f[i], b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x",
"K0, K1) cg, g = dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u,",
"b, v, K) for ch in h ] return R, B, D @cythonized(\"u\")",
"using subresultants over a field. \"\"\" if not u: return dup_ff_prs_gcd(f, g, K)",
"len(group) > 1: _max = max([ r[1] for r in group ]) for",
"fc, f = dup_primitive(f, K) gc, g = dup_primitive(g, K) c = K.lcm(fc,",
"F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm sequence at",
"dw = dup_degree(R[i+1]) if du % 2 and dv % 2: s =",
"K) if result is not None: return result df = dup_degree(f) dg =",
"of a polynomial in `K[x]`. \"\"\" d = dup_degree(f) if d <= 0:",
"not u: return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return",
"(t, s) def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a positive root",
"_, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h =",
"K.log(f[j], 2) Q.append(q // (j - i)) t += 1 if not Q:",
"K): \"\"\"Evaluate a polynomial at `x_0 = a` in `K[X]` using Horner scheme.",
"dmp_degree(f, u), u-1 if d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1))",
"USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two",
"F_neg[k] = f, g step = lambda a, b, c, d, i, F:",
"K): \"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\" d = dup_degree(f) if",
"u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g,",
"= K.complex_domain() a, b = C(p, q), C(x, y) f = dup_convert(f, K,",
"a field. \"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns content and a",
"cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\")",
"K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM",
"result df = dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f, g,",
"one root on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c,",
"r a2, b2, c2, d2 = b, a+b, d, c+d if k2 >",
"K), [], [dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)], []",
"a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a,",
"K1): \"\"\"XXX\"\"\" common = K1.one if not v: for c in g: common",
"dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero,",
"sorted([ ((-v, -u), k) for (u, v) in I_neg ] + \\ [",
"\"\"\"Isolate real roots using continued fractions approach. \"\"\" if K.is_QQ: (_, f), K",
"def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in `K[x]`. Given an univariate",
"g, K): \"\"\"Computes subresultant PRS of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f,",
"< 0: if t <= 0: f, s, t, negative = dup_mirror(f, K),",
"= dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i]",
"NotInvertible, DomainError ) from sympy.ntheory import nextprime from sympy.utilities import ( cythonized, variations",
"c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r,",
"hy, K) if k4 == 1: roots.append((cx, y, hx, hy, (F41, F42, F43,",
"and `T_m` are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition",
"u), u-1 if d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) //",
"if g > x // 2: g -= x f.insert(0, g) h =",
"< 0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u,",
"raise IndexError(\"-%s <= j < %s expected, got %s\" % (u, u, j))",
"t, negative = dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't refine a",
"= dup_taylor(f, -K.unit, K), s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u,",
"- i)) t += 1 if not Q: continue P.append(min(Q)) if not P:",
"== p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K)",
"a polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff = dup_LC(f,",
"cond, fast, K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K)",
"= dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g,",
"g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) + 29 x =",
"d, i, F): A = dup_root_lower_bound(f, K) if A is not None: A",
"@cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over",
"K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) coeff = -coeff",
"<= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t",
"cy, hx, hy, (F21, F22, F23, F24)) # Quadrant #3: -- F31 =",
"q = c**(d-1) c = K.exquo((-lc)**d, q) b = -lc * c**(m-k) f,",
"= dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2, y2, dx2, dy2, F2",
"u, K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" zero_f",
"s, t, cond, fast, K): \"\"\"Refine a positive root of `f` given an",
"in `K[X]` using Horner scheme. \"\"\" if j < 0 or j >",
"v, K) for cf in f ] cfg = [ dmp_exquo(cg, h, v,",
"which means it may fail to compute the GCD. This will be signaled",
"p if c > p // 2: g.append(c - p) else: g.append(c) else:",
"elif not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return",
"factors = dup_sqf_list(f, K) for g, k in factors: g = dup_convert(g, K,",
"f1, f2, k1, k2 = f2, f1, k2, k1 if k1 == 0:",
"The algorithm computes the polynomial GCD by evaluating polynomials f and g at",
"j < 0 or j > u: raise IndexError(\"-%s <= j < %s",
"g, u, K) if result is not None: return result df = dmp_degree(f,",
"only in a field') a, b = [K.one], [] while g: q, r",
"# Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K) F42 = F2 F43",
"dmp_ground_LC(g, u, K) v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p,",
"k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K):",
"y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K): \"\"\"Refine a complex",
"dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\" if",
"of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f,",
"f in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for f in F3",
"K) if not h: result.append((p, i)) break g, p, q = dup_inner_gcd(p, h,",
"\"\"\"Computes functional decomposition of `f` in `K[x]`. Given an univariate polynomial `f` with",
"K) _, p, q = dmp_inner_gcd(p, q, v, K) if s < 0:",
"= F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f,",
"\"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1], K) else: h = [",
"not (b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K)",
"dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff,",
"`K[X]`. \"\"\" if j < 0 or j > u: raise IndexError(\"-%s <=",
"= 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\"",
"f(x + b) o (g - b)` 2. `x**n o x**m = x**m",
"polynomials in `K[X]`. \"\"\" if not u: return dup_resultant(f, g, K) if K.has_Field:",
"field') f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]:",
"G, p, u, K) except HomomorphismFailed: continue if K.is_one(P): r = R else:",
"is not None: return result df = dmp_degree(f, u) dg = dmp_degree(g, u)",
"elif not g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD",
"`f` and `g` in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g, K)",
"K): \"\"\"Compute LMQ upper bound for `f`'s positive roots. \"\"\" n, t, P",
"v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if not v: for c in",
"dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f`",
"F = K.float_domain() else: raise DomainError(\"isolation of complex roots not supported over %s\"",
"], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a",
"h, K): \"\"\"XXX\"\"\" g, i = {}, 0 while f: q, r =",
"u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant",
"], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4 ], K), ]",
"F32, F33, F34))) elif k3 > 1: stack.append((x, y, hx, hy, k3, F31,",
"modulo a constant `p` in `K`. \"\"\" if not u: return dup_trunc(f, p,",
"all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for",
"cfg, K) if not r: cff_, r = dup_div(f, h, K) if not",
"f = dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return common, f else:",
"except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K):",
"K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns",
"= dup_mul_ground(q, c, K) h = dup_add(h, q, K) return h def dup_compose(f,",
"\"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can",
"K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def",
"except HomomorphismFailed: continue if K.is_one(P): r = R else: r = dmp_apply_pairs(r, R,",
"= [dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)] else: roots, stack",
"eps, K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint",
"n, lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in f)",
"[], [dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)], [] else:",
"dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term,",
"dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm,",
"q, v, K) if s < 0: p = dmp_neg(p, v, K) i",
"dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem,",
"y, hx, hy, k3, F31, F32, F33, F34)) # Quadrant #4: +- F41",
"x, v, K) f.insert(0, g) h = dmp_sub(h, g, v, K) h =",
"zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g,",
"<NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation 7 (1989), pp. 445-456",
"K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f,",
"def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating rectangles for all quadrants.",
"y, K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q direction. \"\"\" C =",
"a for i in xrange(n-1, -1, -1): f[i], b = b*f[i], b*a return",
"def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\"",
"`K_0` to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0, K1) if K1",
"dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM",
"\"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" zero_f = dmp_zero_p(f,",
"return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c in g",
"integral of `f` in `K[x]`. \"\"\" if m <= 0 or not f:",
"f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2",
"g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from a pair",
"dup_lcm(f, g, K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u, K)",
"x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f,",
"exact number of zeros in the given rectangle. \"\"\" V1 = [ dup_sign_variations([",
"f = dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u, K) h =",
"if not f: return [] h, Q = [f[0]], [[K.one]] for i in",
"from random import random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators,",
"x, K) gg = dup_eval(g, x, K) if ff and gg: h =",
"F2 = r2 while not ((x2 >= x1+dx1 or x2+dx2 <= x1) and",
"polynomial in `K[x]`. \"\"\" if not f: return f if K.is_negative(dup_LC(f, K)): f",
"real roots not supported over %s\" % K) if dup_degree(f) <= 0: return",
"if dmp_zero_p(f, u): return K.zero, f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f,",
"a2, b2, c2, d2 = b, a+b, d, c+d if k2 > 1",
"dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\" if not f:",
"for (_, (x, y, dx, dy, _), k) in roots: multiplicity[(x, y, dx,",
"if k == 0: return [] if k == 1: roots = [dup_inner_refine_real_root(",
"= dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff = -coeff",
"dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K): \"\"\"Refine a positive root of",
"K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f",
"\"\"\"Computes subresultant PRS of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u,",
"K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K)",
"g, K) return s, t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse",
"effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial GCD,",
"Canada, 1995, pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g, K) result",
"dup_taylor(f, -K.unit, K), s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K):",
"the correct GCD. This gives cofactors as a side effect. References ========== ..",
"g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0)",
"dmp_one(v, K) for b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv",
"is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if not",
"= dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r,",
"(f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g,",
"square-free part of a polynomial in `K[x]`. \"\"\" if not f: return f",
"= dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc,",
"K): \"\"\"m-th order derivative in `x_j` of a polynomial in `K[X]`. \"\"\" if",
"dmp_degree(f, u) <= 0: if args.get('include', False): return f else: return coeff, []",
"for cg in g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K):",
"1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors",
"\"\"\" if not u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return f",
"dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div,",
"K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf = dmp_exquo(f,",
"decomposition of a polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff",
"else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and",
"dup_degree(h) R.append(h) lc = dup_LC(g, K) if not d: q = c else:",
"_rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g,",
"subresultant PRS of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\")",
"lc**(dv*(1+d)) if s < 0: p = -p i = dup_degree(R[-2]) res =",
"dup_degree(g) gcd, f, g = dup_extract(f, g, K) if df == 0 or",
"`f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x),",
"`K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant",
"The algorithm is purely heuristic which means it may fail to compute the",
"K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg =",
"GCD of coefficients over a ring. \"\"\" if not u: return dup_rr_content(f, K)",
"if not d: q = c else: q = c**(d-1) c = K.exquo((-lc)**d,",
"K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[x]`. \"\"\" if K.has_Field",
"dy) in enumerate(group): if y == _max: upper.append((x, y, dx, dy)) del group[i]",
"field. \"\"\" if not f: return K.zero else: return K.one def dup_content(f, K):",
"g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and",
"0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x =",
"f = dup_taylor(f, b, C) f = dup_scale(f, a, C) u = dup_strip([",
"result, v = dmp_LC(f, K), u-1 for coeff in f[1:]: result = dmp_mul_ground(result,",
"denominators, i.e. transform `K_0` to `K_1`. \"\"\" if K1 is None: K1 =",
"`K[x]`, useful over algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must",
"dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground,",
"hy, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for",
"cff = [ dmp_exquo(cf, h, v, K) for cf in f ] cfg",
"def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g`",
"= dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s, g, K) else:",
"f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return dmp_quo_ground(f,",
"% p if c > p // 2: g.append(c - p) else: g.append(c)",
"k) return sorted([ ((-v, -u), k) for (u, v, k) in I_neg ]",
"g, u, K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g,",
"Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h =",
"result, i = [], 1 h = dmp_diff(f, 1, u, K) g, p,",
"False if s < 0: if t <= 0: f, s, t, negative",
"while True: d = dup_diff(p, 1, K) h = dup_sub(q, d, K) if",
"roots.append((x, y, hx, hy, (F31, F32, F33, F34))) elif k3 > 1: stack.append((x,",
"dy1, F1, K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1,",
"\"\"\"Refine a positive root of `f` given an interval `(s, t)`. \"\"\" if",
"u, K) return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)`",
"elif k2 > 1: stack.append((x, cy, hx, hy, k2, F21, F22, F23, F24))",
"[b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B, D h",
"gcd, K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts",
"+ b, A*c + d if not dup_eval(f, K.zero, K): return F(b, d),",
"(_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation",
"p, q = dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g, u) >",
"`p` in `K`. \"\"\" if K.is_ZZ: g = [] for c in f:",
"cont, v = dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v,",
"f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References",
"and g variable by variable into a large integer. The final step is",
"v, k) in I_neg ] + \\ [ (( u, v), k) for",
"HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return",
"`K`. \"\"\" if not u: return dup_trunc(f, p, K) v = u-1 return",
"None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases",
"dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[X]`.",
"dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)):",
"c, d, i, F: i >= n s, t = dup_outer_refine_real_root(f, s, t,",
"= -s lc, i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv,",
"df): if df % s != 0: continue h = _dup_right_decompose(f, s, K)",
"dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u,",
"(K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s, i =",
"K0, K1) f = dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h,",
"for i, (u, v, k) in enumerate(I_pos): for j, (s, t, m) in",
"t = dup_exquo(F, g, K) return s, t, h def dup_invert(f, g, K):",
"None: K1 = K0.get_ring() common = K1.one for c in f: common =",
"K): \"\"\"Computes polynomial LCM over a ring in `K[X]`. \"\"\" fc, f =",
"`K[x]`. \"\"\" prev, k = K.zero, 0 for coeff in f: if coeff*prev",
"dup_sign_variations([ dup_eval(f, hx, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, hy,",
"def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One bisection step of complex",
"dx, dy, K) if k != n: return dup_inner_isolate_complex_roots(f, K) if k ==",
"resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f,",
"Computation, Academic Press, London, 1988, pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation",
"(dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g,",
"n = dup_degree(f) m = dup_degree(g) if n < m: f, g =",
"s+1 return s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part of a",
"= dup_taylor(f, K.one, K) a1, b1, c1, d1, r = a, a+b, c,",
"K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u,",
"K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u,",
"= dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h,",
"c, d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k",
"b1 c1, c2, d1, d2 = c2, c1, d2, d1 f1, f2, k1,",
"dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if",
") from sympy.ntheory import nextprime from sympy.utilities import ( cythonized, variations ) from",
"dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros )",
"u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant",
"the exact number of zeros in the given rectangle. \"\"\" V1 = [",
"x, v, K) h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u):",
"K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if K.has_Field",
"{}, 0 while f: q, r = dup_div(f, h, K) if dup_degree(r) >",
"u, K): \"\"\"m-th order derivative in `x_0` of a polynomial in `K[X]`. \"\"\"",
"u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K) if",
"@cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in `K[X]`, useful over",
"dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K):",
"in `K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc, g = dup_primitive(g, K)",
"= dup_sub(q, d, K) if not h: result.append((p, i)) break g, p, q",
"j: return dmp_eval(g, a, v, K) v, i = v-1, i+1 return dmp_strip([",
"K) s = 0 while True: h, _ = dmp_inject(f, u, K, front=True)",
"g = dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g,",
"dup_convert(h, K1, K0) c = dup_LC(h, K0) h = dup_monic(h, K0) cff =",
"g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _ = dmp_inject(f,",
"p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p` in `K`. \"\"\"",
"sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K)",
"dup_strip([ C.imag(c) for c in f ]) seq = [u, v] while seq[-1]:",
"if K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain() f = dup_convert(f, K0,",
"K) if dup_degree(r) > 0: return None else: g[i] = dup_LC(r, K) f,",
"is not None: cond = lambda a, b, c, d, i, F: abs(F(a,",
"polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)):",
"`f(-x)` in `K[x]`. \"\"\" f, n, a = list(f), dup_degree(f), -K.one for i",
"for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K):",
"k1 > 1: stack.append((cx, cy, hx, hy, k1, F11, F12, F13, F14)) #",
"polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u,",
"= K.zero, u-1 for c in f: gc = dmp_rr_ground_content(c, v, K) cont",
"= _dup_left_decompose(f, h, K) if g is not None: return g, h return",
"= { s : K.one } r = n // s for i",
"K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over",
"(u, v, k) for i, (u, v, k) in enumerate(I_neg): for j, (s,",
"dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd, K) if K.has_Field or",
"= g, h, k, m-k B.append(b) D.append(d) h = dup_prem(f, g, K) h",
"K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f` and `g` in",
"u, K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1], K) else: h",
"= Fx F12 = _dup_sturm_shift(F2, hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy,",
"_ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h, u, K) h",
"= dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3,",
"dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff = dup_exquo(f, h, K) cfg",
"if c > p // 2: g.append(c - p) else: g.append(c) else: g",
"in (%s, %s) x (%s, %s) rectangle\" % (x, y, x+dx, y+dy)) def",
"Sturm sequence at its origin. \"\"\" return [ dup_mirror(f, K) for f in",
"= dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return a, f def",
"0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r =",
"= dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g,",
"K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients",
"in `K[X]`. \"\"\" if not u: return dup_lcm(f, g, K) if K.has_Field or",
"K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f,",
"cy, hx, hy, k2, F21, F22, F23, F24)) # Quadrant #3: -- F31",
"d, i, F: i >= 1 for i, (u, v, k) in enumerate(I_pos):",
"== 1: roots.append((x, cy, hx, hy, (F21, F22, F23, F24))) elif k2 >",
"x + hx, y + hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy,",
"dup_ground_to_ring(f, K0, K1) if K1 is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f,",
"gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd, K) if",
"def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f` in `F[x]`. Given an",
"max([ r[1] for r in group ]) for i, (x, y, dx, dy)",
"dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return a, f def dup_gcdex(f,",
"@cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\"",
"d = A*a + b, A*c + d if not dup_eval(f, K.zero, K):",
"K.zero, K.one, cx, cy, K) # Quadrant #1: ++ F11 = Fx F12",
"( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict,",
"= A*a + b, A*c + d if not dup_eval(f, K.zero, K): roots.append((F(b,",
"P = len(f), K.one, [] if dup_LC(f, K) < 0: f = dup_neg(f,",
"a2, a1, b2, b1 c1, c2, d1, d2 = c2, c1, d2, d1",
"not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g, K),",
"F4 ], K), ] return sum(v1 - v0 for v1, v0 in zip(V1,",
"cases in GCD algorithm over a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g",
"h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if not r:",
"V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One bisection",
"`K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc, g = dup_primitive(g, K) c",
"not u: return dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact: coeff =",
"u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf =",
"i)) t += 1 if not Q: continue P.append(min(Q)) if not P: return",
"return dup_compose(f, g, K) if dmp_zero_p(f, u): return f h = [f[0]] for",
"monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm in perms: G =",
"hy, (F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1 F32",
"g, v = dmp_zeros(m, u-1, K), u-1 for i, c in enumerate(reversed(f)): n",
"or x2+dx2 <= x1) and (y2 >= y1+dy1 or y2+dy2 <= y1)): x1,",
"_ = dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h, 1, K.dom) if",
"b, a+b, d, c+d i += 1 s, t = F(a, c), F(b,",
"h = [f[0]] for c in f[1:]: h = dmp_mul(h, g, u, K)",
"return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i+1, A, u, K)",
"in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg = dmp_eval(g, x,",
"cg in g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes",
"r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g,",
"if k1 < k2: a1, a2, b1, b2 = a2, a1, b2, b1",
"return sorted([ ((-v, -u), k) for (u, v) in I_neg ] + \\",
"u, K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not",
"[ _rec_eval_tail(c, i+1, A, u, K) for c in g ] if i",
"K): \"\"\"Computes indefinite integral of `f` in `x_j` in `K[X]`. \"\"\" if j",
"u, K): \"\"\"Differentiate and evaluate a polynomial in `x_j` at `a` in `K[X]`.",
"\"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\" if m <= 0 or",
"dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1,",
"or not cond(a, b, c, d, i, F): A = dup_root_lower_bound(f, K) if",
"cy, hx, hy, (F11, F12, F13, F14)) # Quadrant #2: -+ F21 =",
"GCD in `Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`, returns their",
"if i == j: return dmp_integrate(g, m, v, K) w, i = v-1,",
"cond, fast, K): I_pos.append((u, v, k)) g = dup_mirror(f, K) for s, t",
"\"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a, v, K) v, i =",
"a, Q = K.log(-f[i], 2), [] for j in xrange(i+1, n): if f[j]",
"if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1,",
"dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s positive roots. \"\"\" bound =",
"= coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s",
"a constant `p` in `K`. \"\"\" if K.is_ZZ: g = [] for c",
"_dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K) f =",
"if s > t: s, t = t, s negative = False if",
"dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith",
"hy = dx/2, dy/2 cx, cy = x + hx, y + hy",
"it may fail to compute the GCD. This will be signaled by raising",
"u: return dup_rr_content(f, K) cont, v = K.zero, u-1 for c in f:",
"..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x))",
"cond, fast, K)) else: stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots) def",
"= dup_taylor(f, b, C) f = dup_scale(f, a, C) u = dup_strip([ C.real(c)",
"K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f) g",
"= list(reversed(f)) for i in xrange(0, n): if f[i] >= 0: continue a,",
"K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a primitive polynomial.",
"K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff =",
"q, x, y, K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q direction. \"\"\"",
"[ (( u, v), k) for (u, v, k) in I_pos ]) def",
".. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms for Algebraic Computation,",
"K) if K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f, cont, u, K)",
"= dup_eval(f, x, K) gg = dup_eval(g, x, K) if ff and gg:",
"= dup_neg(f, K) coeff = -coeff if dup_degree(f) <= 0: if args.get('include', False):",
"K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k == 0: return []",
"(u, v, k) in I_pos ]) def _dup_inner_sturm(f, p, q, x, y, K):",
"F32, F33, F34, hx, hy, K) if k3 == 1: roots.append((x, y, hx,",
"-- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34",
"p, q = dmp_inner_gcd(f, h, u, K) all = args.get('all', False) while True:",
"[], [], [] elif not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif",
"K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p` in",
"for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try:",
"F41, F42, F43, F44)) if len(roots) == n: eps = args.get('eps') if eps",
"G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom)",
"not supported over %s\" % K) squarefree = args.get('sqf', False) if squarefree: roots",
"subresultants over a ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g, K) result",
"1 k1 = dup_sign_variations(f1, K) k2 = k - k1 - r a2,",
"-+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3, hx, K)",
"*= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K):",
"v), k) for (u, v, k) in I_pos ]) def _dup_inner_sturm(f, p, q,",
"K) else: raise DomainError(\"isolation of complex roots not supported over %s\" % K)",
"n, a = list(f), dup_degree(f), -K.one for i in xrange(n-1, -1, -1): f[i],",
"1: return (cx, y, hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots",
"dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[x]`. \"\"\"",
"[ dup_taylor(f, c, K) for f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip",
"K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return",
"dmp_eval(g, a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a,",
"the GCD. This will be signaled by raising an exception. In this case",
"dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\"",
"a polynomial at `x_j = a_j, ...` in `K[X]`. \"\"\" if not A:",
"= dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P *= p return",
"(dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u)",
"(x, y, dx, dy, _), k) in roots: multiplicity[(x, y, dx, dy)] =",
"d2 = b, a+b, d, c+d if k2 > 1 or (k1 >",
"`K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g) if n < m: f,",
"g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD",
"\"\"\" if not f: return K.zero else: return K.one def dup_content(f, K): \"\"\"Returns",
"= sorted(lower, key=lambda r: r[0]) if not squarefree: for i, r in enumerate(upper):",
"cg, g = dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u, K0, K1)",
"\"\"\" if s == t: return (s, t) F = K.get_field() a, c",
"if not (f or g): return [], [], [] elif not f: if",
"None: return result fc, F = dup_primitive(f, K) gc, G = dup_primitive(g, K)",
"if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K),",
"zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw =",
"useful over algebraic domains. \"\"\" if not u: return dup_sqf_norm(f, K) if not",
"#2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3, hx,",
"dmp_LC(g, K) v = u - 1 h = dmp_gcd(F, G, v, K)",
"not None: return g, h return None def dup_decompose(f, K): \"\"\"Computes functional decomposition",
"return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a",
"if result is not None: return result df = dmp_degree(f, u) dg =",
"import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime from",
"K0) cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u,",
"K) w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j,",
"g, K) h = dup_mul_ground(h, b, K) while h: k = dup_degree(h) R.append(h)",
"g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K)",
"purely heuristic which means it may fail to compute the GCD. This will",
"K.zero, K) for f in F4 ], K), ] return sum(v1 - v0",
"`K[X]`. \"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f =",
"+ 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g,",
"dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a primitive",
"b, A*c + d if not dup_eval(f, K.zero, K): return F(b, d), F(b,",
"dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f,",
"K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)` in `K[x]`. \"\"\" f, n",
"_dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2, df): if df",
"[] while h: g = h % x if g > x //",
"i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i",
"= c**(d-1) c = K.exquo((-lc)**d, q) b = -lc * c**(m-k) f, g,",
"if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u,",
"return (s, t) if s > t: s, t = t, s negative",
"dup_taylor(f, c, K) for f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the",
"nextprime from sympy.utilities import ( cythonized, variations ) from random import random as",
"K) F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K)",
"u) R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d, v,",
"dx, dy) in roots: if x in groups: groups[x].append((x, y, dx, dy)) else:",
"\"\"\" n, t, P = len(f), K.one, [] if dup_LC(f, K) < 0:",
"<gh_stars>0 \"\"\"Advanced tools for dense recursive polynomials in `K[x]` or `K[X]`. \"\"\" from",
"dmp_degree(g, u) if df > 0 and dg > 0: return None if",
"`f`'s positive roots. \"\"\" n, t, P = len(f), K.one, [] if dup_LC(f,",
"a Sturm sequence by a real number `c`. \"\"\" return [ dup_taylor(f, c,",
"polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff = dup_LC(f, K)",
"dup_sign_variations([ dup_eval(f, hy, K) for f in F4 ], K), ] V0 =",
"k) in roots: multiplicity[(x, y, dx, dy)] = k roots = multiplicity.keys() groups",
"b1, c1, d1, f1, k1)) if k2 == 0: continue if k2 ==",
"a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f, K) return a, f",
"K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x,",
"y, dx, dy) in enumerate(group): if y == _min: lower.append((x, y, dx, dy))",
"u) m = dmp_degree(g, u) if n < m: f, g = g,",
"F14))) elif k1 > 1: stack.append((cx, cy, hx, hy, k1, F11, F12, F13,",
"dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i+1, A, u, K) for",
"return f g, v = dmp_zeros(m, u-1, K), u-1 for i, c in",
"0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond,",
"*= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m,",
"K) if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p), 1, u,",
"for j in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K))",
"g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\"",
"+= a*f[j] return f def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n",
"B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f,",
"ValueError(\"can't refine a real root on (%s, %s)\" % (s, t)) fast =",
"of `f` in `K[X]`, useful over algebraic domains. \"\"\" if not u: return",
"as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to",
"% 2: s = -s lc, i = dup_LC(R[i], K), i+1 p *=",
"from a pair of polynomials in `K[x]`. \"\"\" fc = dup_content(f, K) gc",
"dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K),",
"K, F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors)",
"dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u,",
"dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g, u,",
"b2 = a2, a1, b2, b1 c1, c2, d1, d2 = c2, c1,",
"del group[i] break _min = min([ r[1] for r in group ]) for",
"p, K), v, K) P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g,",
"K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc,",
"K) return s, t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of",
"K) for g, k in factors: g = dup_convert(g, K, F) for r",
"0: f = dup_neg(f, K) f = list(reversed(f)) for i in xrange(0, n):",
"g, v, K) h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)):",
"K) if u == len(A)-1: return e else: return dmp_strip(e, u - len(A))",
"dmp_exquo(g, h, u, K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u,",
"dup_content(f, K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return",
"that:: h = gcd(f, g), cff = quo(f, h) and cfg = quo(g,",
"result = dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v, K) return",
"using subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result",
"0: continue h = _dup_right_decompose(f, s, K) if h is not None: g",
"if not u: return dup_monic(f, K) if dmp_zero_p(f, u): return f lc =",
"F44))) elif k4 > 1: stack.append((cx, y, hx, hy, k4, F41, F42, F43,",
"`x_j` of a polynomial in `K[X]`. \"\"\" if j < 0 or j",
"return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u),",
"dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a ring in `K[x]`. \"\"\" fc,",
"K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u, K) def",
"fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] =",
"D.append(d) h = dmp_prem(f, g, u, K) h = [ dmp_exquo(ch, b, v,",
"v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _, p,",
"dmp_LC(g, K) else: if not df: F = dmp_LC(f, K) G = dmp_content(g,",
"] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over",
"K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS.",
"K) if all or dup_degree(g) > 0: result.append((g, i)) i += 1 if",
"= result F = [h] + F else: break return [f] + F",
"K) g, p, q = dup_inner_gcd(f, h, K) all = args.get('all', False) while",
"K) if s == t: return (s, t) if s > t: s,",
"Computation 7 (1989), pp. 445-456 \"\"\" F = [] while True: result =",
"K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if K.has_Field or",
"_rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0)",
"K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1",
"[], [] for group in groups.values(): while len(group) > 1: _max = max([",
"is not None: return result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h,",
"DomainError('computation can be done only in a field') f = dup_sqf_part(f, K) sturm",
"and `cfg` such that:: h = gcd(f, g), cff = quo(f, h) and",
"u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f` and `g`",
"part of a polynomial in `K[x]`. \"\"\" if not f: return f if",
"y == _min: lower.append((x, y, dx, dy)) del group[i] break upper = sorted(upper,",
"d = dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v, K),",
"in `K[X]`. \"\"\" if not u: return dup_content(f, K) if K.has_Field or not",
"cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\")",
"\"\"\"Returns GCD of coefficients over a ring. \"\"\" cont = K.zero for c",
"K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a square-free polynomial in",
"= _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u,",
"(F1, F2, F3, F4))) elif k > 1: stack.append((x, y, dx, dy, k,",
"in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial",
"dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in `K[X]`, useful over algebraic domains.",
"= _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if",
"dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j,",
"+ 1: return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A,",
"v-1 for c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return",
"-a], K) D = dup_trunc(D, p, K) return r def _collins_crt(r, R, P,",
"K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u,",
"K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c,",
"(F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22",
"dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f,",
"c else: q = c**(d-1) c = K.exquo((-lc)**d, q) b = -lc *",
"dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a",
"g > x // 2: g -= x f.insert(0, g) h = (h-g)",
"> x // 2: g -= x f.insert(0, g) h = (h-g) //",
"i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res =",
"f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88]",
"= dmp_degree(f, u) m = dmp_degree(g, u) if n < m: f, g",
"u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u - 1",
"f = [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K)",
"**args): roots.append((g, r, k)) if len(factors) > 1: for i, (f1, r1, k1)",
"res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of `f`",
"R) s, i, v = 1, 1, u-1 p = dmp_one(v, K) q",
"front=True) r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break else: f,",
"groups: groups[x].append((x, y, dx, dy)) else: groups[x] = [(x, y, dx, dy)] upper,",
"_rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args):",
"return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for",
"not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a, b, c, d",
"u): return f g, v = dmp_zeros(m, u-1, K), u-1 for i, c",
"while True: result = _dup_decompose(f, K) if result is not None: f, h",
"return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u)",
"(%s, %s)\" % (s, t)) fast = args.get('fast') if type(n) is not int:",
"m < 0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u,",
"Academic Press, London, 1988, pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation can",
"ring. \"\"\" cont = dup_content(f, K) if not f or K.is_one(cont): return cont,",
"if dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K),",
"* K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial",
"K) v = u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)):",
"gg = dmp_eval(g, x, u, K) v = u - 1 if not",
"xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g, x, K) if",
"of a polynomial in `K[X]`. \"\"\" if not u: return dup_discriminant(f, K) d,",
"u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g,",
"a` in `K[X]` using Horner scheme. \"\"\" if not u: return dup_eval(f, a,",
"F2, F3, F4)) while stack: x, y, dx, dy, k, F1, F2, F3,",
"@cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K)",
"the correct GCD. This gives cofactors of the input polynomials as a side",
"polynomials in `K[x]`. \"\"\" fc = dup_content(f, K) gc = dup_content(g, K) gcd",
"c, d), cond, fast, K)) continue f1 = dup_taylor(f, K.one, K) a1, b1,",
"dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _ = dmp_inject(f, 0, K, front=True)",
"= dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B,",
"K.is_one(lc): return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K):",
"g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\"",
"_rec_integrate_in(c, m, w, i, j, K) for c in g ], v) @cythonized(\"m,j,u\")",
"% (u, u, j)) return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def",
"def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a field. \"\"\"",
"s < 0: p = dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res",
"g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in",
"r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f,",
"HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try:",
"k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c,",
"f = dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex roots not supported",
"a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K),",
"1995, pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g, K) result =",
"h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g,",
"v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over",
"while not (s >= v or t <= u): u, v = dup_outer_refine_real_root(F_neg[k],",
"if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B, D h = dmp_prem(f,",
"s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K):",
"f or not g: return (K.zero, []) R, B, D = dup_inner_subresultants(f, g,",
"= a` in `K[X]` using Horner scheme. \"\"\" if j < 0 or",
"\"\"\" C = K.complex_domain() a, b = C(p, q), C(x, y) f =",
"to another GCD method. The algorithm computes the polynomial GCD by evaluating polynomials",
"result is not None: return result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f,",
"dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f,",
"<= 0 or dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u-1, K),",
">= v or t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step,",
"modular resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g,",
"p) v = u - 1 n = dmp_degree(f, u) m = dmp_degree(g,",
"= dup_primitive(f, K) gc, G = dup_primitive(g, K) c = K.gcd(fc, gc) h",
"% (u, u, j)) if not j: return dmp_eval(dmp_diff(f, m, u, K), a,",
"\"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for c in f ], u)",
"= a` in `K[X]` using Horner scheme. \"\"\" if not u: return dup_eval(f,",
"_dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r,",
"dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One bisection step of complex root",
"K) t = dup_exquo(F, g, K) return s, t, h def dup_invert(f, g,",
"= lambda a, b, c, d, i, F: i >= 1 for i,",
"if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots = []",
"`K`. \"\"\" if K.is_ZZ: g = [] for c in f: c =",
"for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g,",
"if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2,",
"K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return",
"cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg,",
"b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0: p = -p",
"0: p = dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1],",
"u, 0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x",
"F, eps, K): \"\"\"Refine a complex root until the desired precision is reached.",
"_dmp_ff_trivial_gcd(f, g, u, K) if result is not None: return result fc, f",
"dx, dy)) del group[i] break _min = min([ r[1] for r in group",
"using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K =",
"`K[x]`. \"\"\" fc = dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc,",
"K) G = dmp_content(g, u, K) else: F = dmp_content(f, u, K) G",
"return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return [] h = [f[0]]",
"dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K)",
"u, K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u,",
"deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order derivative in `x_0` of",
"d1), cond, fast, K)) else: stack.append((a1, b1, c1, d1, f1, k1)) if k2",
"if not P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ",
"\"\"\" f = [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v,",
"least second degree. Unlike factorization, complete functional decompositions of polynomials are not unique,",
"d if not dup_eval(f, K.zero, K): return F(b, d), F(b, d) f, g",
"return f else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD",
"I_pos.append((u, v, k)) g = dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond,",
"else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes",
"a field. \"\"\" if not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f,",
"pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not None:",
"cf, f = dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0, K1) f",
"u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant",
"{} for (x, y, dx, dy) in roots: if x in groups: groups[x].append((x,",
"= dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots = [] _, factors =",
"in enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]): while not (s >=",
"dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg =",
"dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" if not",
"h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD",
"intervals. \"\"\" a, b, c, d = K.one, K.zero, K.zero, K.one k =",
"def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and evaluate a polynomial in",
"dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None",
"m-k, v, K), v, K) f, g, m, d = g, h, k,",
"root refinement not supported over %s\" % K) if s == t: return",
"f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return dup_monic(f, K),",
"if not f: return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K):",
"K): \"\"\"Compute LMQ lower bound for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f),",
"monoms, polys = dmp_to_dict(f, u), [], [] for monom, coeff in F.iteritems(): if",
"v, k) in enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]): while not",
"\"\"\" if not u: return dup_ground_to_ring(f, K0, K1) if K1 is None: K1",
"v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral of `f`",
"coefficients by `LC(f)` in `K[X]`. \"\"\" if not u: return dup_monic(f, K) if",
"return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial",
"if K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of complex roots",
"_ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h,",
"\"\"\" f = [] while h: g = h % x if g",
"if not K.is_Algebraic: raise DomainError('computation can be done only in an algebraic domain')",
"-K.one r = dmp_zero(v) while dup_degree(D) <= B: while True: a += K.one",
"m <= 0 or not f: return f g = [K.zero]*m for i,",
"return K.zero, f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else:",
"u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial",
"= _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy,",
"domain') F, monoms, polys = dmp_to_dict(f, u), [], [] for monom, coeff in",
"dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros",
"G = dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G, p, u,",
"return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y, dx, dy, (F1, F2,",
"g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h, g, v,",
"dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du % 2 and dv",
"[] eps, fast = args.get('eps'), args.get('fast') if eps is not None: cond =",
"-p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p, q) return",
"\"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if",
"not A: return f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e =",
"= dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _",
"f, n, b = list(f), dup_degree(f), a for i in xrange(n-1, -1, -1):",
"subresultant PRS. \"\"\" if not f or not g: return (K.zero, []) R,",
"u): k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc,",
"K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _,",
"f = dup_rshift(f, 1, K) a, b, c, d = b, a+b, d,",
"common, u, K0) if not args.get('convert'): return common, f else: return common, dmp_convert(f,",
"u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J,",
"return dmp_TC(f, K) result, v = dmp_LC(f, K), u-1 for coeff in f[1:]:",
"p, u, K) G = dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F,",
"in f ]) v = dup_strip([ C.imag(c) for c in f ]) seq",
"enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]): while not (s >= v",
"u) if df > 0 and dg > 0: return None if not",
"a, K): \"\"\"Evaluate a polynomial at `x = a` in `K[x]` using Horner",
"dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _, p, q = dmp_inner_gcd(p, q,",
"not a: return dmp_TC(f, K) result, v = dmp_LC(f, K), u-1 for coeff",
"K): \"\"\"Computes the Sturm sequence of `f` in `F[x]`. Given an univariate, square-free",
"2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm",
"F34, hx, hy, K) if k3 == 1: roots.append((x, y, hx, hy, (F31,",
"f) while True: r = randfloat() if r < 0.5: break x, y,",
"h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) cff",
"not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg =",
"max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for",
"n+j-i in f: continue if not s-j in g: continue fc, gc =",
"1 if not Q: continue P.append(min(Q)) if not P: return None else: return",
"u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`, useful over",
"g = dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r,",
"def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f`",
"t = F(a, c), F(b, d) if s <= t: return (s, t)",
"K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31,",
"K) h = dup_sub(q, d, K) if not h: result.append((p, i)) break g,",
"for v1, v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx,",
"K) c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h =",
"d = dup_diff(p, 1, K) h = dup_sub(q, d, K) if not h:",
"c**(d-1) c = K.exquo((-lc)**d, q) b = -lc * c**(m-k) f, g, m,",
"v, K) cont = K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\") def",
"u-1, K), u-1 for i, c in enumerate(reversed(f)): n = i+1 for j",
"dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h",
"K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h, c, K) cff = dup_exquo(f,",
"v = dup_strip([ C.imag(c) for c in f ]) seq = [u, v]",
"result is not None: return result fc, f = dmp_primitive(f, u, K) gc,",
"at its origin. \"\"\" return [ dup_mirror(f, K) for f in F ]",
"dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`.",
"c in f[1:]: h = dmp_mul(h, g, u, K) h = dmp_add_term(h, c,",
"F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy =",
"in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q, c, K)",
"K): \"\"\"Returns square-free part of a polynomial in `K[x]`. \"\"\" if not f:",
"v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j,",
"= dup_sub_mul(h, s, f, K) t = dup_exquo(F, g, K) return s, t,",
"!= 0: continue h = _dup_right_decompose(f, s, K) if h is not None:",
"roots in (%s, %s) x (%s, %s) rectangle\" % (x, y, x+dx, y+dy))",
"return g, h return None def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f`",
"K, **args): \"\"\"Refine real root's approximating interval to the given precision. \"\"\" if",
"dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd, K) if K.has_Field or not",
"is not int: cond = lambda a, b, c, d, i, F: abs(F(a,",
"= dmp_pow(dmp_neg(lc, v, K), d, v, K) if not d: q = c",
"K.one, K) a1, b1, c1, d1, r = a, a+b, c, c+d, 0",
"K.is_one(P): r = R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K),",
"not u: return dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f, u):",
"j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m, v, K), a,",
"dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if",
"dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u,",
"g, K1) h = dup_convert(h, K1, K0) c = dup_LC(h, K0) h =",
"return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order derivative in `x_0`",
"dup_strip([ C.real(c) for c in f ]) v = dup_strip([ C.imag(c) for c",
"real roots using continued fractions approach. \"\"\" if K.is_QQ: (_, f), K =",
"u, K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h, u,",
"dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a primitive polynomial. \"\"\" cont, v",
"c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q,",
"u, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x,",
"K)[0] % p, p) v = u - 1 n = dmp_degree(f, u)",
"in zip(perm, monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K))",
"dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1],",
"a ring. \"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f",
"= _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx,",
"v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute",
"i), rest = result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)]",
"by `LC(f)` in `K[x]`. \"\"\" if not f: return f lc = dup_LC(f,",
"for f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in",
"K), 1 k1 = dup_sign_variations(f1, K) k2 = k - k1 - r",
"= [] _, factors = dup_sqf_list(f, K) for g, k in factors: g",
"m: return [] deriv, c = [], K.one for i in xrange(0, m):",
"`f` is a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True",
"\"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\" if not u: return dup_discriminant(f,",
"dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P *= p return r",
"not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h =",
"(u, u, j)) return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g,",
"elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g,",
"K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if not f:",
"enumerate(group): if y == _min: lower.append((x, y, dx, dy)) del group[i] break upper",
"K) h = dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p, i)) break",
"u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one,",
"not None: return result df = dup_degree(f) dg = dup_degree(g) gcd, f, g",
"= K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k == 0:",
"K) k2 = k - k1 - r a2, b2, c2, d2 =",
"\"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if not u: return dup_compose(f, g,",
"key=lambda r: r[0]) lower = sorted(lower, key=lambda r: r[0]) if not squarefree: for",
"lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d, v, K) if",
"dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K) if",
"polynomial LCM over a ring in `K[x]`. \"\"\" fc, f = dup_primitive(f, K)",
"i.e. transform `K_0` to `K_1`. \"\"\" if K1 is None: K1 = K0.get_ring()",
"K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\") def",
"return dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg,",
"K) I_neg[i+j+1] = (s, t, m) I_neg[i] = (u, v, k) return sorted([",
"algorithm over a ring. \"\"\" if not (f or g): return [], [],",
"dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K) def dup_refine_real_root(f, s, t, n,",
"f else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K):",
"u, K) f = dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f, u,",
"\"\"\" if dmp_zero_p(f, u): return K.zero, f else: return K.one, f @cythonized(\"u\") def",
"while len(group) > 1: _max = max([ r[1] for r in group ])",
"stack: a, b, c, d, f, k = stack.pop() A = dup_root_lower_bound(f, K)",
"rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of a polynomial",
"(f1, (x1, y1, dx1, dy1, F1), k1) multiplicity = {} for (_, (x,",
"2), [] for j in xrange(i+1, n): if f[j] <= 0: continue q",
"= dup_div(g, cfg, K) if not r: cff_, r = dup_div(f, h, K)",
"h = dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def dmp_compose(f, g, u,",
"factorization, complete functional decompositions of polynomials are not unique, consider examples: 1. `f",
"g, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[x]`. \"\"\" if",
"n = dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f) g = {",
"dmp_exquo_ground(g, gcd, u, K) return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently",
"(dmp_LC(R[-1], K), R) s, i, v = 1, 1, u-1 p = dmp_one(v,",
"\"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if K.has_Field or not",
"= dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t,",
"\"\"\"Compute disjoint complex root isolating rectangles for all quadrants. \"\"\" n, lc =",
"K) if g is not None: return g, h return None def dup_decompose(f,",
"-coeff if dup_degree(f) <= 0: if args.get('include', False): return f else: return coeff,",
"GCD of coefficients in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f,",
"def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at `x_j = a_j, ...`",
"u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p` in `K`. \"\"\" if",
"K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f",
"% 2 and dv % 2: s = -s lc, i = dup_LC(R[i],",
"K) F22 = Fy F23 = _dup_sturm_shift(F3, hx, K) F24 = F4 k2",
"g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not None:",
"g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h",
"\"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g,",
"fast, K): \"\"\"Refine a positive root of `f` given a Mobius transform. \"\"\"",
"in `K[X]`. \"\"\" if not A: return f if dmp_zero_p(f, u): return dmp_zero(u",
"lc = dup_LC(f, K) f = dup_to_raw_dict(f) g = { s : K.one",
"I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u) for (u, v)",
"m, K): \"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\" if m <=",
"c, d, i, F: abs(F(a, c) - F(b, d)) < eps else: cond",
"\"\"\" if m <= 0: return f n = dup_degree(f) if n <",
"else: if not df: F = dmp_LC(f, K) G = dmp_content(g, u, K)",
"\"\"\"Computes polynomial GCD of `f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g,",
"multiplicity.keys() groups = {} for (x, y, dx, dy) in roots: if x",
"(F31, F32, F33, F34))) elif k3 > 1: stack.append((x, y, hx, hy, k3,",
"\"\"\" if not u: return dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1",
"not None: return result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0,",
"K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f,",
"Q = [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for",
"cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f,",
"@cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\" d",
"all coefficients by `LC(f)` in `K[X]`. \"\"\" if not u: return dup_monic(f, K)",
"return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u)",
"0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _ = dmp_inject(f, 0, K,",
"u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return f h = [f[0]]",
"d1, d2 = c2, c1, d2, d1 f1, f2, k1, k2 = f2,",
"+ I_pos) _, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),)",
"real root on (%s, %s)\" % (s, t)) fast = args.get('fast') if type(n)",
"K)): h = dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K) h",
"xrange(0, i): if not n+j-i in f: continue if not s-j in g:",
"if `f` is a square-free polynomial in `K[x]`. \"\"\" if not f: return",
"f = [] while h: g = h % x if g >",
"h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else: f, s = dmp_compose(f,",
"g, K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h =",
"dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step,",
"b2, c2, d2), cond, fast, K)) else: stack.append((a2, b2, c2, d2, f2, k2))",
"dup_diff(f, m, K) if m <= 0: return f n = dmp_degree(f, u)",
"u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u, K)",
"eps, K): \"\"\"Refine a complex root until the desired precision is reached. \"\"\"",
"\"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n, a = list(f), dup_degree(f),",
"\"\"\" if not f: return f lc = dup_LC(f, K) if K.is_one(lc): return",
"dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of",
"K), K) f = dup_monic(f, K) return a, f def dup_gcdex(f, g, K):",
"-B+r, -B-r, 2*B+r, 2*B+r roots, stack = [], [] F1 = _dup_inner_sturm(f, K.one,",
"h = dup_sub(q, d, K) if not h: result.append((p, i)) break g, p,",
"for i in xrange(0, n): if f[i] >= 0: continue a, Q =",
"gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r",
"= dup_strip([e]) else: R = [R] e = [e] d = K.invert(dup_eval(D, a,",
"c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h,",
"`g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K):",
"dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of two polynomials in `K[X]`. \"\"\"",
"v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m, v,",
"-s lc, i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v,",
"F = dup_sub_mul(h, s, f, K) t = dup_exquo(F, g, K) return s,",
"of coefficients over a field. \"\"\" if not f: return K.zero else: return",
"GCD is recovered from the integer image by interpolation. The evaluation proces reduces",
"= _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h,",
"B.append(b) D.append(d) h = dup_prem(f, g, K) h = dup_exquo_ground(h, b, K) return",
"not f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\")",
"F = dup_primitive(f, K) gc, G = dup_primitive(g, K) c = K.gcd(fc, gc)",
"to compute the GCD. This will be signaled by raising an exception. In",
"\"\"\"Compute LMQ lower bound for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K)",
"= dup_strip([R]) e = dup_strip([e]) else: R = [R] e = [e] d",
"dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd,",
"lower bound for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound",
"Unlike factorization, complete functional decompositions of polynomials are not unique, consider examples: 1.",
"f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) gcd = dmp_gcd(f,",
"= dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K) t = dup_exquo(F,",
"`f` and `g` in `Z[x]`, returns their GCD and cofactors, i.e. polynomials `h`,",
"K): \"\"\"XXX\"\"\" g, i = {}, 0 while f: q, r = dup_div(f,",
"1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast, K)) else: stack.append((a2, b2,",
"cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg, u,",
"u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i in xrange(0,",
"for f in F4 ], K), ] return sum(v1 - v0 for v1,",
"< %s expected, got %s\" % (u, u, j)) if not j: return",
"dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors) > 1: for i, (f1,",
"dup_trunc(f, p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for",
"dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of",
"g, h, k, m-k B.append(b) D.append(d) h = dmp_prem(f, g, u, K) h",
"real number `c`. \"\"\" return [ dup_taylor(f, c, K) for f in F",
"A*a + b, A*c + d if not dup_eval(f, K.zero, K): return F(b,",
"< %s expected, got %s\" % (u, u, j)) return _rec_integrate_in(f, m, u,",
"def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\" if",
"q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K):",
"if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u,",
"polynomials `f` and `g` in `Z[x]`, returns their GCD and cofactors, i.e. polynomials",
"return cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a field. \"\"\"",
"cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c =",
"F, **args): roots.append((g, r, k)) if len(factors) > 1: for i, (f1, r1,",
"not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u, K)",
"= a*f[i], -a return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)`",
"complex root using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0,",
"b, d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K)",
"dmp_rem(c, p, u-1, K) for c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f,",
"variations of `f` in `K[x]`. \"\"\" prev, k = K.zero, 0 for coeff",
"K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise",
"polynomial LCM of `f` and `g` in `K[X]`. \"\"\" if not u: return",
"xrange(1, s): coeff = K.zero for j in xrange(0, i): if not n+j-i",
"`K[x]`. \"\"\" f, n, b = list(f), dup_degree(f), a for i in xrange(n-1,",
"]) seq = [u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s,",
"K.dom): break else: f, s = dmp_compose(f, F, u, K), s+1 return s,",
"(u, v, k) in enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]): while",
"j, K) for c in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j,",
"[] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero,",
"GCD. This gives cofactors as a side effect. References ========== .. [Liao95] <NAME>,",
"try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\")",
"u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg",
"`dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return",
"of coefficients in `K[X]`. \"\"\" if not u: return dup_content(f, K) if K.has_Field",
"f = dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u,",
"dup_div(f, h, K) if dup_degree(r) > 0: return None else: g[i] = dup_LC(r,",
"t, m) I_pos[i] = (u, v, k) for i, (u, v, k) in",
"if the interpolated polynomial is the correct GCD. This gives cofactors of the",
"_dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K) if not r: cff_,",
"return R, B, D h = dup_prem(f, g, K) h = dup_mul_ground(h, b,",
"break return [f] + F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of",
"K) if K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f,",
"h, K) cfg = dup_exquo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f,",
"K) for c in f ], u) def dup_monic(f, K): \"\"\"Divides all coefficients",
"d, K) if not h: result.append((p, i)) break g, p, q = dup_inner_gcd(p,",
"not n+j-i in f: continue if not s-j in g: continue fc, gc",
"_dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K)",
"if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass",
"algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K)",
"K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _, h = dmp_primitive(h, u,",
"h = dup_add(h, q, K) return h def dup_compose(f, g, K): \"\"\"Evaluate functional",
"return r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT for Collins's",
"= [] for c in f: c = c % p if c",
"None if not (df or dg): F = dmp_LC(f, K) G = dmp_LC(g,",
"K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f,",
"K) for f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of",
"cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J,",
"dmp_degree(g, u) if n < 0 or m < 0: return dmp_zero(u-1) A",
"eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy, F,",
"P <= B: p = K(nextprime(p)) while not (a % p) or not",
"= dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1)",
"c+d if k2 > 1 or (k1 > 0 and k2 == 1):",
"u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c,",
"u, K) h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u, K)",
"over %s\" % K) squarefree = args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f,",
"= 1, 1 p, q = K.one, K.one for b, d in zip(B,",
"r: cff_, r = dup_div(f, h, K) if not r: h = dup_mul_ground(h,",
"desired precision is reached. \"\"\" while dx >= eps and dy >= eps:",
"result fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K)",
"c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]`",
"g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u,",
"def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n",
"u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u, K) if",
"m*N D, a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B:",
"isolation intervals. \"\"\" a, b, c, d = K.one, K.zero, K.zero, K.one k",
"0.5: break x, y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack",
"from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict,",
"K) f = dup_monic(f, K) return a, f def dup_gcdex(f, g, K): \"\"\"Extended",
"K)): return f, [K.one], [] else: return dup_neg(f, K), [-K.one], [] return None",
"@cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\"",
"polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g,",
"dup_taylor(f, K.one, K) a1, b1, c1, d1, r = a, a+b, c, c+d,",
"not (a % p) or not (b % p): p = K(nextprime(p)) F",
"norm of `f` in `K[X]`, useful over algebraic domains. \"\"\" if not u:",
"Fy F23 = _dup_sturm_shift(F3, hx, K) F24 = F4 k2 = _dup_inner_zeros(F21, F22,",
"] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return the exact number",
"GCD. This will be signaled by raising an exception. In this case you",
"return common, f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v,",
"h = result F = [h] + F else: break return [f] +",
"None: cond = lambda a, b, c, d, i, F: abs(F(a, c) -",
"be done only in an algebraic domain') F, monoms, polys = dmp_to_dict(f, u),",
"def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a primitive polynomial. \"\"\" cont,",
"upper = sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda r: r[0]) if",
"return (t, s) def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a positive",
"[] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g)",
"x1, y1, dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2,",
"USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in",
"n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return",
"dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c,",
"dmp_degree(f, u) m = dmp_degree(g, u) if n < 0 or m <",
"if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f,",
"dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of",
"`x = a` in `K[x]` using Horner scheme. \"\"\" if not a: return",
"i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K)",
"K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h,",
"G = dict(F) for sign, monom in zip(perm, monoms): if sign == -1:",
"a, u, 0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm",
"g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a ring",
"large integer. The final step is to verify if the interpolated polynomial is",
"\"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g:",
"m, K): \"\"\"m-th order derivative of a polynomial in `K[x]`. \"\"\" if m",
"K.zero, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for",
"hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots in (%s, %s) x",
"== 1: a, b, c, d = a1, b1, c1, d1 else: f",
"i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m,",
"in xrange(0, m): c, n = c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c)",
"K) for c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K):",
"Algebraic Computation, Academic Press, London, 1988, pp. 124-128 \"\"\" if not K.has_Field: raise",
"in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def",
"K) cont = K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f,",
"if not n+j-i in f: continue if not s-j in g: continue fc,",
"HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K):",
"return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s, i,",
"if not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K)",
"cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K) if",
"K) w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j,",
"_dup_left_decompose(f, h, K) if g is not None: return g, h return None",
"not u: return dup_monic(f, K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f,",
"u, K) else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce",
"p, K): \"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R],",
"from sympy.ntheory import nextprime from sympy.utilities import ( cythonized, variations ) from random",
"or t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K)",
"dy, F, K): \"\"\"One bisection step of complex root refinement algorithm. \"\"\" hx,",
"T_n` where `T_n` and `T_m` are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>,",
"= dmp_inner_gcd(f, h, u, K) all = args.get('all', False) while True: d =",
"(s >= v or t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v,",
"hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if",
"return dup_ground_to_ring(f, K0, K1) if K1 is None: K1 = K0.get_ring() common =",
"recovered from the integer image by interpolation. The final step is to verify",
"\"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result is not None: return result",
"luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from integer GCD.",
"c1, d1, r = a, a+b, c, c+d, 0 if not dup_eval(f1, K.zero,",
"return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f,",
"elif not K.is_ZZ: raise DomainError(\"real root refinement not supported over %s\" % K)",
"g, u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try",
"dy, (F1, F2, F3, F4))) elif k > 1: stack.append((x, y, dx, dy,",
"u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K)",
"dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x))",
"their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg` such that:: h",
"def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f =",
"], u) def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\"",
"i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m, v, K),",
"of `f` in `K[x]`. \"\"\" prev, k = K.zero, 0 for coeff in",
"`K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not",
"(s, t, m) in enumerate(I_neg[i+1:]): while not (s >= v or t <=",
"return K.zero, f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns",
"dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res, p, v, K), q, v,",
"not dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K)",
"D = dup_trunc(D, p, K) return r def _collins_crt(r, R, P, p, K):",
"in g: continue fc, gc = f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc",
"K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g,",
"= dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else:",
"or j > u: raise IndexError(\"-%s <= j < %s expected, got %s\"",
"integer GCD. \"\"\" f = [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h,",
"= dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0)",
"in g ], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate",
"I_pos, I_neg = [], [] F_pos, F_neg = {}, {} for f, k",
"K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a field in `K[x]`.",
"u, K) if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p), 1,",
"y, hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots in (%s, %s)",
"[(g, i)] + rest def dup_extract(f, g, K): \"\"\"Extracts common content from a",
"a, j, u, K): \"\"\"Evaluate a polynomial at `x_j = a` in `K[X]`",
"dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1] = (f2,",
"K.one if a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p),",
"dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2, y2, dx2,",
"dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0, u, K) while not",
"dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\")",
"b, c, d, i, F: i >= n s, t = dup_outer_refine_real_root(f, s,",
"return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r =",
"K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" zero_f =",
"v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x,",
"k3, F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx,",
"in roots: multiplicity[(x, y, dx, dy)] = k roots = multiplicity.keys() groups =",
"proces reduces f and g variable by variable into a large integer. The",
"K.dom) if dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f, -K.unit, K), s+1",
"roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots = [] _, factors",
"its origin. \"\"\" return [ dup_mirror(f, K) for f in F ] def",
"d <= 0: return K.zero else: s = (-1)**((d*(d-1)) // 2) c =",
"o f_2 o ... f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n` are",
"K) for ch in h ] return R, B, D @cythonized(\"u\") def dmp_subresultants(f,",
"K) F = (F1, F2, F3, F4) x, y, dx, dy, _ =",
"[h] + F else: break return [f] + F def dup_sturm(f, K): \"\"\"Computes",
"= dmp_degree(R[i+1], u) if du % 2 and dv % 2: s =",
"pair of polynomials in `K[x]`. \"\"\" fc = dup_content(f, K) gc = dup_content(g,",
"= dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29",
"k2 = f2, f1, k2, k1 if k1 == 0: continue if k1",
"d), cond, fast, K): \"\"\"Refine a positive root of `f` given a Mobius",
"if s == t: return (s, t) F = K.get_field() a, c =",
"not f: return K.zero else: return K.one def dup_content(f, K): \"\"\"Returns GCD of",
"r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff,",
"= _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1, F2, F3, F4) x,",
"dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K)",
"K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 ==",
"return 1.0 / bound else: return None def dup_inner_refine_real_root(f, (a, b, c, d),",
"in `K[x]`, useful over algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain",
"not v: R = dup_strip([R]) e = dup_strip([e]) else: R = [R] e",
"dmp_mul(d, dmp_sub(R, e, v, K), v, K) r = dmp_add(r, c, v, K)",
"f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s",
"f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2,",
"dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of `f` in `x_0` in `K[X]`.",
"dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC,",
"F44)) if len(roots) == n: eps = args.get('eps') if eps is not None:",
"sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add,",
"[P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant",
"K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy,",
"K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if not f: return",
"K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\" cont,",
"g = _dup_left_decompose(f, h, K) if g is not None: return g, h",
"f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n`",
"= c else: q = dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q,",
"( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime from sympy.utilities",
"if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1,",
"dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\" if not",
"in F4 ], K), ] return sum(v1 - v0 for v1, v0 in",
"u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if",
"K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero,",
"= {}, {} for f, k in factors: for u, v in dup_inner_isolate_real_roots(f,",
"K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def",
"== 1: roots.append((cx, y, hx, hy, (F41, F42, F43, F44))) elif k4 >",
"got %s\" % (u, u, j)) return _rec_integrate_in(f, m, u, 0, j, K)",
"stack.append((cx, y, hx, hy, k4, F41, F42, F43, F44)) if len(roots) == n:",
"a*f[i], -a return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in",
"result.append((g, i)) i += 1 if not args.get('include', False): return coeff, result else:",
"K) if k == 1: a, b, c, d = a1, b1, c1,",
"y == _max: upper.append((x, y, dx, dy)) del group[i] break _min = min([",
"= dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v = u -",
"K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f",
"u, K) sqf = dmp_exquo(f, gcd, u, K) if K.has_Field or not K.is_Exact:",
"1, u, K) if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G,",
"K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\" cont =",
"a primitive polynomial over a field. \"\"\" return K.one, f def dup_primitive(f, K):",
"g at certain points and computing (fast) integer GCD of those evaluations. The",
"dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) h, cff, cfg",
"K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0)",
"dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm )",
"common = K1.one if not v: for c in g: common = K1.lcm(common,",
"u, K): \"\"\"Computes subresultant PRS of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f,",
"v, K), dmp_pow(lc, du-dw, v, K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d),",
"g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u, K)",
"all or dup_degree(g) > 0: result.append((g, i)) i += 1 if not args.get('include',",
"t, cond, fast, K): \"\"\"Refine a positive root of `f` given an interval",
"None else: g[i] = dup_LC(r, K) f, i = q, i + 1",
"u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f)",
"dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u, K) if u ==",
"polynomial GCD from integer GCD. \"\"\" f = [] while h: g =",
"@cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at `x_j = a_j,",
"= dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2, y2,",
"K.has_Field: raise DomainError('computation can be done only in a field') f = dup_sqf_part(f,",
"K) return [(g, i)] + rest def dup_extract(f, g, K): \"\"\"Extracts common content",
"dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k))",
"dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else:",
"= F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4,",
"factors: g = dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g,",
"indefinite integral of `f` in `x_0` in `K[X]`. \"\"\" if not u: return",
"p) d = dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K) c",
"dmp_ground_trunc(c, p, v, K) for c in f ], u) def dup_monic(f, K):",
"rest = result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] +",
"= [h] + F else: break return [f] + F def dup_sturm(f, K):",
"q = dmp_inner_gcd(f, h, u, K) all = args.get('all', False) while True: d",
"\"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f,",
"_dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34,",
"is the correct GCD. This gives cofactors as a side effect. References ==========",
"\"\"\" return [ dup_taylor(f, c, K) for f in F ] def _dup_sturm_mirror(F,",
"a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v = u",
"a polynomial at `x_0 = a` in `K[X]` using Horner scheme. \"\"\" if",
"len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\" if i",
"(u, v) in I_neg ] + \\ [ (( u, v), k) for",
"dmp_sub(R, e, v, K), v, K) r = dmp_add(r, c, v, K) r",
"f in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F4",
"dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial",
"K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a polynomial in",
"> 0: result.append((g, i)) i += 1 if not args.get('include', False): return coeff,",
"= dmp_diff(p, 1, u, K) h = dmp_sub(q, d, u, K) if dmp_zero_p(h,",
"u, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\" cont",
"du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du %",
"return None def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in `K[x]`. Given",
"i = 1, 1 p, q = K.one, K.one for b, d in",
"in `K[X]`. \"\"\" if not u: return dup_resultant(f, g, K) if K.has_Field: if",
"dmp_degree(f, u) dg = dmp_degree(g, u) if df > 0 and dg >",
"not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if",
"K): \"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\" if not u: return",
"% K) if s == t: return (s, t) if s > t:",
"if y == _max: upper.append((x, y, dx, dy)) del group[i] break _min =",
"return dup_rr_content(f, K) cont, v = K.zero, u-1 for c in f: gc",
"K) gc, G = dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F,",
"dup_div(g, cfg, K) if not r: cff_, r = dup_div(f, h, K) if",
"u, K) all = args.get('all', False) while True: d = dmp_diff(p, 1, u,",
"dmp_subresultants(f, g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _,",
"zip(perm, monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return",
"if dup_degree(f) <= 0: return [] eps, fast = args.get('eps'), args.get('fast') if eps",
"lc = dup_LC(g, K) if not d: q = c else: q =",
"K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases",
"(a, b, c, d), cond, fast, K) def dup_refine_real_root(f, s, t, n, K,",
"I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u), k) for (u,",
"if not dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1) k = dup_sign_variations(f,",
"is recovered from the integer image by interpolation. The final step is to",
"= dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont for c in f[1:]:",
"a+b, d, c+d if k2 > 1 or (k1 > 0 and k2",
"tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u,",
"`K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert,",
"u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if",
"if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return",
"dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i = v-1, i+1 return",
"C) f = dup_scale(f, a, C) u = dup_strip([ C.real(c) for c in",
"b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one, v) B, D",
"f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1",
"if all or dmp_degree(g, u) > 0: result.append((g, i)) i += 1 if",
"+ a)` in `K[x]`. \"\"\" f, n = list(f), dup_degree(f) for i in",
"\"\"\"Returns square-free part of a polynomial in `K[x]`. \"\"\" if not f: return",
"dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD",
"= _rec_eval_tail(f, 0, A, u, K) if u == len(A)-1: return e else:",
"= [] while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0,",
"v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v),",
"where `T_n` and `T_m` are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>,",
"(u, v) in I_pos ]) I_pos, I_neg = [], [] F_pos, F_neg =",
"K)]) if not f: return [] h = [f[0]] for c in f[1:]:",
"if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast, K))",
"or m < 0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f,",
"n s, t = dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative: return",
"dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial",
"try: R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if K.is_one(P):",
"dup_rshift(f, 1, K) a, b, c, d = b, a+b, d, c+d i",
"K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f,",
"cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive",
"F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K)",
"not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f,",
"dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u, K)",
"K1.is_one(common): f = dup_mul_ground(f, common, K0) if not args.get('convert'): return common, f else:",
"v, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while",
"dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff,",
"F3, F4 = stack.pop() hx, hy = dx/2, dy/2 cx, cy = x",
"return dmp_eval(g, a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c,",
"f_2 o ... f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic",
"h = dmp_diff(f, 1, u, K) g, p, q = dmp_inner_gcd(f, h, u,",
"k in factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v,",
"v = dmp_zeros(m, u-1, K), u-1 for i, c in enumerate(reversed(f)): n =",
"univariate polynomials `f` and `g` in `Z[x]`, returns their GCD and cofactors, i.e.",
"u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result",
"for c in f: c = c % p if c > p",
"ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g,",
"h, u, K) all = args.get('all', False) while True: d = dmp_diff(p, 1,",
"[ dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f,",
"= dmp_to_dict(f, u), [], [] for monom, coeff in F.iteritems(): if not coeff.is_ground:",
"v, K), d, v, K) if not d: q = c else: q",
"cfg = dmp_exquo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX = 6",
"dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u,",
"K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT",
"j)) return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K):",
"K0, K = K, K.float_domain() f = dup_convert(f, K0, K) else: raise DomainError(\"isolation",
"K0.quo(c, cg), K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0):",
"else: w = v-1 for c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w,",
"= dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u,",
"f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and",
"B.append(b) D.append(d) h = dmp_prem(f, g, u, K) h = [ dmp_exquo(ch, b,",
"u, K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b",
"upper[i] = (r, multiplicity[r]) for i, r in enumerate(lower): lower[i] = (r, multiplicity[r])",
"g, u, K): \"\"\"Computes polynomial LCM over a field in `K[X]`. \"\"\" h",
"n < m: return dmp_zero(u) deriv, c, v = [], K.one, u-1 for",
"dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD",
"dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\" if not",
"for c in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f =",
"dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0,",
"c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over",
"if k == 1: roots = [dup_inner_refine_real_root( f, (a, b, c, d), cond,",
"`x_j = a_j, ...` in `K[X]`. \"\"\" if not A: return f if",
"F(b, d)) < eps else: cond = lambda a, b, c, d, i,",
"i == u: return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i+1,",
"g, K) n = dmp_degree(f, u) m = dmp_degree(g, u) if n <",
"[] _, factors = dup_sqf_list(f, K) for g, k in factors: g =",
"m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m,",
"d) if s <= t: return (s, t) else: return (t, s) def",
"(x2, y2, dx2, dy2, F2), k2) roots[i] = (f1, (x1, y1, dx1, dy1,",
"<= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return [] h",
"dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs,",
"i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g",
"NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\"",
"dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2, y2, dx2,",
"y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating rectangles",
"]) for i, (x, y, dx, dy) in enumerate(group): if y == _max:",
"K) if not r: cfg_, r = dup_div(g, h, K) if not r:",
"a polynomial in `x_j` at `a` in `K[X]`. \"\"\" if j > u:",
"R def dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\"",
"continue a, Q = K.log(-f[i], 2), [] for j in xrange(i+1, n): if",
"K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1,",
"(x, cy, hx, hy, (F21, F22, F23, F24)) # Quadrant #3: -- F31",
"cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h, u, K) return",
"h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K) return",
"def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return the exact number of",
"in a field') a, b = [K.one], [] while g: q, r =",
"fast = args.get('fast') if type(n) is not int: cond = lambda a, b,",
"dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating rectangles for all",
"p = dmp_one(v, K) q = dmp_one(v, K) for b, d in zip(B,",
"f = dup_scale(f, A, K) a, c, A = A*a, A*c, K.one if",
"f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def",
"return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [],",
"K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" if not",
"K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u,",
"I_pos) _, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) =",
"K) if not d: q = c else: q = c**(d-1) c =",
"not supported over %s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y,",
"for j in xrange(0, i): f[j+1] += a*f[j] return f def dup_transform(f, p,",
"K) result = K.zero for c in f: result *= a result +=",
"K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3,",
"= dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1, K1, K0) c =",
"else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\") def",
"K)), g_norm // abs(dup_LC(g, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff",
"K) if h == [K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\")",
"GCD from integer GCD. \"\"\" f = [] while not dmp_zero_p(h, v): g",
"dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res, p,",
"g, u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2],",
"k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s positive roots. \"\"\"",
"abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i in",
"G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _,",
"dup_sub_mul(h, s, f, K) t = dup_exquo(F, g, K) return s, t, h",
"= K, K.float_domain() f = dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex",
"import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub,",
"Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one,",
"cfg = gg // h h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h,",
"in `K[x]`. \"\"\" f, n, a = list(f), dup_degree(f), -K.one for i in",
"A = A*a, A*c, K.one if A >= K.one: f = dup_taylor(f, A,",
"u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one,",
"g, r a, b = b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a,",
"g[i] = dup_LC(r, K) f, i = q, i + 1 return dup_from_raw_dict(g,",
"if K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h, c, K) cff =",
"@cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of `f` in `x_0`",
"K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f,",
"K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K)",
"and a primitive polynomial over a ring. \"\"\" if dmp_zero_p(f, u): return K.zero,",
"Q = K.log(-f[i], 2), [] for j in xrange(i+1, n): if f[j] <=",
"None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s",
"coeff, K) return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args):",
"`x_j = a` in `K[X]` using Horner scheme. \"\"\" if j < 0",
"return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i",
"r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg x = 73794*x",
"gcd, u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K)",
"\"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1.0 /",
"b, c, d), cond, fast, K) def dup_refine_real_root(f, s, t, n, K, **args):",
"as a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of the",
"1: roots.append((cx, cy, hx, hy, (F11, F12, F13, F14))) elif k1 > 1:",
"> t: s, t = t, s negative = False if s <",
"if not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f if",
"j in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return",
"g = dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u, K)[-1] c, _,",
"None: return result fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g,",
"return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f,",
"cy, hx, hy, k1, F11, F12, F13, F14)) # Quadrant #2: -+ F21",
"def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm sequence at x+I*y in",
"gcd, u, K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else:",
"K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1, F2, F3,",
"`x_0` of a polynomial in `K[X]`. \"\"\" if not u: return dup_diff(f, m,",
"K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement",
"= dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1,",
"+ hx, y + hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K)",
"i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i =",
"F def dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine a complex root",
"f = dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g, u, K0, K1)",
"dy, _), k) in roots: multiplicity[(x, y, dx, dy)] = k roots =",
"u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) coeff =",
"\"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in,",
"K): \"\"\"Evaluate a polynomial at `x_j = a` in `K[X]` using Horner scheme.",
"= h % x if g > x // 2: g -= x",
"= dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1) g = dup_convert(g, K0,",
"`Z[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if n <",
"given a Mobius transform. \"\"\" F, i = K.get_field(), 0 while not c",
"return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a",
"complete functional decompositions of polynomials are not unique, consider examples: 1. `f o",
"= _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 == 1: return",
"polynomial GCD of `f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u,",
"q = dmp_one(v, K) for b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1],",
"dup_degree(D) <= B: while True: a += K.one if a == p: raise",
"s == t: return (s, t) if s > t: s, t =",
"s negative = False if s < 0: if t <= 0: f,",
"v, K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p,",
"dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift,",
"Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g,",
"g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of `f` in",
"`f` in `K[x]`. Given an univariate polynomial `f` with coefficients in a field",
"== t: return (s, t) if s > t: s, t = t,",
"= dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if K.is_one(P): r =",
"K.one, K), f a1, b1, c1, d1 = a, a+b, c, c+d if",
"in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s,",
"r: r[0]) if not squarefree: for i, r in enumerate(upper): upper[i] = (r,",
"F11 = Fx F12 = _dup_sturm_shift(F2, hx, K) F13 = F3 F14 =",
"hx, hy, k1, F11, F12, F13, F14)) # Quadrant #2: -+ F21 =",
"not None: return result fc, F = dmp_primitive(f, u, K) gc, G =",
"in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K):",
"in `K[x]`. \"\"\" if not f: return f lc = dup_LC(f, K) if",
"dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if not f:",
"`x**n o x**m = x**m o x**n` 3. `T_n o T_m = T_m",
"of sign variations of `f` in `K[x]`. \"\"\" prev, k = K.zero, 0",
"k4 == 1: return (cx, y, hx, hy, (F41, F42, F43, F44)) raise",
"g, u, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" if",
"// (j - i)) t += 1 if not Q: continue P.append(min(Q)) if",
"F24))) elif k2 > 1: stack.append((x, cy, hx, hy, k2, F21, F22, F23,",
"u): cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): h =",
"cofactors of `f` and `g` in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f,",
"f = dup_scale(f, a, C) u = dup_strip([ C.real(c) for c in f",
"dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else: f, s =",
"input polynomials as a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation",
"fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h",
"or g): return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return",
"direction of a Sturm sequence at its origin. \"\"\" return [ dup_mirror(f, K)",
"f_n)) and `f_2, ..., f_n` are monic and homogeneous polynomials of at least",
"stack.append((x, y, dx, dy, k, F1, F2, F3, F4)) while stack: x, y,",
"dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\")",
"hx, hy, (F41, F42, F43, F44))) elif k4 > 1: stack.append((cx, y, hx,",
"dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial over",
"polynomial GCD is recovered from the integer image by interpolation. The evaluation proces",
"0: return None else: g[i] = dup_LC(r, K) f, i = q, i",
"if i == j: return dmp_diff(g, m, v, K) w, i = v-1,",
"= dup_prem(f, g, K) h = dup_exquo_ground(h, b, K) return R, B, D",
"Given univariate polynomials `f` and `g` in `Z[X]`, returns their GCD and cofactors,",
"= {} for (x, y, dx, dy) in roots: if x in groups:",
"or not g: return R, B, D h = dup_prem(f, g, K) h",
"K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm //",
"None def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K): \"\"\"Refine a positive",
"squarefree: for i, r in enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r",
"and a primitive polynomial in `K[x]`. \"\"\" if not u: return dup_primitive(f, K)",
"quo(f, h) and cfg = quo(g, h) The algorithm is purely heuristic which",
"of polynomials are not unique, consider examples: 1. `f o g = f(x",
"\"\"\"Computes subresultant PRS of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0]",
"f lc = dup_LC(f, K) if K.is_one(lc): return f else: return dup_quo_ground(f, lc,",
"i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes",
"dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f,",
"R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d, v, K)",
"1: for i, (f1, r1, k1) in enumerate(roots): x1, y1, dx1, dy1, F1",
"gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K)",
"for i in xrange(0, m): c, n = c*K(n), n-1 for coeff in",
"K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" if not",
"not None: return result df = dmp_degree(f, u) dg = dmp_degree(g, u) gcd,",
"dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v,",
"== j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i =",
"u, K) h = dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def",
"v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return",
"_dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 == 1: roots.append((x, cy,",
"K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4",
"dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if",
"h = dup_prem(f, g, K) h = dup_mul_ground(h, b, K) while h: k",
"primitive polynomial in `K[x]`. \"\"\" if not u: return dup_primitive(f, K) if dmp_zero_p(f,",
"not squarefree: for i, r in enumerate(upper): upper[i] = (r, multiplicity[r]) for i,",
"dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt ) from",
"0 while not c or not cond(a, b, c, d, i, F): A",
"K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise",
"> 0: return (K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1], K), R)",
"K): \"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\" a, b, c, d",
"if K.is_one(lc): return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u,",
"[], [(a, b, c, d, f, k)] F = K.get_field() while stack: a,",
"- F(b, d)) < eps else: cond = lambda a, b, c, d,",
"\"\"\" if not f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K),",
"`True` if `f` is a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u):",
"k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2 while not ((x2",
"cond = lambda a, b, c, d, i, F: True if args.get('sqf', False):",
"cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r = dmp_div(g, cfg, u, K)",
"K.one for i in xrange(0, m): c, n = c*K(n), n-1 for coeff",
"[], 1 h = dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f, h,",
"K) for s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k],",
"= K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return",
"F13, F14, hx, hy, K) if k1 == 1: roots.append((cx, cy, hx, hy,",
"h = dmp_subresultants(f, g, u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1,",
"polynomial modulo a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1,",
"= K.float_domain() else: raise DomainError(\"isolation of complex roots not supported over %s\" %",
"primitive polynomial over a ring. \"\"\" cont = dup_content(f, K) if not f",
"dup_div(f, cff, K) if not r: cfg_, r = dup_div(g, h, K) if",
"def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\" if",
"K0, K1) g = dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f,",
"K.has_Field or not K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f, K) else:",
"in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert,",
"if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_",
"over a field. \"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns content and",
"return result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg, g",
"g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of `f`",
"r = dup_div(f, h, K) if not r: h = dup_mul_ground(h, gcd, K)",
"while not dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h",
"x, y, dx, dy, eps, K): \"\"\"Refine a complex root using Wilf's global",
"`a` in `K[X]`. \"\"\" if j > u: raise IndexError(\"-%s <= j <",
"a ring. \"\"\" if not (f or g): return [], [], [] elif",
"f or not g: return R, B, D h = dup_prem(f, g, K)",
"abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for i in xrange(0, HEU_GCD_MAX):",
"n, b = list(f), dup_degree(f), a for i in xrange(n-1, -1, -1): f[i],",
"hy, k2, F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1",
"x + hx, y + hy F1, F2, F3, F4 = F Fx",
"F43, F44, hx, hy, K) if k4 == 1: roots.append((cx, y, hx, hy,",
"1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f =",
"f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root",
"c2, c1, d2, d1 f1, f2, k1, k2 = f2, f1, k2, k1",
"can be done only in a field') f = dup_sqf_part(f, K) sturm =",
"h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate",
"dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K)",
"u): return K.zero, f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K):",
"F24, hx, hy, K) if k2 == 1: return (x, cy, hx, hy,",
"g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f, K), [-K.one],",
"K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f",
"x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) +",
"\"\"\"Returns `True` if `f` is a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f,",
"polynomials of at least second degree. Unlike factorization, complete functional decompositions of polynomials",
"HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime from sympy.utilities import (",
"return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM",
"K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients",
"is to verify if the interpolated polynomial is the correct GCD. This gives",
"defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ==========",
"\"\"\"m-th order derivative of a polynomial in `K[x]`. \"\"\" if m <= 0:",
"try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u,",
"y1, dx1, dy1, F1), k1) multiplicity = {} for (_, (x, y, dx,",
"m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m,",
"K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant",
"dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo,",
"g, u, K) h = dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h,",
"over a field. \"\"\" if not u: return dup_ff_prs_gcd(f, g, K) result =",
"K) if K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h, c, K) cff",
"dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[X]`.",
"((x2 >= x1+dx1 or x2+dx2 <= x1) and (y2 >= y1+dy1 or y2+dy2",
"sorted(lower, key=lambda r: r[0]) if not squarefree: for i, r in enumerate(upper): upper[i]",
"x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g,",
"y+dy, K) F = (F1, F2, F3, F4) x, y, dx, dy, _",
"recovered from the integer image by interpolation. The evaluation proces reduces f and",
"df % s != 0: continue h = _dup_right_decompose(f, s, K) if h",
"K(s), v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle",
"y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K): \"\"\"Refine",
"i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g, x,",
"f g = [K.zero]*m for i, c in enumerate(reversed(f)): n = i+1 for",
"u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u,",
"K), K) sqf = dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact: return",
"= K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g",
"coefficients over a ring. \"\"\" cont = K.zero for c in f: cont",
"K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" if not u: return",
"h = dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0, u, K)",
"f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given",
"for c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common",
"= dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1, K0) c =",
"dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f,",
"gives cofactors of the input polynomials as a side effect. References ========== ..",
"return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g,",
"dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p,",
"K.zero, 0 for coeff in f: if coeff*prev < 0: k += 1",
"[] while g: q, r = dup_div(f, g, K) f, g = g,",
"def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\"",
"m, w, i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def",
"is not None: return result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0,",
"def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if",
"continue if not s-j in g: continue fc, gc = f[n+j-i], g[s-j] coeff",
"return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns",
"hx, hy, (F31, F32, F33, F34))) elif k3 > 1: stack.append((x, y, hx,",
"b = dmp_ground_LC(g, u, K) v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n",
"r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1, K1, K0) c",
"cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff, u, K)",
"= dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg",
"K1) if K1 is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0,",
"i, (x, y, dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y,",
"return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)`",
"dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K)",
"p, q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if",
"99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for i",
"_dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K):",
"= dmp_LC(g, K) v = u - 1 h = dmp_gcd(F, G, v,",
"= dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i,",
"must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u,",
"i)) break g, p, q = dmp_inner_gcd(p, h, u, K) if all or",
"n < 0 or m < 0: return dmp_zero(u-1) A = dmp_max_norm(f, u,",
"f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K) c =",
"dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K),",
"a, j, u, K): \"\"\"Differentiate and evaluate a polynomial in `x_j` at `a`",
"dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g =",
"u, K) h = dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h, u):",
"in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F2 ],",
"_rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order",
"K) if result is not None: return result h = dup_subresultants(f, g, K)[-1]",
"if not args.get('convert'): return common, f else: return common, dmp_convert(f, u, K0, K1)",
"K) if s < 0: p = dmp_neg(p, v, K) i = dmp_degree(R[-2],",
"s > t: s, t = t, s negative = False if s",
"s = dup_taylor(f, -K.unit, K), s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f,",
"(P, p, K), v, K) P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f,",
"cofactors, i.e. polynomials `h`, `cff` and `cfg` such that:: h = gcd(f, g),",
"dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[X]`. \"\"\"",
"c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial in `K[X]`.",
"in `Z[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if n",
"I_pos ]) def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm sequence at",
"return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants",
"in f: c = c % p if c > p // 2:",
"F_pos[k], F_neg[k] = f, g step = lambda a, b, c, d, i,",
"= f2, f1, k2, k1 if k1 == 0: continue if k1 ==",
"or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\")",
"f ]) seq = [u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K)",
"= dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u, K) cff =",
"x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex root isolating",
"\"\"\" if not u: return dup_diff(f, m, K) if m <= 0: return",
"Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def",
"1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one while P",
"or g): return [], [], [] elif not f: return dup_monic(g, K), [],",
"= dmp_prem(f, g, u, K) h = [ dmp_exquo(ch, b, v, K) for",
"def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" if",
"xrange(0, m): c, n = c*K(n), n-1 for coeff in f[:-m]: h =",
"D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K) return r",
"K): \"\"\"Compute the number of sign variations of `f` in `K[x]`. \"\"\" prev,",
"= K.exquo((-lc)**d, q) b = -lc * c**(m-k) f, g, m, d =",
"if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G, p, v, K)",
"in f[1:]: result = dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v,",
"1 n = dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1,",
"K): return F(b, d), F(b, d) f, g = dup_taylor(f, K.one, K), f",
"in `K[X]`. \"\"\" if not u: return dup_compose(f, g, K) if dmp_zero_p(f, u):",
"dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground,",
"f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break if",
"= (f1, (x1, y1, dx1, dy1, F1), k1) multiplicity = {} for (_,",
"K)): f = dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f, u) <=",
"if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g,",
"def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two polynomials in `K[x]`. \"\"\"",
"if not f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K))",
"= dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res,",
"dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools",
"perms: G = dict(F) for sign, monom in zip(perm, monoms): if sign ==",
"if not u: return dup_eval(f, a, K) if not a: return dmp_TC(f, K)",
"% (u, u, j)) return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f,",
"@cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i == u: return",
"v: R = dup_strip([R]) e = dup_strip([e]) else: R = [R] e =",
"B: p = K(nextprime(p)) while not (a % p) or not (b %",
"over a ring. \"\"\" cont = K.zero for c in f: cont =",
"- 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one while",
"K), u-1 if dmp_zero_p(f, u): return cont for c in f[1:]: cont =",
"K0, K1) if K1 is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u,",
"using subresultant PRS. \"\"\" if not f or not g: return (K.zero, [])",
"modulo a prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0] %",
"return h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no",
"squarefree = args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args)",
"not r: cff_, r = dup_div(f, h, K) if not r: h =",
"K) return _rec_diff_eval(f, m, a, u, 0, j, K) def dup_half_gcdex(f, g, K):",
"def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a",
"h, K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff,",
"True: result = _dup_decompose(f, K) if result is not None: f, h =",
"= (f2, (x2, y2, dx2, dy2, F2), k2) roots[i] = (f1, (x1, y1,",
"for j in xrange(i+1, n): if f[j] <= 0: continue q = t",
"K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q direction. \"\"\" C = K.complex_domain()",
"at `x = a` in `K[x]` using Horner scheme. \"\"\" if not a:",
"return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over",
"if k2 == 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2,",
"is reached. \"\"\" while dx >= eps and dy >= eps: x, y,",
"K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2,",
"f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1:",
"of CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K),",
"supported over %s\" % K) if s == t: return (s, t) if",
"if dmp_zero_p(f, u): return f h = [f[0]] for c in f[1:]: h",
"for c in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K):",
"\"\"\" prev, k = K.zero, 0 for coeff in f: if coeff*prev <",
"LMQ upper bound for `f`'s positive roots. \"\"\" n, t, P = len(f),",
"gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError )",
"return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm",
"u-1 for coeff in f[1:]: result = dmp_mul_ground(result, a, v, K) result =",
"None: return result df = dup_degree(f) dg = dup_degree(g) gcd, f, g =",
"and cofactors of `f` and `g` in `K[X]`. \"\"\" if not u: return",
"s, i, v = 1, 1, u-1 p = dmp_one(v, K) q =",
"cont, f else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u,",
"dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res, R def dup_resultant(f, g, K):",
"#4: +- F41 = _dup_sturm_shift(F1, hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx,",
"dy2, F2), k2) roots[i] = (f1, (x1, y1, dx1, dy1, F1), k1) multiplicity",
"+ \\ [ (( u, v), k) for (u, v, k) in I_pos",
"= -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def",
"for f in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in",
"= [], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 =",
"p, q = K.one, K.one for b, d in zip(B, D)[:-1]: du =",
"%s\" % K) if dup_degree(f) <= 0: return [] eps, fast = args.get('eps'),",
"m = dup_degree(g) if n < m: f, g = g, f n,",
"dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not u:",
"= i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n)))",
"= dmp_one(v, K) q = dmp_one(v, K) for b, d in zip(B, D)[:-1]:",
"G, v, K) cff = [ dmp_exquo(cf, h, v, K) for cf in",
"k - k1 - r a2, b2, c2, d2 = b, a+b, d,",
"K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u), k) for",
"\"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`,",
"else: roots = [] _, factors = dup_sqf_list(f, K) for g, k in",
"K1 is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if",
"N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B = n*M",
"if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f, K), [-K.one], []",
"f = dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd, u, K) return",
"k1)) if k2 == 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2,",
"F42, F43, F44)) raise RefinementFailed(\"no roots in (%s, %s) x (%s, %s) rectangle\"",
"of `f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def",
"x, y, dx, dy, F, K) return x, y, dx, dy, F def",
"*= lc**(dv*(1+d)) if s < 0: p = -p i = dup_degree(R[-2]) res",
"K) return r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT for",
"by raising an exception. In this case you will need to switch to",
"v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u,",
"K.zero, K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1, K) k =",
"q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q, c,",
"k1 == 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1,",
"c1, d2, d1 f1, f2, k1, k2 = f2, f1, k2, k1 if",
"def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)` in `K[x]`.",
"coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff",
"h = dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s, g, K)",
"<= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t",
"h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K),",
"_dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K):",
"x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 =",
"[], [] F_pos, F_neg = {}, {} for f, k in factors: for",
"K0) c = dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1,",
"u, K): \"\"\"Compute resultant of `f` and `g` modulo a prime `p`. \"\"\"",
"K.get_field(), 0 while not c or not cond(a, b, c, d, i, F):",
"dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else:",
"= K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0,",
"(r, multiplicity[r]) for i, r in enumerate(lower): lower[i] = (r, multiplicity[r]) return upper,",
"K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return cont",
"return dup_monic(f, K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K)",
"u, K0) if not args.get('convert'): return common, f else: return common, dmp_convert(f, u,",
"r = dup_div(f, g, K) f, g = g, r a, b =",
"(f or g): return [], [], [] elif not f: return dup_monic(g, K),",
"K) v = u - 1 h = dmp_gcd(F, G, v, K) cff",
"\"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K)",
"F42, F43, F44)) if len(roots) == n: eps = args.get('eps') if eps is",
"k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast, K)) else:",
"dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h, c, K)",
"A = K.zero if fast and A > 16: f = dup_scale(f, A,",
"y, dx, dy)) del group[i] break _min = min([ r[1] for r in",
"K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if",
"using Horner scheme. \"\"\" if not u: return dup_eval(f, a, K) if not",
"K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial",
"= dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f,",
"\"\"\" hx, hy = dx/2, dy/2 cx, cy = x + hx, y",
"return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots",
"not r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff =",
"hy, (F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx,",
"dup_eval(f, K.zero, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K)",
"F43, F44)) raise RefinementFailed(\"no roots in (%s, %s) x (%s, %s) rectangle\" %",
"K1, K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0)",
"= f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return",
"dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if",
"v, K) P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0):",
"not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u,",
"f = dup_monic(f, K) return a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean",
"cond, fast, K)) continue f1 = dup_taylor(f, K.one, K) a1, b1, c1, d1,",
"= dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd, u, K) return gcd,",
"v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f",
"[Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms for Algebraic Computation, Academic",
"if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\")",
"= dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f,",
"- v0 for v1, v0 in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x,",
"dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a, v, K) if not",
"I_neg[i+j+1] = (s, t, m) I_neg[i] = (u, v, k) return sorted([ ((-v,",
"(u, u, j)) return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f,",
"dup_TC(f, K) result = K.zero for c in f: result *= a result",
"K1 = K0.get_ring() common = K1.one for c in f: common = K1.lcm(common,",
"e = dup_strip([e]) else: R = [R] e = [e] d = K.invert(dup_eval(D,",
"+ rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of a",
"= dmp_LC(f, K) G = dmp_content(g, u, K) else: F = dmp_content(f, u,",
"over %s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2",
"derivative in `x_0` of a polynomial in `K[X]`. \"\"\" if not u: return",
"order derivative in `x_j` of a polynomial in `K[X]`. \"\"\" if j <",
"for perm in perms: G = dict(F) for sign, monom in zip(perm, monoms):",
"for c in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K):",
"`K[x]`. \"\"\" d = dup_degree(f) if d <= 0: return K.zero else: s",
"over a ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f else: return K.one,",
"return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns",
"= dx/2, dy/2 cx, cy = x + hx, y + hy F1,",
"k = dup_sign_variations(f, K) if k == 0: continue if k == 1:",
"or not f: return f g = [K.zero]*m for i, c in enumerate(reversed(f)):",
"K): \"\"\"Evaluate a polynomial at `x_j = a_j, ...` in `K[X]`. \"\"\" if",
"return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f,",
"raise ValueError(\"can't refine a real root on (%s, %s)\" % (s, t)) fast",
"f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued",
"g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n,",
"consider examples: 1. `f o g = f(x + b) o (g -",
"if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u,",
"[] if k == 1: roots = [dup_inner_refine_real_root( f, (a, b, c, d),",
"else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g,",
"= (-K.one)**(d+1) c = -K.one B, D = [b], [d] if not f",
"_dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\"",
"else: F = dmp_content(f, u, K) G = dmp_LC(g, K) v = u",
"h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return",
"return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns",
"not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u,",
"C(p, q), C(x, y) f = dup_convert(f, K, C) f = dup_taylor(f, b,",
"polynomial GCD using subresultants over a field. \"\"\" if not u: return dup_ff_prs_gcd(f,",
"== len(A)-1: return e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g,",
"in g ] if i < u - len(A) + 1: return h",
"result += c return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a",
"k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued fractions",
"(F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K)",
"u, K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\" if not u:",
"v, K) c = dmp_ground(-K.one, v) B, D = [b], [d] if dmp_zero_p(f,",
"0 or dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u-1, K), u-1",
"LCM over a ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K)",
"u: return dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f,",
"1 s, t = F(a, c), F(b, d) if s <= t: return",
"K) if k3 == 1: return (x, y, hx, hy, (F31, F32, F33,",
"] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo",
"composition `f(g)` in `K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K),",
"i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res,",
"K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\")",
"not args.get('convert'): return common, f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def",
"v, K) for ch in h ] return R, B, D @cythonized(\"u\") def",
"return dmp_zero(u) deriv, c, v = [], K.one, u-1 for i in xrange(0,",
"= [ dup_sign_variations([ dup_eval(f, hx, K) for f in F1 ], K), dup_sign_variations([",
"g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS",
"d2 = c2, c1, d2, d1 f1, f2, k1, k2 = f2, f1,",
"abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in f) while True: r =",
"K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def",
"R, P, p, K): \"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\" return",
"* c**(m-k) f, g, m, d = g, h, k, m-k B.append(b) D.append(d)",
"\"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\" if not u: return dup_resultant(f,",
"F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K)",
"1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff,",
"Quebec, Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result",
"False) while True: d = dmp_diff(p, 1, u, K) h = dmp_sub(q, d,",
"for all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc",
"g, u, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in",
"hx, hy, K) if k4 == 1: roots.append((cx, y, hx, hy, (F41, F42,",
"return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content",
"cx, cy, K) # Quadrant #1: ++ F11 = Fx F12 = _dup_sturm_shift(F2,",
"sorted([ ((-v, -u), k) for (u, v, k) in I_neg ] + \\",
"F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12,",
"= dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift",
"PRS of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\")",
"b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero,",
"g, u, K): \"\"\"Computes polynomial LCM over a ring in `K[X]`. \"\"\" fc,",
"K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc",
"x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K)",
"dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h,",
"= randfloat() if r < 0.5: break x, y, dx, dy = -B+r,",
"dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content",
"coeff, K) return [(g, i)] + rest def dup_extract(f, g, K): \"\"\"Extracts common",
"dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args):",
"by variable into a large integer. The final step is to verify if",
"K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg",
"d1, f1, k1)) if k2 == 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root(",
"if t <= 0: f, s, t, negative = dup_mirror(f, K), -t, -s,",
"\"\"\" s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K)",
"= dup_div(f, g, K) f, g = g, r a, b = b,",
"K) f = dup_monic(f, K) else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f,",
"p = dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K),",
"not K.has_Field: raise DomainError('computation can be done only in a field') a, b",
"return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is",
"K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ:",
"\"\"\" f, n, a = list(f), dup_degree(f), -K.one for i in xrange(n-1, -1,",
"j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j,",
"not dup_eval(f, K.zero, K): return F(b, d), F(b, d) f, g = dup_taylor(f,",
"[] elif not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not g:",
"K) if k2 == 1: return (x, cy, hx, hy, (F21, F22, F23,",
"not u: return dup_content(f, K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u,",
"dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1,",
"w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K)",
"and cofactors of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not",
"F43, F44))) elif k4 > 1: stack.append((cx, y, hx, hy, k4, F41, F42,",
"a polynomial in `K[x]`. \"\"\" if not f: return f if K.is_negative(dup_LC(f, K)):",
"function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ:",
"fast and A > 16: f = dup_scale(f, A, K) a, c, A",
"m <= 0: return f n = dup_degree(f) if n < m: return",
"unique, consider examples: 1. `f o g = f(x + b) o (g",
"] + \\ [ (( u, v), k) for (u, v, k) in",
"def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative in `x_j` of a",
"= dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def dmp_compose(f, g, u, K):",
"polynomial GCD by evaluating polynomials f and g at certain points and computing",
"sequence of `f` in `F[x]`. Given an univariate, square-free polynomial `f(x)` returns the",
"0, K) c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) r =",
"for (u, v) in I_neg ] + I_pos) _, factors = dup_sqf_list(f, K)",
"hx, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for",
"q = dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g, u) > 0:",
"if n < 0 or m < 0: return dmp_zero(u-1) K1 = K0.get_ring()",
"m, u, 0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at",
"j)) if not j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return",
"K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1, K1,",
"dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f",
"rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F,",
"dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f` and `g`",
"k = dup_sign_variations(f, K) if k == 1: a, b, c, d =",
"K)[1] cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r",
"def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a field in `K[x]`. \"\"\"",
"if not r: cff_, r = dup_div(f, h, K) if not r: h",
"\"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f,",
"#1: ++ F11 = Fx F12 = _dup_sturm_shift(F2, hx, K) F13 = F3",
"K) if m <= 0: return f n = dmp_degree(f, u) if n",
"GCD is recovered from the integer image by interpolation. The final step is",
"dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if K.has_Field or not",
"K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if",
"= dup_diff(p, 1, K) h = dup_sub(q, d, K) if not h: result.append((p,",
"using subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result",
"u-1, K) for c in f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u,",
"= dup_extract(f, g, K) if df == 0 or dg == 0: return",
"+ 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm //",
"dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps,",
"p, v, K) e = dmp_eval(r, a, v, K) if not v: R",
"cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff,",
"> 0: return None if not (df or dg): F = dmp_LC(f, K)",
"dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2), k2)",
"m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w,",
"K) if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G, p, v,",
"h = _dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f,",
"B, D h = dup_prem(f, g, K) h = dup_mul_ground(h, b, K) while",
"@cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[x]`.",
"result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return result fc,",
"dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return",
"\"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)",
"xrange(n-1, -1, -1): f[i], b = b*f[i], b*a return f def dup_taylor(f, a,",
"Sturm sequence at x+I*y in p+I*q direction. \"\"\" C = K.complex_domain() a, b",
"and cofactors, i.e. polynomials `h`, `cff` and `cfg` such that:: h = gcd(f,",
"_dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3, hx, K) F24 = F4",
"IndexError(\"-%s <= j < %s expected, got %s\" % (u, u, j)) return",
"stack.append((x, cy, hx, hy, k2, F21, F22, F23, F24)) # Quadrant #3: --",
"dup_monic(f, K), [dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def",
"v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\"",
"i == j: return dmp_diff(g, m, v, K) w, i = v-1, i+1",
"u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns",
"K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) if",
"if du % 2 and dv % 2: s = -s lc, i",
"= dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a], K) D =",
"cff = _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K) if not",
"modulo a constant `p` in `K`. \"\"\" if K.is_ZZ: g = [] for",
"\"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`. \"\"\" if",
"else: g[i] = dup_LC(r, K) f, i = q, i + 1 return",
"`F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f,",
"u, K): \"\"\"Returns square-free part of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f,",
"K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1], K) else: h =",
"], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F4 ], K), ]",
"k) in enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]): while not (s",
"i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg = dmp_eval(g,",
"u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\"",
"a field. \"\"\" if not f: return K.zero else: return K.one @cythonized(\"u\") def",
"gc) h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h,",
"c else: q = dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q, v,",
"v, K), v, K) f, g, m, d = g, h, k, m-k",
"F, monoms, polys = dmp_to_dict(f, u), [], [] for monom, coeff in F.iteritems():",
"]) dw = dup_degree(R[i+1]) if du % 2 and dv % 2: s",
"HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u, K)",
"_dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\"",
"(s, t, m) in enumerate(I_pos[i+1:]): while not (s >= v or t <=",
"return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f,",
"P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`.",
"K.zero,-K.one, x, y+dy, K) F = (F1, F2, F3, F4) x, y, dx,",
"dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else: return",
"K), v, K) f, g, m, d = g, h, k, m-k B.append(b)",
"g), cff = quo(f, h) and cfg = quo(g, h) The algorithm is",
"dx1, dy1, F1), k1) multiplicity = {} for (_, (x, y, dx, dy,",
"not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K) return",
"return res, R def dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials in",
"h: k = dup_degree(h) R.append(h) lc = dup_LC(g, K) if not d: q",
"h == [K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def",
"K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h,",
"def dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial in `K[x]`. \"\"\" if",
"the heuristic polynomial GCD, International Symposium on Symbolic and Algebraic Computation (ISSAC), ACM",
"sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed,",
"K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement not supported over %s\" %",
"\"\"\" if not u: return dup_trunc(f, p, K) v = u-1 return dmp_strip([",
"dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c, K(s), v, K) return",
"F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4,",
"K) if not d: q = c else: q = dmp_pow(c, d-1, v,",
"dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if",
"K) if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep,",
"complex root isolating rectangles for all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f,",
"roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast, K)) else: stack.append((a2, b2, c2,",
"Quadrant #3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx,",
"dx, dy, F, eps, K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K,",
"degree. Unlike factorization, complete functional decompositions of polynomials are not unique, consider examples:",
"dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt )",
"u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over a ring in",
"return (K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s, i",
"m, a, u, 0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean",
"(F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1 F32 =",
"dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u,",
"b, c, d), cond, fast, K)) continue f1 = dup_taylor(f, K.one, K) a1,",
"\"\"\" if K.has_Field or not K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f,",
"coeff in f: if coeff*prev < 0: k += 1 if coeff: prev",
"shift `f(x + a)` in `K[x]`. \"\"\" f, n = list(f), dup_degree(f) for",
"return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B",
"dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in",
"v+1, K)): return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g,",
"K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1",
"at `x_j = a_j, ...` in `K[X]`. \"\"\" if not A: return f",
"if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s, i, v = 1,",
"h = dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x, v, K) if",
"dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont for c in f[1:]: cont",
"`g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u,",
"u, K)): h = dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K)",
"field. \"\"\" if not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g,",
"q = K.one, K.one for b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1])",
"dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f`",
"d+1, v, K) c = dmp_ground(-K.one, v) B, D = [b], [d] if",
"i): if not n+j-i in f: continue if not s-j in g: continue",
"while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K)",
"**args): \"\"\"Refine real root's approximating interval to the given precision. \"\"\" if K.is_QQ:",
"x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`.",
"K): \"\"\"Compute resultant of `f` and `g` modulo a prime `p`. \"\"\" if",
"expected, got %s\" % (u, u, j)) return _rec_eval_in(f, a, u, 0, j,",
"if not K.has_Field: raise DomainError('computation can be done only in a field') a,",
"x2+dx2 <= x1) and (y2 >= y1+dy1 or y2+dy2 <= y1)): x1, y1,",
"composition `f(a*x)` in `K[x]`. \"\"\" f, n, b = list(f), dup_degree(f), a for",
"@cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a",
"= [e] d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K)",
"at `a` in `K[X]`. \"\"\" if j > u: raise IndexError(\"-%s <= j",
"v, K) D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K)",
"if bound is not None: return 1.0 / bound else: return None def",
"K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\")",
"pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes",
"= dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f,",
"m-k B.append(b) D.append(d) h = dup_prem(f, g, K) h = dup_exquo_ground(h, b, K)",
"dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a",
"dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont,",
"for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\")",
"K.zero, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for",
"dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y, dx, dy, (F1, F2, F3,",
"K, F), F, **args) else: roots = [] _, factors = dup_sqf_list(f, K)",
"gcd, u, K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) //",
"= dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u,",
"DomainError('computation can be done only in an algebraic domain') F, monoms, polys =",
"dup_trunc(D, p, K) return r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of",
"return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f if K.has_Field or not",
"K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if K1",
"F22, F23, F24, hx, hy, K) if k2 == 1: roots.append((x, cy, hx,",
"F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K)",
"if not f or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont,",
"number `c`. \"\"\" return [ dup_taylor(f, c, K) for f in F ]",
"= args.get('all', False) while True: d = dmp_diff(p, 1, u, K) h =",
"= ff // h cfg = gg // h h = _dup_zz_gcd_interpolate(h, x,",
"= args.get('eps'), args.get('fast') if eps is not None: cond = lambda a, b,",
"= dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0, u, K) while",
"s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive root isolation",
"u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if not u: return",
"K): return (dmp_LC(R[-1], K), R) s, i, v = 1, 1, u-1 p",
"F, K): \"\"\"One bisection step of complex root refinement algorithm. \"\"\" hx, hy",
"K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h,",
"a, u, K): \"\"\"Evaluate a polynomial at `x_0 = a` in `K[X]` using",
"over a ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g, K) result =",
"side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial",
"K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K):",
"h is not None: g = _dup_left_decompose(f, h, K) if g is not",
"def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued fractions approach. \"\"\" if",
"continue if K.is_one(P): r = R else: r = dmp_apply_pairs(r, R, _collins_crt, (P,",
"complex roots not supported over %s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero,",
"n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g,",
"1: return (x, cy, hx, hy, (F21, F22, F23, F24)) # Quadrant #3:",
"return sorted([ ((-v, -u), k) for (u, v, k) in I_neg ] +",
"], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial at",
"the given precision. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True),",
"def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p` in `K`.",
"((-v, -u), k) for (u, v, k) in I_neg ] + \\ [",
"gc, g = dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g,",
"else: return K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\"",
"f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate",
"240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return",
"dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over",
"a*f[j] return f def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n *",
"in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g",
"gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f",
"polynomial LCM over a ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u,",
"K) return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f`",
"`f(x)` returns the associated Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x)",
"`K[X]`. \"\"\" if not u: return dup_sqf_list(f, K, **args) if K.has_Field or not",
"g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u,",
"d, c+d i += 1 s, t = F(a, c), F(b, d) if",
"K) # Quadrant #1: ++ F11 = Fx F12 = _dup_sturm_shift(F2, hx, K)",
"None: for i, (x, y, dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f,",
"u, K): \"\"\"Square-free norm of `f` in `K[X]`, useful over algebraic domains. \"\"\"",
"_dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if",
"of coefficients over a ring. \"\"\" cont = K.zero for c in f:",
"u, K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[X]`. \"\"\"",
"`K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for c in f ],",
"K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a",
"n - m v = u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1,",
"multivariate content and a primitive polynomial. \"\"\" cont, v = dmp_content(f, u, K),",
"u, K) gc, g = dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u,",
"coeff, [] result, i = [], 1 h = dup_diff(f, 1, K) g,",
"0: continue a, Q = K.log(-f[i], 2), [] for j in xrange(i+1, n):",
"= [ dup_sign_variations([ dup_eval(f, K.zero, K) for f in F1 ], K), dup_sign_variations([",
"for i in xrange(n, 0, -1): for j in xrange(0, i): f[j+1] +=",
"sorted([ (-v, -u) for (u, v) in I_neg ] + I_pos) _, factors",
"in enumerate(roots): x1, y1, dx1, dy1, F1 = r1 for j, (f2, r2,",
"dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int,",
"0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`.",
"c return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at",
"< 0 or m < 0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K)",
"c = dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k,",
"f, [K.one], [] else: return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f,",
"elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f,",
"for b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i",
"+= 1 if coeff: prev = coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute",
"by evaluating polynomials f and g at certain points and computing (fast) integer",
"K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4 ], K), ] return",
"= [u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return",
"1: raise RefinementFailed(\"there should be exactly one root on (%s, %s)\" % (s,",
"h = dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s,",
"u - len(A) + 1: return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\")",
"K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one,",
"dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n =",
"gives cofactors as a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation",
"= dup_inner_gcd(p, h, K) if all or dup_degree(g) > 0: result.append((g, i)) i",
"dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]): h = dup_mul(h,",
"dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if len(g) <=",
"y + hy F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one,",
"dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K)",
"- 1 n = dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f,",
"_dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm sequence at its origin. \"\"\"",
"modular resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g,",
"# Quadrant #3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 =",
"p, p) v = u - 1 n = dmp_degree(f, u) m =",
"hy, K) if k3 == 1: return (x, y, hx, hy, (F31, F32,",
"dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes",
"c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\")",
"k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 == 1:",
"K) return h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)`",
"o x**n` 3. `T_n o T_m = T_m o T_n` where `T_n` and",
"of complex roots not supported over %s\" % K) F1 = _dup_inner_sturm(f, K.one,",
"DomainError(\"isolation of complex roots not supported over %s\" % K) F1 = _dup_inner_sturm(f,",
"a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True else: return",
"for i in xrange(1, s): coeff = K.zero for j in xrange(0, i):",
"v, K) for cg in g ] return [h], cff, cfg def dup_rr_prs_gcd(f,",
"dv % 2: s = -s lc, i = dmp_LC(R[i], K), i+1 p",
"if i < u - len(A) + 1: return h else: return dup_eval(h,",
"= dmp_LC(f, K), u-1 for coeff in f[1:]: result = dmp_mul_ground(result, a, v,",
"K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1)",
"= [ dmp_exquo(ch, b, v, K) for ch in h ] return R,",
"Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if",
"= f(x + b) o (g - b)` 2. `x**n o x**m =",
"of complex root refinement algorithm. \"\"\" hx, hy = dx/2, dy/2 cx, cy",
"\"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of complex",
"B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two polynomials in",
"not args.get('include', False): return coeff, result else: (g, i), rest = result[0], result[1:]",
"u, K): \"\"\"Returns multivariate content and a primitive polynomial. \"\"\" cont, v =",
"h = dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f, h, K) all",
"u): h = dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg =",
"K) f, g = g, r a, b = b, dup_sub_mul(a, q, b,",
"dup_LC(f, K), K) f = dup_monic(f, K) return a, f def dup_gcdex(f, g,",
"s): coeff = K.zero for j in xrange(0, i): if not n+j-i in",
"+- F41 = _dup_sturm_shift(F1, hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx,",
"F12 = _dup_sturm_shift(F2, hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K),",
"K.float_domain() f = dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex roots not",
"return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of",
"is not None: return 1.0 / bound else: return None def dup_inner_refine_real_root(f, (a,",
"for f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in",
"(s >= v or t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v,",
"all or dmp_degree(g, u) > 0: result.append((g, i)) i += 1 if not",
"R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P",
"(a, b, c, d), cond, fast, K)] else: roots, stack = [], [(a,",
"dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate, dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject,",
"y, dx, dy, F, K): \"\"\"One bisection step of complex root refinement algorithm.",
"F3, F4)) while stack: x, y, dx, dy, k, F1, F2, F3, F4",
"return (-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K):",
"gcd, u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K)",
"u-1 for c in f: gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont,",
"ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g,",
"[], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else:",
"@cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\"",
"def _rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j:",
"c1, d1), cond, fast, K)) else: stack.append((a1, b1, c1, d1, f1, k1)) if",
"dmp_pow(lc, dv*(1+d), v, K), v, K) _, p, q = dmp_inner_gcd(p, q, v,",
"v, K), v, K), dmp_pow(lc, du-dw, v, K), v, K) q = dmp_mul(q,",
"dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2, y2, dx2, dy2, F2 =",
"\"\"\" if j > u: raise IndexError(\"-%s <= j < %s expected, got",
"0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two polynomials in",
"and `g` in `Z[x]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff`",
"e, v, K), v, K) r = dmp_add(r, c, v, K) r =",
">= K.one: f = dup_taylor(f, A, K) b, d = A*a + b,",
"return (x, cy, hx, hy, (F21, F22, F23, F24)) # Quadrant #3: --",
"c1, d1 = a, a+b, c, c+d if not dup_eval(f, K.zero, K): return",
"Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result",
"dup_mul_ground(g, coeff, K) return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K,",
"root using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K",
"= u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff,",
"\\ [ (( u, v), k) for (u, v) in I_pos ]) I_pos,",
"None: return 1.0 / bound else: return None def dup_inner_refine_real_root(f, (a, b, c,",
"\"\"\"Refine a positive root of `f` given a Mobius transform. \"\"\" F, i",
"w = v-1 for c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0,",
"if k3 == 1: return (x, y, hx, hy, (F31, F32, F33, F34))",
"break x, y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack =",
"P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound",
"1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return [] h =",
"K)[1] cff_, r = dup_div(f, h, K) if not r: cfg_, r =",
"eps, fast = args.get('eps'), args.get('fast') if eps is not None: cond = lambda",
"= dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c,",
"i)) i += 1 if not args.get('include', False): return coeff, result else: (g,",
"s, t = dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative: return (-t,",
"return f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) gcd =",
"g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h,",
"(( u, v), k) for (u, v) in I_pos ]) I_pos, I_neg =",
"F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 =",
"g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg,",
"f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) and `f_2,",
"du % 2 and dv % 2: s = -s lc, i =",
"return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is",
"g = f(x + b) o (g - b)` 2. `x**n o x**m",
"o g = f(x + b) o (g - b)` 2. `x**n o",
"F14, hx, hy, K) if k1 == 1: roots.append((cx, cy, hx, hy, (F11,",
"== _max: upper.append((x, y, dx, dy)) del group[i] break _min = min([ r[1]",
"= dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K)",
"def dup_diff(f, m, K): \"\"\"m-th order derivative of a polynomial in `K[x]`. \"\"\"",
"K) h = [ dmp_exquo(ch, b, v, K) for ch in h ]",
"-rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and",
"K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is a",
"K) if not a: return dmp_TC(f, K) result, v = dmp_LC(f, K), u-1",
"h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1,",
"in `x_j` at `a` in `K[X]`. \"\"\" if j > u: raise IndexError(\"-%s",
"if s <= t: return (s, t) else: return (t, s) def dup_outer_refine_real_root(f,",
"F.denom(s) b, d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]),",
"step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1]",
"xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]): h =",
"K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part",
"\"\"\"Differentiate and evaluate a polynomial in `x_j` at `a` in `K[X]`. \"\"\" if",
"`x_0` from GCD computation in `K[X]`. \"\"\" df = dmp_degree(f, u) dg =",
"K.zero, K.one k = dup_sign_variations(f, K) if k == 0: return [] if",
"K)) continue f1 = dup_taylor(f, K.one, K) a1, b1, c1, d1, r =",
"try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else:",
"= K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u,",
"K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff,",
"dy, F, eps, K): \"\"\"Refine a complex root until the desired precision is",
"in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K)",
"if fast and A > 16: f = dup_scale(f, A, K) a, c,",
"t)) fast = args.get('fast') if type(n) is not int: cond = lambda a,",
"h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x = 73794*x",
"K1) h = dup_convert(h, K1, K0) c = dup_LC(h, K0) h = dup_monic(h,",
"return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given",
"F = K.get_field() a, c = F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t)",
"K) cfg = dmp_exquo(g, h, u, K) return h, cff, cfg @cythonized(\"u\") def",
"g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K)",
"_dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a ring.",
"v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of",
"else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i,",
"RefinementFailed(\"there should be exactly one root on (%s, %s)\" % (s, t)) return",
"y, dx, dy)] = k roots = multiplicity.keys() groups = {} for (x,",
"n = dmp_degree(f, u) m = dmp_degree(g, u) if n < 0 or",
"K.one, K.one while P <= B: p = K(nextprime(p)) while not (a %",
"= dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff = dup_exquo(f, h, K)",
"f, s, t, negative = dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't",
"F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero,",
"= _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if k != n: return",
"dense recursive polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip,",
"m-k B.append(b) D.append(d) h = dmp_prem(f, g, u, K) h = [ dmp_exquo(ch,",
"not s-j in g: continue fc, gc = f[n+j-i], g[s-j] coeff += (i",
"K) gg = dup_eval(g, x, K) if ff and gg: h = K.gcd(ff,",
"K), -t, -s, True else: raise ValueError(\"can't refine a real root on (%s,",
"algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _",
"to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0, K1) if K1 is",
"F1), k1) multiplicity = {} for (_, (x, y, dx, dy, _), k)",
"HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result",
"fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i] = (u, v, k) return",
"n < m: return [] deriv, c = [], K.one for i in",
"= sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda r: r[0]) if not",
"u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K))",
"roots not supported over %s\" % K) squarefree = args.get('sqf', False) if squarefree:",
"dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f` in `F[x]`. Given an univariate,",
"F(b1, d1) k = dup_sign_variations(f, K) if k == 1: a, b, c,",
"= dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K),",
"( cythonized, variations ) from random import random as randfloat def dup_ground_to_ring(f, K0,",
"K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f,",
"return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if",
"return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f, s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc =",
"not d: q = c else: q = c**(d-1) c = K.exquo((-lc)**d, q)",
"K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff = dmp_mul_ground(cff, K0.quo(c, cf),",
"hy, K) if k1 == 1: roots.append((cx, cy, hx, hy, (F11, F12, F13,",
"c2, d2 = b, a+b, d, c+d if k2 > 1 or (k1",
"return None else: g[i] = dup_LC(r, K) f, i = q, i +",
"is recovered from the integer image by interpolation. The evaluation proces reduces f",
"dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x",
"if K.is_ZZ: g = [] for c in f: c = c %",
"@cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative in `x_j` of",
"or y2+dy2 <= y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1,",
"D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1),",
"= dup_degree(g) if n < m: f, g = g, f n, m",
"-s, True else: raise ValueError(\"can't refine a real root on (%s, %s)\" %",
"p // 2: g.append(c - p) else: g.append(c) else: g = [ c",
"dv % 2: s = -s lc, i = dup_LC(R[i], K), i+1 p",
"u, K), s+1 return s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part",
"g, u, K0) if result is not None: return result K1 = K0.get_ring()",
"<NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms for Algebraic Computation, Academic Press,",
"dmp_zero_p(h, v): g = dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h,",
"c2, d2), cond, fast, K)) else: stack.append((a2, b2, c2, d2, f2, k2)) return",
"_dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result df =",
"if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u,",
"D.append(d) h = dup_prem(f, g, K) h = dup_exquo_ground(h, b, K) return R,",
"hx, hy, K): \"\"\"Return the exact number of zeros in the given rectangle.",
") from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory",
"F12, F13, F14, hx, hy, K) if k1 == 1: return (cx, cy,",
"algorithm over a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u)",
"dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be exactly one root on (%s,",
"<= j < %s expected, got %s\" % (u, u, j)) return _rec_diff_in(f,",
"`K[X]`. \"\"\" if not u: return dup_discriminant(f, K) d, v = dmp_degree(f, u),",
"= [f, g] d = n - m v = u - 1",
"K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K):",
"K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m, v, K) w, i",
"if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u,",
"dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1, K) k",
"h = dup_monic(h, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h,",
"dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors import (",
"]) def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm sequence at x+I*y",
"= _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K)",
"`K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial",
"K, **args) if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f",
"K.one, K) if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a,",
"**args): \"\"\"Isolate real roots using continued fractions approach. \"\"\" if K.is_QQ: (_, f),",
"-s) else: return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute",
"else: g = [ c % p for c in f ] return",
"K0) return h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial",
"K)): return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K):",
"@cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial at `x_j =",
"dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf = dmp_exquo(f, gcd, u, K)",
"dmp_integrate(g, m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m,",
"f h = [f[0]] for c in f[1:]: h = dmp_mul(h, g, u,",
"algorithm over a field. \"\"\" if not (f or g): return [], [],",
"g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif",
"dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f,",
"dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K)",
"m, n R = [f, g] d = n - m b =",
"not u: return dup_ground_to_ring(f, K0, K1) if K1 is None: K1 = K0.get_ring()",
"K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] = (s,",
"B = n*M + m*N D, a = [K.one], -K.one r = dmp_zero(v)",
"= g, f n, m = m, n R = [f, g] d",
"if not v: for c in g: common = K1.lcm(common, K0.denom(c)) else: w",
"m): c, n = c*K(n), n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff,",
"return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns",
"K) h = dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h, u): k",
"g = g, f n, m = m, n R = [f, g]",
"= dup_sign_variations(f2, K) if k1 < k2: a1, a2, b1, b2 = a2,",
"cfg = quo(g, h) The algorithm is purely heuristic which means it may",
"and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return",
"u: return dup_monic(f, K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u,",
"y) f = dup_convert(f, K, C) f = dup_taylor(f, b, C) f =",
"dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom):",
"i, F: i >= 1 for i, (u, v, k) in enumerate(I_pos): for",
"K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f",
"dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g step",
"content and a primitive polynomial in `K[x]`. \"\"\" if not u: return dup_primitive(f,",
"= F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4",
"\"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for f in F1 ],",
"u, j)) return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m,",
"= 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _ = dmp_inject(f, 0,",
"K.dom) if dmp_sqf_p(r, u, K.dom): break else: f, s = dmp_compose(f, F, u,",
"= -coeff if dmp_degree(f, u) <= 0: if args.get('include', False): return f else:",
"is not None: return result fc, F = dmp_primitive(f, u, K) gc, G",
"c in f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K):",
"raise DomainError('computation can be done only in a field') f = dup_sqf_part(f, K)",
"= dup_strip([ C.real(c) for c in f ]) v = dup_strip([ C.imag(c) for",
"f, k = stack.pop() A = dup_root_lower_bound(f, K) if A is not None:",
"u-1, K1, K0) c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1,",
"x1, y1, dx1, dy1, F1 = r1 for j, (f2, r2, k2) in",
"\"\"\"Computes the Sturm sequence of `f` in `F[x]`. Given an univariate, square-free polynomial",
"= x**m o x**n` 3. `T_n o T_m = T_m o T_n` where",
"not f or not g: return R, B, D h = dup_prem(f, g,",
"gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\"",
"to eliminate `x_0` from GCD computation in `K[X]`. \"\"\" df = dmp_degree(f, u)",
"[] for monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1,",
"u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u),",
"interpolation. The evaluation proces reduces f and g variable by variable into a",
"a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic",
"if type(n) is not int: cond = lambda a, b, c, d, i,",
"K) if not r: cff_, r = dup_div(f, h, K) if not r:",
"y, dx, dy, F, eps, K): \"\"\"Refine a complex root until the desired",
"else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in",
"b, a+b, d, c+d if k2 > 1 or (k1 > 0 and",
"[f[0]] for c in f[1:]: h = dmp_mul(h, g, u, K) h =",
"h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h,",
"[], [] elif not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not",
"over algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\")",
"u, K): \"\"\"Computes polynomial LCM over a field in `K[X]`. \"\"\" h =",
"C.imag(c) for c in f ]) seq = [u, v] while seq[-1]: s",
"240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g,",
"cont = K.gcd(cont, gc) if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u,",
"if df == 0 or dg == 0: return [gcd], f, g f_norm",
"K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n, a = list(f),",
"in groups.values(): while len(group) > 1: _max = max([ r[1] for r in",
"i, F): A = dup_root_lower_bound(f, K) if A is not None: A =",
"abs(F(a, c) - F(b, d)) < n else: cond = lambda a, b,",
"fractions approach. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring()",
"r in enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r in enumerate(lower): lower[i]",
"K) != 1: raise RefinementFailed(\"there should be exactly one root on (%s, %s)\"",
"dup_extract(f, g, K): \"\"\"Extracts common content from a pair of polynomials in `K[x]`.",
"> 1: stack.append((x, cy, hx, hy, k2, F21, F22, F23, F24)) # Quadrant",
"return dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)):",
"return dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u,",
"g): return [], [], [] elif not f: return dup_monic(g, K), [], [dup_LC(g,",
"return [] h, Q = [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1],",
"= args.get('fast') if type(n) is not int: cond = lambda a, b, c,",
"(x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K):",
"if k1 == 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1,",
"= b*f[i], b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift",
"n R = [f, g] d = n - m v = u",
"= _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result fc,",
"@cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\"",
"= dmp_ground(-K.one, v) B, D = [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g,",
"over %s\" % K) if dup_degree(f) <= 0: return [] eps, fast =",
"dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd):",
"K) def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real root's approximating interval",
"= c else: q = c**(d-1) c = K.exquo((-lc)**d, q) b = -lc",
"in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g,",
"K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0) cfg",
"K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f",
"k roots = multiplicity.keys() groups = {} for (x, y, dx, dy) in",
"= _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u,",
"u, K) if K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f, cont, u,",
"v, k) return sorted([ ((-v, -u), k) for (u, v, k) in I_neg",
"c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a",
"i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g",
"True: d = dmp_diff(p, 1, u, K) h = dmp_sub(q, d, u, K)",
"not f: return f lc = dup_LC(f, K) if K.is_one(lc): return f else:",
"h, K) cfg = dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\") def",
"algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [], [] for monom, coeff",
"not None: cond = lambda a, b, c, d, i, F: abs(F(a, c)",
"h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using",
"u: return dup_lcm(f, g, K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g,",
"u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f else: return",
"if dup_LC(f, K) < 0: f = dup_neg(f, K) f = list(reversed(f)) for",
"K), dup_sign_variations([ dup_eval(f, hy, K) for f in F4 ], K), ] V0",
"F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if",
"a, b, c, d, i, F: True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f,",
"if m <= 0: return f n = dmp_degree(f, u) if n <",
"[K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B: while True: a +=",
"if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g,",
"divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n",
"K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] = (s,",
"D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1],",
"// abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i",
"\"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM",
"% (u, u, j)) return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def",
"dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" cont = K.zero",
"return h def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\"",
"eps else: cond = lambda a, b, c, d, i, F: True if",
"<= j < %s expected, got %s\" % (u, u, j)) if not",
"K.is_nonnegative(dup_LC(f, K)): return f, [K.one], [] else: return dup_neg(f, K), [-K.one], [] return",
"result is not None: return result fc, F = dmp_primitive(f, u, K) gc,",
"u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if",
"= dmp_one(v, K) for b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u)",
"_dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant #1: ++ F11 = Fx",
"c = dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff, K1, K0)",
"= _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff, u, K) if",
"K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if K1 is",
"dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in g ], v)",
"dup_LC(f, K) if K.is_one(lc): return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\") def",
"j, u, K): \"\"\"Differentiate and evaluate a polynomial in `x_j` at `a` in",
"and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\")",
"def dup_extract(f, g, K): \"\"\"Extracts common content from a pair of polynomials in",
"[] result, i = [], 1 h = dmp_diff(f, 1, u, K) g,",
"result = _dup_ff_trivial_gcd(f, g, K) if result is not None: return result h",
"return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j,",
"<= 0: return [] eps, fast = args.get('eps'), args.get('fast') if eps is not",
"= dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K)",
"dmp_diff(p, 1, u, K) h = dmp_sub(q, d, u, K) if dmp_zero_p(h, u):",
"roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1, 1, K), 1 k1 =",
"dup_mul_ground(g, coeff, K) return [(g, i)] + rest def dup_extract(f, g, K): \"\"\"Extracts",
"dup_scale(f, A, K) a, c, A = A*a, A*c, K.one if A >=",
"dmp_neg(g, u, K), dmp_zero(u), dmp_ground(-K.one, u) elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return",
"F22 = Fy F23 = _dup_sturm_shift(F3, hx, K) F24 = F4 k2 =",
"= multiplicity.keys() groups = {} for (x, y, dx, dy) in roots: if",
"return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a",
"not K.is_ZZ: raise DomainError(\"isolation of real roots not supported over %s\" % K)",
"% K) if dup_degree(f) <= 0: return [] eps, fast = args.get('eps'), args.get('fast')",
"else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a",
"F22, F23, F24))) elif k2 > 1: stack.append((x, cy, hx, hy, k2, F21,",
"f = dup_mul_ground(f, common, K0) if not args.get('convert'): return common, f else: return",
"cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if",
"stack.append((a1, b1, c1, d1, f1, k1)) if k2 == 0: continue if k2",
"c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1",
"\"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while not dmp_zero_p(h,",
"g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g,",
"`K[X]`. \"\"\" if not u: return dup_diff(f, m, K) if m <= 0:",
"u, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if not f:",
"v), k) for (u, v) in I_pos ]) I_pos, I_neg = [], []",
"result.append((p, i)) break g, p, q = dup_inner_gcd(p, h, K) if all or",
"cond, fast, K) def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real root's",
"j, u, K): \"\"\"m-th order derivative in `x_j` of a polynomial in `K[X]`.",
"supported over %s\" % K) squarefree = args.get('sqf', False) if squarefree: roots =",
"2: s = -s lc, i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p,",
"LCM over a ring in `K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc,",
"= dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a, v, K) if",
"d-1, v, K) c = dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v,",
"n // s for i in xrange(1, s): coeff = K.zero for j",
"g, u, K) if result is not None: return result fc, F =",
"dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's global bisection",
"of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return",
"c, 0, u, K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g,",
"if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f,",
"return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo",
"< 0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0,",
"K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g,",
"= dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h,",
"+ d if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f =",
"dx1, dy1, F1 = r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2,",
"positive root isolation intervals. \"\"\" a, b, c, d = K.one, K.zero, K.zero,",
"= dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v,",
"\"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS",
"return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K,",
"= -coeff if dup_degree(f) <= 0: if args.get('include', False): return f else: return",
"cy, hx, hy, (F11, F12, F13, F14))) elif k1 > 1: stack.append((cx, cy,",
"coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K):",
"r = randfloat() if r < 0.5: break x, y, dx, dy =",
"u: return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f,",
"primitive polynomial over a ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f else:",
"bound for `f`'s positive roots. \"\"\" n, t, P = len(f), K.one, []",
"dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases",
"y2, dx2, dy2, F2), k2) roots[i] = (f1, (x1, y1, dx1, dy1, F1),",
"K) v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j,",
"cff, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K)",
"dg > 0: return None if not (df or dg): F = dmp_LC(f,",
"K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f, g,",
"d = dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0, K) c =",
"@cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2, df):",
"and `f_2, ..., f_n` are monic and homogeneous polynomials of at least second",
"s = dmp_compose(f, F, u, K), s+1 return s, f, r def dup_sqf_part(f,",
"def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h =",
"coefficients to integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can be",
"@cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate",
"a primitive polynomial. \"\"\" cont, v = dmp_content(f, u, K), u-1 if dmp_zero_p(f,",
"K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over",
"hy, K) if k1 == 1: return (cx, cy, hx, hy, (F11, F12,",
"K.is_ZZ: raise DomainError(\"isolation of real roots not supported over %s\" % K) if",
"f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)` in",
"= _dup_sturm_shift(F1, hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K)",
"g, u, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" if",
"not unique, consider examples: 1. `f o g = f(x + b) o",
"dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c = dup_LC(h, K0) h",
"K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K)",
"LCM of `f` and `g` in `K[X]`. \"\"\" if not u: return dup_lcm(f,",
"n, K, **args): \"\"\"Refine real root's approximating interval to the given precision. \"\"\"",
"\"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result is not None: return result",
"if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd,",
"K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K)",
"functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if not f: return []",
"% K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f,",
"h, 1, K.dom) if dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f, -K.unit,",
"elif zero_g: if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return",
"u, K0, K1) cg, g = dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f,",
"decompositions of polynomials are not unique, consider examples: 1. `f o g =",
"\"\"\" if not u: return dup_monic(f, K) if dmp_zero_p(f, u): return f lc",
"= dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u), k) for (u, v)",
"u, K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u,",
"sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n =",
"g = dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u, K0, K1) g",
"F23, F24, hx, hy, K) if k2 == 1: roots.append((x, cy, hx, hy,",
"in I_neg ] + I_pos) _, factors = dup_sqf_list(f, K) if len(factors) ==",
"verify if the interpolated polynomial is the correct GCD. This gives cofactors of",
"coeff = dup_LC(f, K) f = dup_monic(f, K) else: coeff, f = dup_primitive(f,",
"f n, m = m, n R = [f, g] d = n",
"v = K.zero, u-1 for c in f: gc = dmp_rr_ground_content(c, v, K)",
"subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is",
"= dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M",
"* K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K):",
"dg = dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm",
"u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if",
"0, u, K) while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc",
"f in F ] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return",
"def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial at `x_j = a`",
"deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if",
"= dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) cff =",
"dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u):",
"dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d,",
"return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {},",
"G = dmp_LC(g, K) v = u - 1 h = dmp_gcd(F, G,",
"f[j] <= 0: continue q = t + a - K.log(f[j], 2) Q.append(q",
"= c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)),",
"K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD",
"f, s = dup_taylor(f, -K.unit, K), s+1 return s, f, r @cythonized(\"s,u\") def",
"\"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in",
"not u: return dup_eval(f, a, K) if not a: return dmp_TC(f, K) result,",
"g, K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" if",
"K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u) m",
"F43, F44, hx, hy, K) if k4 == 1: return (cx, y, hx,",
"K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u,",
"\"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n, b = list(f), dup_degree(f),",
"f, g, m, d = g, h, k, m-k B.append(b) D.append(d) h =",
"K): \"\"\"Return the exact number of zeros in the given rectangle. \"\"\" V1",
"F12, F13, F14, hx, hy, K) if k1 == 1: roots.append((cx, cy, hx,",
"k2 > 1: stack.append((x, cy, hx, hy, k2, F21, F22, F23, F24)) #",
"F1, K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1,",
"common content from a pair of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f,",
"x1) and (y2 >= y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1, dy1,",
"negative: return (-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast,",
"y, hx, hy, (F31, F32, F33, F34))) elif k3 > 1: stack.append((x, y,",
"square-free decomposition of a polynomial in `K[X]`. \"\"\" if not u: return dup_sqf_list(f,",
"field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result is not None: return",
"repetition=True) for perm in perms: G = dict(F) for sign, monom in zip(perm,",
"\"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K)",
"negative = dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't refine a real",
"K): \"\"\"Flip the direction of a Sturm sequence at its origin. \"\"\" return",
"Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p,",
"m, K) if m <= 0: return f n = dmp_degree(f, u) if",
"gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf = dmp_exquo(f, gcd,",
"= F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f,",
"<= y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1,",
"a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(dmp_diff(g, m,",
"f: q, r = dup_div(f, h, K) if dup_degree(r) > 0: return None",
"u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result",
"dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf",
"seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm",
"dup_LC(f, K) f = dup_monic(f, K) else: coeff, f = dup_primitive(f, K) if",
"args.get('fast') if eps is not None: cond = lambda a, b, c, d,",
"= dup_taylor(f, K.one, K), f a1, b1, c1, d1 = a, a+b, c,",
"K)[-1] h = dup_monic(h, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g,",
"]) I_pos, I_neg = [], [] F_pos, F_neg = {}, {} for f,",
"if not f: return f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd",
"lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return dmp_quo_ground(f, lc,",
"hy, (F41, F42, F43, F44))) elif k4 > 1: stack.append((cx, y, hx, hy,",
"t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s,",
"\"\"\" if m <= 0 or not f: return f g = [K.zero]*m",
"can be done only in a field') a, b = [K.one], [] while",
"dy/2 cx, cy = x + hx, y + hy F1, F2, F3,",
"V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for f in F1 ], K),",
"0: return (K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s,",
"\"\"\"Extracts common content from a pair of polynomials in `K[x]`. \"\"\" fc =",
"over a ring. \"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont,",
"square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True else: return not",
"f def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in",
"g, u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\" if not",
"K.gcd(ff, gg) cff = ff // h cfg = gg // h h",
"over a ring. \"\"\" cont = dup_content(f, K) if not f or K.is_one(cont):",
"h = dup_exquo_ground(h, b, K) return R, B, D def dup_subresultants(f, g, K):",
"a polynomial at `x = a` in `K[x]` using Horner scheme. \"\"\" if",
"K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral",
"(x, y, dx, dy) in enumerate(group): if y == _max: upper.append((x, y, dx,",
"F2, K) roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2), k2) roots[i] =",
"x, v, K) h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u):",
"dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a positive root of `f` given",
"j in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\")",
"\"\"\" if not u: return dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact:",
"f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A,",
"in `K[X]`. \"\"\" if not u: return dup_discriminant(f, K) d, v = dmp_degree(f,",
">= eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy,",
"DomainError ) from sympy.ntheory import nextprime from sympy.utilities import ( cythonized, variations )",
"the Sturm sequence of `f` in `F[x]`. Given an univariate, square-free polynomial `f(x)`",
"result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g",
"_dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 == 1: return (cx,",
"[f, g] d = n - m v = u - 1 b",
"K) return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in",
"dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if not",
"u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while",
"dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du % 2 and dv % 2:",
"return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g, u,",
"q = dmp_inner_gcd(p, q, v, K) if s < 0: p = dmp_neg(p,",
"g] d = n - m v = u - 1 b =",
"g -= x f.insert(0, g) h = (h-g) // x return f @cythonized(\"i,df,dg\")",
"dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow,",
"= F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2",
"\"\"\" if not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f",
"> 1: stack.append((x, y, dx, dy, k, F1, F2, F3, F4)) while stack:",
"K) c = dmp_ground(-K.one, v) B, D = [b], [d] if dmp_zero_p(f, u)",
"h, r = dup_div(g, cfg, K) if not r: cff_, r = dup_div(f,",
"else: R = [R] e = [e] d = K.invert(dup_eval(D, a, K), p)",
"v, K) r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v,",
"K), K)]) if not f: return [] h = [f[0]] for c in",
"else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed:",
"u: return dup_diff(f, m, K) if m <= 0: return f n =",
"in `K[x]` using Horner scheme. \"\"\" if not a: return dup_TC(f, K) result",
"> 1: _max = max([ r[1] for r in group ]) for i,",
"d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u)",
"K) if k1 < k2: a1, a2, b1, b2 = a2, a1, b2,",
"o T_n` where `T_n` and `T_m` are Chebyshev polynomials. References ========== .. [Kozen89]",
"polynomial in `K[X]`. \"\"\" if not u: return dup_sqf_list(f, K, **args) if K.has_Field",
"args.get('all', False) while True: d = dup_diff(p, 1, K) h = dup_sub(q, d,",
"= _dup_decompose(f, K) if result is not None: f, h = result F",
"= dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du % 2",
"D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two polynomials in `K[x]`.",
"polynomial over a ring. \"\"\" cont = dmp_ground_content(f, u, K) if K.is_one(cont): return",
"dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f, h, K) all = args.get('all',",
"hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3",
"This gives cofactors as a side effect. References ========== .. [Liao95] <NAME>, <NAME>,",
"K, front=True) r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break",
"dmp_diff(f, m, u, K): \"\"\"m-th order derivative in `x_0` of a polynomial in",
"a1, b1, c1, d1 = a, a+b, c, c+d if not dup_eval(f, K.zero,",
"_dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0` from GCD computation in `K[X]`.",
"groups.values(): while len(group) > 1: _max = max([ r[1] for r in group",
"result fc, F = dup_primitive(f, K) gc, G = dup_primitive(g, K) c =",
"k3 == 1: roots.append((x, y, hx, hy, (F31, F32, F33, F34))) elif k3",
"raise DomainError(\"ground domain must be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0,",
"K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if k1 <",
"= _dup_ff_trivial_gcd(f, g, K0) if result is not None: return result K1 =",
"u, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" if not",
"= (r, multiplicity[r]) for i, r in enumerate(lower): lower[i] = (r, multiplicity[r]) return",
"= args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else:",
"c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) r = dmp_add(r, c,",
"def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return",
"dmp_zero(u-1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a =",
"1: roots.append((cx, y, hx, hy, (F41, F42, F43, F44))) elif k4 > 1:",
"g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result is not None:",
"sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K),",
"= dup_primitive(f, K) gc, g = dup_primitive(g, K) c = K.lcm(fc, gc) h",
"K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2,",
"dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i] =",
"while P <= B: p = K(nextprime(p)) while not (a % p) or",
"dup_monic(f, K) else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f =",
"x, K) h, r = dup_div(g, cfg, K) if not r: cff_, r",
"K) q = dup_mul_ground(q, c, K) h = dup_add(h, q, K) return h",
"reached. \"\"\" while dx >= eps and dy >= eps: x, y, dx,",
"[dup_LC(f, K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g,",
"D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero, R) if",
"_dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K)",
"m < 0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g,",
"in f: if coeff*prev < 0: k += 1 if coeff: prev =",
"or not K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f, K) else: coeff,",
"K1) cg, g = dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u, K0,",
"r = dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m * cg**n, K1) return",
"h = (h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic",
"import ( cythonized, variations ) from random import random as randfloat def dup_ground_to_ring(f,",
"def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n,",
"K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass",
"for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors) > 1:",
"\"\"\"Computes polynomial LCM over a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g,",
"\"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2, df): if df % s",
"c in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate",
"`p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v",
"xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\")",
"in `K[X]`. \"\"\" if not u: return dup_monic(f, K) if dmp_zero_p(f, u): return",
"u, K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if",
"f = dup_taylor(f, A, K) b, d = A*a + b, A*c +",
"elif k1 > 1: stack.append((cx, cy, hx, hy, k1, F11, F12, F13, F14))",
"\"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if not u: return dup_content(f, K)",
"g, u, K): \"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\" if not",
"= dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c",
"heuristic polynomial GCD, International Symposium on Symbolic and Algebraic Computation (ISSAC), ACM Press,",
"h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K)",
"Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247",
"x, u, K) v = u - 1 if not (dmp_zero_p(ff, v) or",
"if h is not None: g = _dup_left_decompose(f, h, K) if g is",
"GCD algorithm over a field. \"\"\" if not (f or g): return [],",
"y, dx, dy) in roots: if x in groups: groups[x].append((x, y, dx, dy))",
"= dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f, u) <= 0: if",
"done only in a field') f = dup_sqf_part(f, K) sturm = [f, dup_diff(f,",
"K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f,",
"g, u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f,",
"y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1,",
"of zeros in the given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx,",
"pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f,",
"not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if",
"h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f,",
"not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s, g = 0, dmp_raise(K.mod.rep,",
"j)) return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate",
"K) f = dup_to_raw_dict(f) g = { s : K.one } r =",
"if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm in",
"lambda a, b, c, d, i, F: abs(F(a, c) - F(b, d)) <",
"x if g > x // 2: g -= x f.insert(0, g) h",
"polynomial `f` with coefficients in a field of characteristic zero, returns tuple `(f_1,",
"_rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g,",
"u, K) cfg = dmp_exquo(g, h, u, K) return h, cff, cfg @cythonized(\"u\")",
"g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not u: return",
"= K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K) d = dmp_raise(d,",
"\"\"\" if K.is_ZZ: g = [] for c in f: c = c",
"if ff and gg: h = K.gcd(ff, gg) cff = ff // h",
"u) if n < m: f, g = g, f n, m =",
"F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23",
"K) e = dmp_eval(r, a, v, K) if not v: R = dup_strip([R])",
"@cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p`",
"dv, v, K), v, K), dmp_pow(lc, du-dw, v, K), v, K) q =",
"algorithm in `K[x]` using subresultant PRS. \"\"\" if not f or not g:",
"b2, c2, d2 = b, a+b, d, c+d if k2 > 1 or",
"while not ((x2 >= x1+dx1 or x2+dx2 <= x1) and (y2 >= y1+dy1",
"u, K) g = dmp_exquo_ground(g, gcd, u, K) return gcd, f, g def",
"not r: cfg_, r = dup_div(g, h, K) if not r: h =",
"in xrange(1, s): coeff = K.zero for j in xrange(0, i): if not",
"dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f,",
"@cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\"",
"GCD of coefficients over a ring. \"\"\" cont = K.zero for c in",
"7 (1989), pp. 445-456 \"\"\" F = [] while True: result = _dup_decompose(f,",
"dmp_content(g, u, K) else: F = dmp_content(f, u, K) G = dmp_LC(g, K)",
"d1, r = a, a+b, c, c+d, 0 if not dup_eval(f1, K.zero, K):",
"ff and gg: h = K.gcd(ff, gg) cff = ff // h cfg",
"d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f",
"dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h,",
"dg = dup_degree(g) gcd, f, g = dup_extract(f, g, K) if df ==",
"K): return F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K) if k ==",
"73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v,",
"========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation 7",
"variations ) from random import random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args):",
"= dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R)",
"s < 0: if t <= 0: f, s, t, negative = dup_mirror(f,",
"K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def",
"= list(f), dup_degree(f), -K.one for i in xrange(n-1, -1, -1): f[i], a =",
"cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a ring.",
"= dup_rshift(f, 1, K) a, b, c, d = b, a+b, d, c+d",
"h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over",
"Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K = K,",
"K) cfg = dmp_exquo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX =",
"1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1]",
"K.one if A >= K.one: f = dup_taylor(f, A, K) b, d =",
"= dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r =",
"dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if not r: cfg_, r",
"p, u, K): \"\"\"Compute resultant of `f` and `g` modulo a prime `p`.",
"v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g = dup_mirror(f, K)",
"if args.get('include', False): return f else: return coeff, [] result, i = [],",
"dup_degree(f) <= 0: return [] eps, fast = args.get('eps'), args.get('fast') if eps is",
"F13, F14, hx, hy, K) if k1 == 1: return (cx, cy, hx,",
"if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if",
"t += 1 if not Q: continue P.append(min(Q)) if not P: return None",
"hx, hy, K) if k1 == 1: return (cx, cy, hx, hy, (F11,",
"dup_monic(h, K0) cff = dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff",
"k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 == 1:",
"K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e.",
"dmp_exquo(c, cont, v, K) for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u,",
"common = _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common,",
"K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D",
"_dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm sequence by a real number",
"dy) in roots: if x in groups: groups[x].append((x, y, dx, dy)) else: groups[x]",
"compute the GCD. This will be signaled by raising an exception. In this",
"eliminate `x_0` from GCD computation in `K[X]`. \"\"\" df = dmp_degree(f, u) dg",
"a constant `p` in `K`. \"\"\" if not u: return dup_trunc(f, p, K)",
"dup_degree(f), a for i in xrange(n-1, -1, -1): f[i], b = b*f[i], b*a",
"\"\"\"Return the exact number of zeros in the given rectangle. \"\"\" V1 =",
"= dmp_inner_gcd(p, q, v, K) if s < 0: p = dmp_neg(p, v,",
"if result is not None: return result fc, F = dmp_primitive(f, u, K)",
"K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f`",
"K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial",
"F32, F33, F34, hx, hy, K) if k3 == 1: return (x, y,",
"f = dup_to_raw_dict(f) g = { s : K.one } r = n",
"[dup_LC(g, K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return",
"u) dg = dmp_degree(g, u) if df > 0 and dg > 0:",
"u, K) v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P",
"dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i] =",
"= dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return h, cff, cfg",
"in `x_j` in `K[X]`. \"\"\" if j < 0 or j > u:",
"g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact:",
"k1 = dup_sign_variations(f1, K) k2 = k - k1 - r a2, b2,",
"K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement not supported over",
"if m <= 0 or dmp_zero_p(f, u): return f g, v = dmp_zeros(m,",
"(x, y, hx, hy, (F31, F32, F33, F34)) # Quadrant #4: +- F41",
"K) if ff and gg: h = K.gcd(ff, gg) cff = ff //",
"F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy,",
"derivative in `x_j` of a polynomial in `K[X]`. \"\"\" if j < 0",
"dup_eval(f, K.zero, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K)",
"integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can be done only",
"and g at certain points and computing (fast) integer GCD of those evaluations.",
"seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c,",
"h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`.",
"u, K)): f = dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f, u)",
"K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k == 0: return",
"K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes",
"return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v = u - 1 n",
"A: return f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f,",
"polynomial LCM of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not",
"certain points and computing (fast) integer GCD of those evaluations. The polynomial GCD",
"y1, dx1, dy1, F1, K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1,",
"using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain()",
"dmp_zero_p(h, u): result.append((p, i)) break g, p, q = dmp_inner_gcd(p, h, u, K)",
"a: return dup_TC(f, K) result = K.zero for c in f: result *=",
"_dup_rr_trivial_gcd(f, g, K) if result is not None: return result df = dup_degree(f)",
"K) F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx,",
"dup_eval(f, hx, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f, hy, K)",
"u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u)",
"K) all = args.get('all', False) while True: d = dmp_diff(p, 1, u, K)",
"square-free polynomial `f(x)` returns the associated Sturm sequence `f_0(x), ..., f_n(x)` defined by::",
"cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def",
"k1, F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K)",
"y, dx, dy)] upper, lower = [], [] for group in groups.values(): while",
"while dx >= eps and dy >= eps: x, y, dx, dy, F",
"0: k += 1 if coeff: prev = coeff return k def dup_root_upper_bound(f,",
"interpolation. The final step is to verify if the result is the correct",
"K): \"\"\"m-th order derivative in `x_0` of a polynomial in `K[X]`. \"\"\" if",
"positive root of `f` given an interval `(s, t)`. \"\"\" if s ==",
"dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g`",
"h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r",
"for c in g: common = K1.lcm(common, K0.denom(c)) else: w = v-1 for",
"zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif",
"return result fc, f = dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u,",
"while stack: x, y, dx, dy, k, F1, F2, F3, F4 = stack.pop()",
"dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC,",
"continue h = _dup_right_decompose(f, s, K) if h is not None: g =",
"K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`. \"\"\"",
"-K.unit, K), s+1 return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free",
"1: stack.append((cx, y, hx, hy, k4, F41, F42, F43, F44)) if len(roots) ==",
"return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s positive roots.",
"dup_mul_ground(q, c, K) h = dup_add(h, q, K) return h def dup_compose(f, g,",
"content and a primitive polynomial. \"\"\" cont, v = dmp_content(f, u, K), u-1",
"not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0,",
"dup_degree(f) if n < m: return [] deriv, c = [], K.one for",
"`K[X]`. \"\"\" if not u: return dup_content(f, K) if K.has_Field or not K.is_Exact:",
"dup_degree(f) <= 0: if args.get('include', False): return f else: return coeff, [] result,",
"G = dmp_LC(g, K) else: if not df: F = dmp_LC(f, K) G",
"over %s\" % K) if s == t: return (s, t) if s",
"GCD of coefficients over a field. \"\"\" if not f: return K.zero else:",
"r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f,",
"0 or m < 0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B",
"a result += c return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate",
"F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3, hx, K) F24",
"= dmp_degree(R[i-1], u) dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if",
"K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate",
"dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return",
"b, c, d, f, k)] F = K.get_field() while stack: a, b, c,",
"dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD",
"`f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f,",
"K), dup_sign_variations([ dup_eval(f, hy, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f,",
"dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2],",
"s-j in g: continue fc, gc = f[n+j-i], g[s-j] coeff += (i -",
"\"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not",
"and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g,",
"dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground,",
"roots.append((cx, y, hx, hy, (F41, F42, F43, F44))) elif k4 > 1: stack.append((cx,",
"result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest @cythonized(\"u,i\")",
"K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3",
"d), cond, fast, K) def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real",
"c = K.exquo((-lc)**d, q) b = -lc * c**(m-k) f, g, m, d",
"_dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result fc, F",
"K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return",
"dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a, b, c, d =",
"\"\"\"Refine a complex root using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or",
"= [], 1 h = dmp_diff(f, 1, u, K) g, p, q =",
"or dg): F = dmp_LC(f, K) G = dmp_LC(g, K) else: if not",
"over a ring in `K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc, g",
"K(nextprime(p)) while not (a % p) or not (b % p): p =",
"0 or m < 0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f =",
"not None: g = _dup_left_decompose(f, h, K) if g is not None: return",
"= max([ r[1] for r in group ]) for i, (x, y, dx,",
"or dmp_zero_p(g, u): return R, B, D h = dmp_prem(f, g, u, K)",
"f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g, K), [],",
"[] deriv, c = [], K.one for i in xrange(0, m): c, n",
"_rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial",
"_max = max([ r[1] for r in group ]) for i, (x, y,",
"dmp_ground(-K.one, v) B, D = [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u):",
"h = dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h, u, K) cff",
"step, fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i] = (u, v, k)",
"c or not cond(a, b, c, d, i, F): A = dup_root_lower_bound(f, K)",
"K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif",
"return result df = dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f, g",
"return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of `f`",
"`x_0` in `K[X]`. \"\"\" if not u: return dup_integrate(f, m, K) if m",
"dg == 0: return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm =",
"1, K.dom) if dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f, -K.unit, K),",
"i, (x, y, dx, dy) in enumerate(group): if y == _max: upper.append((x, y,",
"u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h =",
"q = c else: q = c**(d-1) c = K.exquo((-lc)**d, q) b =",
"in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for c in f",
"= q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\"",
"elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return",
"roots = [] _, factors = dup_sqf_list(f, K) for g, k in factors:",
"F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3 ], K),",
"refinement not supported over %s\" % K) if s == t: return (s,",
"g, K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\" if not f",
"- len(A) + 1: return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def",
"dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c,",
"K), v, K), dmp_pow(lc, du-dw, v, K), v, K) q = dmp_mul(q, dmp_pow(lc,",
"F = [h] + F else: break return [f] + F def dup_sturm(f,",
"not g: return R, B, D h = dup_prem(f, g, K) h =",
"`K[X]`, useful over algebraic domains. \"\"\" if not u: return dup_sqf_norm(f, K) if",
"a_j, ...` in `K[X]`. \"\"\" if not A: return f if dmp_zero_p(f, u):",
"K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {}, 0 while",
"v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial at `x_j",
"k2 == 1: roots.append((x, cy, hx, hy, (F21, F22, F23, F24))) elif k2",
"g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if",
"fc, f = dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u, K) h",
"def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\"",
"c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm",
"dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else:",
"variable into a large integer. The final step is to verify if the",
"dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)`",
"K) b, d = A*a + b, A*c + d if not dup_eval(f,",
"`K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u,",
"not u: return dup_trunc(f, p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p,",
"`T_n` and `T_m` are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial",
"if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K)",
"p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in `K[Y]`. \"\"\"",
"x+I*y in p+I*q direction. \"\"\" C = K.complex_domain() a, b = C(p, q),",
"GCD. \"\"\" f = [] while h: g = h % x if",
"of `f` given an interval `(s, t)`. \"\"\" if s == t: return",
"r, p, P = dmp_zero(v), K.one, K.one while P <= B: p =",
"h = [ _rec_eval_tail(c, i+1, A, u, K) for c in g ]",
"df > 0 and dg > 0: return None if not (df or",
"None: f, h = result F = [h] + F else: break return",
"dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two polynomials in `K[x]`. \"\"\" return",
"0: if args.get('include', False): return f else: return coeff, [] result, i =",
"f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>,",
"dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv",
"a, K), p) d = dup_mul_ground(D, d, K) d = dmp_raise(d, v, 0,",
"y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1]",
"root until the desired precision is reached. \"\"\" while dx >= eps and",
"seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm sequence by a",
"f[i] >= 0: continue a, Q = K.log(-f[i], 2), [] for j in",
"[f] + F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f` in",
"if not f: return K.zero else: return K.one def dup_content(f, K): \"\"\"Returns GCD",
"p = dmp_pow(dmp_neg(lc, v, K), d, v, K) if not d: q =",
"return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a",
"not K.is_Algebraic: raise DomainError('computation can be done only in an algebraic domain') F,",
"dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\" a,",
"dup_LC(g, K) if not d: q = c else: q = c**(d-1) c",
"from the integer image by interpolation. The evaluation proces reduces f and g",
"i = q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K):",
"= dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v, K) D =",
"], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3 ], K), dup_sign_variations([",
"K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order derivative",
"g, K) if result is not None: return result h = dup_subresultants(f, g,",
"GCD using subresultants over a ring. \"\"\" if not u: return dup_rr_prs_gcd(f, g,",
"raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\"",
"and a primitive polynomial over a field. \"\"\" return K.one, f def dup_primitive(f,",
"a, b, c, d = b, a+b, d, c+d i += 1 s,",
"`K[x]`. \"\"\" if not f: return f lc = dup_LC(f, K) if K.is_one(lc):",
"dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return x, y,",
"\"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is not None: return",
"v, K) v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v,",
"roots.append((x, cy, hx, hy, (F21, F22, F23, F24))) elif k2 > 1: stack.append((x,",
"= dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm =",
"dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\" d = dup_degree(f)",
"K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of `f` and",
"a += K.one if a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f,",
"gcd, K) if K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf,",
"== 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K): f2",
"K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K)",
"a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\"",
"n*M + m*N D, a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D)",
"hx, K) F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy,",
"[ dmp_exquo(cf, h, v, K) for cf in f ] cfg = [",
"f, i = q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f,",
"g: return R, B, D h = dup_prem(f, g, K) h = dup_mul_ground(h,",
"= f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic and homogeneous polynomials of",
"= dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i,",
"K.log(-f[i], 2), [] for j in xrange(i+1, n): if f[j] <= 0: continue",
"K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f, K) else: coeff, f =",
"and `g` in `Z[X]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff`",
"modulo a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K)",
"\"\"\"One bisection step of complex root refinement algorithm. \"\"\" hx, hy = dx/2,",
"F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy",
"hx, K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 =",
"K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD",
"\"\"\"Isolate complex roots using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ:",
"1: return (x, y, hx, hy, (F31, F32, F33, F34)) # Quadrant #4:",
"v, K) f.insert(0, g) h = dmp_sub(h, g, v, K) h = dmp_exquo_ground(h,",
"while h: g = h % x if g > x // 2:",
"u, v), k) for (u, v) in I_pos ]) I_pos, I_neg = [],",
"u, K) if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G, p,",
"gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g",
"F4, hx, hy, K): \"\"\"Return the exact number of zeros in the given",
"x, y+dy, K) F = (F1, F2, F3, F4) x, y, dx, dy,",
"dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff",
"F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4 ], K),",
"<= B: while True: a += K.one if a == p: raise HomomorphismFailed('no",
"root on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d),",
"_dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3 =",
"`c`. \"\"\" return [ dup_taylor(f, c, K) for f in F ] def",
"gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)",
"f1 = dup_taylor(f, K.one, K) a1, b1, c1, d1, r = a, a+b,",
"GCD computation in `K[X]`. \"\"\" df = dmp_degree(f, u) dg = dmp_degree(g, u)",
"u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) gcd",
"= gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The",
"= dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0, u, K) return",
"of a polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff =",
"R = dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a, v, K)",
"Q: continue P.append(min(Q)) if not P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f,",
"h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using",
"cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return h, cff,",
"expected, got %s\" % (u, u, j)) return _rec_integrate_in(f, m, u, 0, j,",
"del group[i] break upper = sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda",
"= dup_div(f, h, K) if not r: cfg_, r = dup_div(g, h, K)",
"K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg),",
"coefficients in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else:",
"dy)) else: groups[x] = [(x, y, dx, dy)] upper, lower = [], []",
"K) P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's",
"computing (fast) integer GCD of those evaluations. The polynomial GCD is recovered from",
"not None: for i, (x, y, dx, dy, F) in enumerate(roots): roots[i] =",
"y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1,",
"if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s, g = 0,",
"integer image by interpolation. The final step is to verify if the result",
"raise RefinementFailed(\"there should be exactly one root on (%s, %s)\" % (s, t))",
"[] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K):",
"dup_eval(f, hy, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K)",
"= dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2 = k -",
"= dup_degree(g) gcd, f, g = dup_extract(f, g, K) if df == 0",
"a field') a, b = [K.one], [] while g: q, r = dup_div(f,",
"K) h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u, K) cfg",
"v = dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K):",
"return (s, t) F = K.get_field() a, c = F.numer(s), F.denom(s) b, d",
"\"\"\" if K1 is None: K1 = K0.get_ring() common = K1.one for c",
"I_pos[i+j+1] = (s, t, m) I_pos[i] = (u, v, k) for i, (u,",
"not args.get('convert'): return common, f else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\")",
"GCD and cofactors of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or",
"dup_eval(f, a, K) if not a: return dmp_TC(f, K) result, v = dmp_LC(f,",
"dmp_degree(g, u) if n < m: f, g = g, f n, m",
"True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u,",
"dmp_inner_gcd(f, h, u, K) all = args.get('all', False) while True: d = dmp_diff(p,",
"<= j < %s expected, got %s\" % (u, u, j)) return _rec_eval_in(f,",
"else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a",
"K) c = dmp_mul(d, dmp_sub(R, e, v, K), v, K) r = dmp_add(r,",
"u, K) except HomomorphismFailed: continue if K.is_one(P): r = R else: r =",
"c in f ], u) def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)`",
"polynomial over a ring. \"\"\" cont = dup_content(f, K) if not f or",
"[] if dup_LC(f, K) < 0: f = dup_neg(f, K) f = list(reversed(f))",
"`K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return",
"k) for (u, v, k) in I_neg ] + \\ [ (( u,",
"complex root until the desired precision is reached. \"\"\" while dx >= eps",
"%s expected, got %s\" % (u, u, j)) if not j: return dmp_eval(dmp_diff(f,",
"if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D =",
"polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for c",
"f1, (a1, b1, c1, d1), cond, fast, K)) else: stack.append((a1, b1, c1, d1,",
"return dmp_integrate(g, m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c,",
"factors = dup_sqf_list(f, K) if len(factors) == 1: ((f, k),) = factors I_pos",
"m): c, n = c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n",
"s != 0: continue h = _dup_right_decompose(f, s, K) if h is not",
"def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm sequence at its origin.",
"K) else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f,",
"xrange(2, df): if df % s != 0: continue h = _dup_right_decompose(f, s,",
"return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m = dmp_degree(g, u) if",
"in `K[x]`. \"\"\" fc = dup_content(f, K) gc = dup_content(g, K) gcd =",
"dy, F def dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine a complex",
"sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime",
"u, K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of sign",
"Quadrant #1: ++ F11 = Fx F12 = _dup_sturm_shift(F2, hx, K) F13 =",
"B = 2*max(abs(c)/lc for c in f) while True: r = randfloat() if",
"dup_scale(f, a, C) u = dup_strip([ C.real(c) for c in f ]) v",
"`K[X]` using subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f, g, K) if",
"r[0]) if not squarefree: for i, r in enumerate(upper): upper[i] = (r, multiplicity[r])",
"and a primitive polynomial over a ring. \"\"\" cont = dup_content(f, K) if",
"all = args.get('all', False) while True: d = dup_diff(p, 1, K) h =",
"c in f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h, c, 0,",
"u, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0,",
"def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return",
"**args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if not u: return",
"_dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f =",
"def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of `f` in `x_0` in",
"i+1 p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0:",
"gcd, f, g = dup_extract(f, g, K) if df == 0 or dg",
"445-456 \"\"\" F = [] while True: result = _dup_decompose(f, K) if result",
"raise DomainError('computation can be done only in a field') a, b = [K.one],",
"c, d), cond, fast, K): \"\"\"Refine a positive root of `f` given a",
"def dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if",
"else: f, s = dup_taylor(f, -K.unit, K), s+1 return s, f, r @cythonized(\"s,u\")",
"not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1, K)",
"K) for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content",
"if not u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return f h",
"g) h = dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x, v, K)",
"content from a pair of polynomials in `K[x]`. \"\"\" fc = dup_content(f, K)",
"rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for f in F1",
"g = dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s,",
"`p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for c in",
"if result is not None: return result fc, F = dup_primitive(f, K) gc,",
"c = [], K.one for i in xrange(0, m): c, n = c*K(n),",
"(i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f,",
"for group in groups.values(): while len(group) > 1: _max = max([ r[1] for",
"K.one, u-1 for i in xrange(0, m): c, n = c*K(n), n-1 for",
"return _rec_diff_eval(f, m, a, u, 0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half",
"bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1.0 / bound",
"GCD of multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f,",
"h = [ dmp_exquo(ch, b, v, K) for ch in h ] return",
"= (h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial",
"\"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\" if not f or not",
"d1 = a, a+b, c, c+d if not dup_eval(f, K.zero, K): return F(b1,",
"dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K): \"\"\"Refine a complex root until",
"= _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4, dx,",
"`K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u)",
"dmp_zero_p(g, u): return R, B, D h = dmp_prem(f, g, u, K) h",
"K), d, v, K) if not d: q = c else: q =",
"K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K):",
"return None if not (df or dg): F = dmp_LC(f, K) G =",
"Horner scheme. \"\"\" if not a: return dup_TC(f, K) result = K.zero for",
"return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number",
"K): I_pos.append((u, v, k)) g = dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g,",
"or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f,",
"F else: break return [f] + F def dup_sturm(f, K): \"\"\"Computes the Sturm",
"k == 1: a, b, c, d = a1, b1, c1, d1 else:",
"F1, F2, F3, F4)) while stack: x, y, dx, dy, k, F1, F2,",
"dup_degree(g) if n < m: f, g = g, f n, m =",
"break g, p, q = dup_inner_gcd(p, h, K) if all or dup_degree(g) >",
"_dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 == 1: return (x,",
"K, **args): \"\"\"Isolate complex roots using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ",
"\"\"\"Evaluate efficiently Taylor shift `f(x + a)` in `K[x]`. \"\"\" f, n =",
"K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c,",
"cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff, u,",
"2 and dv % 2: s = -s lc, i = dup_LC(R[i], K),",
"<= x1) and (y2 >= y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1,",
"resultant of `f` and `g` modulo a prime `p`. \"\"\" if not u:",
"u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r, u-1,",
"g, u, K) if result is not None: return result fc, f =",
"F33, F34))) elif k3 > 1: stack.append((x, y, hx, hy, k3, F31, F32,",
"-lc * c**(m-k) f, g, m, d = g, h, k, m-k B.append(b)",
"= K1.lcm(common, K0.denom(c)) else: w = v-1 for c in g: common =",
"B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of two",
"= (-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1,",
"b1, b2 = a2, a1, b2, b1 c1, c2, d1, d2 = c2,",
"result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at `x_0 =",
"hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots in (%s, %s) x (%s,",
"= a` in `K[x]` using Horner scheme. \"\"\" if not a: return dup_TC(f,",
"CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p], K), P*p)",
"@cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j:",
"= dup_mul(h, g, K) h = dup_add_term(h, c, 0, K) return h @cythonized(\"u\")",
"F): A = dup_root_lower_bound(f, K) if A is not None: A = K(int(A))",
"USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g,",
"K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K):",
"if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a, b, c,",
"isolating rectangles for all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B",
"and `g` modulo a prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g,",
"_dup_sturm_shift(F3, hx, K) F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx,",
"def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`, useful over algebraic domains.",
"1, u) B = n*M + m*N D, a = [K.one], -K.one r",
"\"\"\" if not f: return [] h, Q = [f[0]], [[K.one]] for i",
"C) u = dup_strip([ C.real(c) for c in f ]) v = dup_strip([",
"if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_",
"`K[X]`. \"\"\" if dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1,",
"r[0]) lower = sorted(lower, key=lambda r: r[0]) if not squarefree: for i, r",
"\"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\" d = dup_degree(f) if d",
"= dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return common, f else: return",
"f, g step = lambda a, b, c, d, i, F: i >=",
"i = dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v,",
"dup_diff(p, 1, K) h = dup_sub(q, d, K) if not h: result.append((p, i))",
"def dup_sqf_list(f, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[x]`. \"\"\"",
"= dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s =",
"dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should",
"field of characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`, where:: f =",
"= dmp_exquo_ground(g, gcd, u, K) return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate",
"0: p = -p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res =",
"t, h def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`.",
"u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u,",
"h: g = h % x if g > x // 2: g",
"= [], [(a, b, c, d, f, k)] F = K.get_field() while stack:",
"if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be exactly one root on",
"def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral of `f` in `x_j`",
"f[1:]: result = dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v, K)",
"M = dmp_degree_in(g, 1, u) B = n*M + m*N D, a =",
"K) if len(factors) == 1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond,",
"in factors: for u, v in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k))",
"K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be exactly one root",
"for f in F4 ], K), ] V0 = [ dup_sign_variations([ dup_eval(f, K.zero,",
"not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm in perms:",
"G, p, v, K) e = dmp_eval(r, a, v, K) if not v:",
"dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c =",
"B, D = [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return R,",
"u, K) g, p, q = dmp_inner_gcd(f, h, u, K) all = args.get('all',",
"R = [f, g] d = n - m v = u -",
"2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for i in",
"dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow,",
"K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant",
"return f h = [f[0]] for c in f[1:]: h = dmp_mul(h, g,",
"n else: cond = lambda a, b, c, d, i, F: i >=",
"h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0) cfg =",
"be done only in a field') f = dup_sqf_part(f, K) sturm = [f,",
"zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K),",
"= dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1,",
"polynomial in `K[x]`. \"\"\" if m <= 0: return f n = dup_degree(f)",
"K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c h",
"K) if k4 == 1: roots.append((cx, y, hx, hy, (F41, F42, F43, F44)))",
"if not u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain must",
"i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m, v, K)",
"f, (a, b, c, d), cond, fast, K)) continue f1 = dup_taylor(f, K.one,",
"k, m-k B.append(b) D.append(d) h = dmp_prem(f, g, u, K) h = [",
"= dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f,",
"n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\"",
"v, K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K)",
"g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm //",
"\"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\")",
"u) def dup_monic(f, K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\" if",
"\"\"\" n = dup_degree(f) m = dup_degree(g) if n < m: f, g",
"= [K.zero]*m for i, c in enumerate(reversed(f)): n = i+1 for j in",
"if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def",
"in group ]) for i, (x, y, dx, dy) in enumerate(group): if y",
"coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\")",
"group in groups.values(): while len(group) > 1: _max = max([ r[1] for r",
"u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD:",
"K) return R, B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of",
"dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD",
"dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1.0 / bound else: return",
"= _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33,",
"dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)` in `K[x]`. \"\"\"",
"else: q = c**(d-1) c = K.exquo((-lc)**d, q) b = -lc * c**(m-k)",
"square-free polynomial in `K[x]`. \"\"\" if not f: return True else: return not",
"u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f`",
"f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if k1 < k2:",
"return a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\"",
"= _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant #1: ++ F11 =",
"= -p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p, q)",
"dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f`",
"0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while True:",
"- 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg =",
"f ] cfg = [ dmp_exquo(cg, h, v, K) for cg in g",
"for s in xrange(2, df): if df % s != 0: continue h",
"True else: raise ValueError(\"can't refine a real root on (%s, %s)\" % (s,",
"`(s, t)`. \"\"\" if s == t: return (s, t) F = K.get_field()",
"d if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f,",
"return dup_quo_ground(f, lc, K) @cythonized(\"u\") def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by",
"= K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0",
"fc = dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if",
"v) in I_neg ] + \\ [ (( u, v), k) for (u,",
"return (x, y, hx, hy, (F31, F32, F33, F34)) # Quadrant #4: +-",
"type(n) is not int: cond = lambda a, b, c, d, i, F:",
"c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K):",
"ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f else: return K.one, f @cythonized(\"u\")",
"x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else: return",
"i < u - len(A) + 1: return h else: return dup_eval(h, A[-u+i-1],",
"K) return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex",
"dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift,",
"K) else: if USE_DMP_HEU_GCD: if K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except",
"m = m, n R = [f, g] d = n - m",
"= 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors of `f`",
"for `f`'s positive roots. \"\"\" n, t, P = len(f), K.one, [] if",
"F3, F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy,",
"s, i = 1, 1 p, q = K.one, K.one for b, d",
"K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\"",
"\"\"\" if K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain() f = dup_convert(f,",
"dup_primitive(g, K) c = K.lcm(fc, gc) h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g,",
"return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th",
"_dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy,",
"deriv, c, v = [], K.one, u-1 for i in xrange(0, m): c,",
"is not None: return result fc, F = dup_primitive(f, K) gc, G =",
"if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g,",
"and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u),",
"= 0 while True: h, _ = dmp_inject(f, u, K, front=True) r =",
"xrange(i+1, n): if f[j] <= 0: continue q = t + a -",
"in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant",
"= dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v) == m: break",
"J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f` and",
"dx, dy)) del group[i] break upper = sorted(upper, key=lambda r: r[0]) lower =",
"u) B = n*M + m*N D, a = [K.one], -K.one r =",
"u, K): \"\"\"Evaluate a polynomial at `x_j = a` in `K[X]` using Horner",
"dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r =",
"polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic",
"@cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of `f` and `g`",
"must be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True:",
"polynomials `f` and `g` in `Z[X]`, returns their GCD and cofactors, i.e. polynomials",
"interval to the given precision. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f,",
"K1, K0) c = dup_LC(h, K0) h = dup_monic(h, K0) cff = dup_convert(cff,",
"i += 1 if not args.get('include', False): return coeff, result else: (g, i),",
"Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of",
"is not None: A = K(int(A)) else: A = K.zero if fast and",
"g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a",
"u-1 p = dmp_one(v, K) q = dmp_one(v, K) for b, d in",
"= [ dmp_exquo(cg, h, v, K) for cg in g ] return [h],",
"\"\"\" fc, f = dmp_ground_primitive(f, u, K) gc, g = dmp_ground_primitive(g, u, K)",
"not u: return dup_rr_content(f, K) cont, v = K.zero, u-1 for c in",
"g, u, K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if not u:",
">= x1+dx1 or x2+dx2 <= x1) and (y2 >= y1+dy1 or y2+dy2 <=",
"K), u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u,",
"`K[X]` using Horner scheme. \"\"\" if not u: return dup_eval(f, a, K) if",
"r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT for Collins's resultant",
"m) in enumerate(I_neg[i+1:]): while not (s >= v or t <= u): u,",
"in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f,",
"upper.append((x, y, dx, dy)) del group[i] break _min = min([ r[1] for r",
"x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps,",
"K0) return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f,",
"return dmp_strip([ dmp_rem(c, p, u-1, K) for c in f ], u) @cythonized(\"u,v\")",
"return dup_lcm(f, g, K) if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u,",
"1: roots = [dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)] else:",
"p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p,",
"dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a",
"dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import (",
"= K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g,",
"= dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K) if not r: cfg_,",
"in `K[x]`. \"\"\" if not f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f,",
"d1 f1, f2, k1, k2 = f2, f1, k2, k1 if k1 ==",
"dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul,",
"in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can be done only in",
"c1, c2, d1, d2 = c2, c1, d2, d1 f1, f2, k1, k2",
"K) return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate",
"K, **args): \"\"\"Isolate real roots using continued fractions approach. \"\"\" if K.is_QQ: (_,",
"(a, b, c, d), cond, fast, K): \"\"\"Refine a positive root of `f`",
"q = dup_inner_gcd(f, h, K) all = args.get('all', False) while True: d =",
"else: return not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K):",
"= g, h, k, m-k B.append(b) D.append(d) h = dmp_prem(f, g, u, K)",
"dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd, u, K) return gcd, f,",
"def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[x]`.",
"o ... f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic and",
"dx >= eps and dy >= eps: x, y, dx, dy, F =",
">= 0: continue a, Q = K.log(-f[i], 2), [] for j in xrange(i+1,",
"`x_j` at `a` in `K[X]`. \"\"\" if j > u: raise IndexError(\"-%s <=",
"f[i], a = a*f[i], -a return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently",
"= list(f), dup_degree(f) for i in xrange(n, 0, -1): for j in xrange(0,",
"given an interval `(s, t)`. \"\"\" if s == t: return (s, t)",
"K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([",
"stack: x, y, dx, dy, k, F1, F2, F3, F4 = stack.pop() hx,",
"is a square-free polynomial in `K[x]`. \"\"\" if not f: return True else:",
"K): \"\"\"Shift origin of a Sturm sequence by a real number `c`. \"\"\"",
"def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is a square-free polynomial in",
"integer GCD of those evaluations. The polynomial GCD is recovered from the integer",
"\"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f,",
"if not Q: continue P.append(min(Q)) if not P: return None else: return 2.0**(max(P)+1)",
"indefinite integral of `f` in `K[x]`. \"\"\" if m <= 0 or not",
"def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a positive root of `f`",
"common, K0) if not args.get('convert'): return common, f else: return common, dup_convert(f, K0,",
"u, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[X]`. \"\"\" return",
"`K[x]`. \"\"\" if m <= 0 or not f: return f g =",
"def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a ring.",
"stack.pop() hx, hy = dx/2, dy/2 cx, cy = x + hx, y",
"return f n = dup_degree(f) if n < m: return [] deriv, c",
"> u: raise IndexError(\"-%s <= j < %s expected, got %s\" % (u,",
"a polynomial at `x_j = a` in `K[X]` using Horner scheme. \"\"\" if",
"k)) F_pos[k], F_neg[k] = f, g step = lambda a, b, c, d,",
"of Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F = [] while True:",
"\"\"\"Returns square-free part of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return",
"f = dup_monic(f, K) else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)):",
"def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial cases in GCD algorithm over a field.",
"coefficients in `K[X]`. \"\"\" if not u: return dup_content(f, K) if K.has_Field or",
"_dup_zz_gcd_interpolate(h, x, K) h = dup_primitive(h, K)[1] cff_, r = dup_div(f, h, K)",
"= dmp_diff(f, 1, u, K) g, p, q = dmp_inner_gcd(f, h, u, K)",
"K) gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd, K)",
"- b)` 2. `x**n o x**m = x**m o x**n` 3. `T_n o",
"F_neg = {}, {} for f, k in factors: for u, v in",
"u, K), u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g,",
"of `f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def",
"k = stack.pop() A = dup_root_lower_bound(f, K) if A is not None: A",
"f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm,",
"dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[x]`. \"\"\"",
"break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over",
"@cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of a polynomial in",
"s, t, cond, fast, K) if negative: return (-t, -s) else: return (",
"B, D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0: return",
"\"\"\"Compute resultant of `f` and `g` modulo a prime `p`. \"\"\" if not",
"K), R) s, i = 1, 1 p, q = K.one, K.one for",
"% p) or not (b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f,",
"K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg, g = dup_ground_to_ring(g, K0, K1)",
"x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K)",
"f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm",
"cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over",
"None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm",
"step = lambda a, b, c, d, i, F: i >= 1 for",
"dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`, useful over algebraic domains. \"\"\"",
"K) gg = dmp_eval(g, x, u, K) v = u - 1 if",
"`f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None:",
"= dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if k1 < k2: a1,",
"g = dup_extract(f, g, K) if df == 0 or dg == 0:",
"polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if result",
"dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u,",
"of characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`, where:: f = f_1",
"dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f,",
"fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g step = lambda",
"for Algebraic Computation, Academic Press, London, 1988, pp. 124-128 \"\"\" if not K.has_Field:",
"dup_sign_variations(f, K) if k == 0: return [] if k == 1: roots",
"b, K) return R, B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS",
"dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f,",
"cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial",
"dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin",
"K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not args.get('convert'):",
"hx, hy, (F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1",
"return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]`",
"= dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r,",
"< 0 or m < 0: return dmp_zero(u-1) K1 = K0.get_ring() cf, f",
"K) d, v = dmp_degree(f, u), u-1 if d <= 0: return dmp_zero(v)",
"= dmp_LC(R[i], K), i+1 p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K),",
"(u, u, j)) if not j: return dmp_eval(dmp_diff(f, m, u, K), a, u,",
"not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K)",
"r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors) > 1: for",
"common = K1.one for c in f: common = K1.lcm(common, K0.denom(c)) if not",
"c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f,",
"= dup_inner_gcd(f, h, K) all = args.get('all', False) while True: d = dup_diff(p,",
"d)) < n else: cond = lambda a, b, c, d, i, F:",
"K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at `x_j =",
"= {}, 0 while f: q, r = dup_div(f, h, K) if dup_degree(r)",
"= [] while True: result = _dup_decompose(f, K) if result is not None:",
"dup_LC(r, K) f, i = q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\")",
"(s, t) if s > t: s, t = t, s negative =",
"= dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break else: f, s =",
"K0) if not args.get('convert'): return common, f else: return common, dup_convert(f, K0, K1)",
"K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K):",
"min([ r[1] for r in group ]) for i, (x, y, dx, dy)",
"= dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h,",
"K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if not u: return dup_content(f,",
"u, K) if result is not None: return result fc, f = dmp_primitive(f,",
"dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots, stack = [], [] F1",
"= dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf, h, v, K) for",
"`K_0` to `K_1`. \"\"\" if K1 is None: K1 = K0.get_ring() common =",
"a, c = F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f = dup_transform(f,",
"b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v, K) f, g,",
"h = dup_subresultants(F, G, K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)):",
"dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v,",
"1, 1 p, q = K.one, K.one for b, d in zip(B, D)[:-1]:",
"f: result *= a result += c return result @cythonized(\"u,v\") def dmp_eval(f, a,",
"{} for (_, (x, y, dx, dy, _), k) in roots: multiplicity[(x, y,",
"def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p` in",
"k == 1: roots.append((x, y, dx, dy, (F1, F2, F3, F4))) elif k",
"dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\"",
"dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n =",
"K.one } r = n // s for i in xrange(1, s): coeff",
"<= 0: return f n = dup_degree(f) if n < m: return []",
"`f` and `g` in `K[X]`. \"\"\" if not u: return dup_lcm(f, g, K)",
"K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed:",
"h, _ = dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h, 1, K.dom)",
"u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u))",
"A, u, K) for c in g ] if i < u -",
"in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a Sturm sequence",
"u: return dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f, u): return",
"def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n",
"algorithm in `K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g) if n <",
">= n s, t = dup_outer_refine_real_root(f, s, t, cond, fast, K) if negative:",
"K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b =",
"c, d = b, a+b, d, c+d i += 1 s, t =",
"\"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g,",
"a polynomial in `K[X]`. \"\"\" if not u: return dup_sqf_list(f, K, **args) if",
"in `Z[X]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg`",
"g, u, K): \"\"\"Extracts common content from a pair of polynomials in `K[X]`.",
"cf in f ] cfg = [ dmp_exquo(cg, h, v, K) for cg",
"list(f), dup_degree(f), -K.one for i in xrange(n-1, -1, -1): f[i], a = a*f[i],",
"dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s",
"in xrange(i+1, n): if f[j] <= 0: continue q = t + a",
"g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1) g = dup_convert(g,",
"K.one, cx, cy, K) # Quadrant #1: ++ F11 = Fx F12 =",
"while f: q, r = dup_div(f, h, K) if dup_degree(r) > 0: return",
"(cx, cy, hx, hy, (F11, F12, F13, F14)) # Quadrant #2: -+ F21",
"dy/2 cx, cy = x + hx, y + hy Fx = _dup_inner_sturm(f,",
"if dmp_zero_p(h, u): result.append((p, i)) break g, p, q = dmp_inner_gcd(p, h, u,",
"[K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g,",
"u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K):",
"j in xrange(i+1, n): if f[j] <= 0: continue q = t +",
"dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if",
"gc, G = dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F, G,",
"\"\"\"Returns GCD of multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1 if",
"for c in g ] if i < u - len(A) + 1:",
"d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c =",
"def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials",
"`f` in `K[x]`. \"\"\" if m <= 0 or not f: return f",
"[ c % p for c in f ] return dup_strip(g) @cythonized(\"u\") def",
"\"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K)",
"return dup_diff(f, m, K) if m <= 0: return f n = dmp_degree(f,",
"= a_j, ...` in `K[X]`. \"\"\" if not A: return f if dmp_zero_p(f,",
"return (cx, cy, hx, hy, (F11, F12, F13, F14)) # Quadrant #2: -+",
"K): \"\"\"Handle trivial cases in GCD algorithm over a ring. \"\"\" zero_f =",
"x**n` 3. `T_n o T_m = T_m o T_n` where `T_n` and `T_m`",
"result = dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v,",
"\"\"\" fc = dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc)",
"else: return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint",
"def dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine a complex root using",
"t, k)) F_pos[k], F_neg[k] = f, g step = lambda a, b, c,",
"dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u, K) v = u",
"-u) for (u, v) in I_neg ] + I_pos) _, factors = dup_sqf_list(f,",
"d = b, a+b, d, c+d i += 1 s, t = F(a,",
"k1 < k2: a1, a2, b1, b2 = a2, a1, b2, b1 c1,",
"in f[1:]: h = dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0,",
"+ d if not dup_eval(f, K.zero, K): return F(b, d), F(b, d) f,",
"ff = dup_eval(f, x, K) gg = dup_eval(g, x, K) if ff and",
"= [] while h: g = h % x if g > x",
"return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over",
"is not None: return result fc, f = dmp_primitive(f, u, K) gc, g",
"= dup_exquo(F, g, K) return s, t, h def dup_invert(f, g, K): \"\"\"Compute",
"dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u,",
"of `f` and `g` in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g,",
"a+b, d, c+d i += 1 s, t = F(a, c), F(b, d)",
"K) if k2 == 1: roots.append((x, cy, hx, hy, (F21, F22, F23, F24)))",
"`f o g = f(x + b) o (g - b)` 2. `x**n",
"< %s expected, got %s\" % (u, u, j)) return _rec_diff_in(f, m, u,",
"dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) h = dmp_ground_monic(h,",
"\"\"\" cont = dup_content(f, K) if not f or K.is_one(cont): return cont, f",
"dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in",
"for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in zip(f[1:],",
"u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K),",
"K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)):",
"is not None: return result df = dup_degree(f) dg = dup_degree(g) gcd, f,",
"n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u,",
"p) or not (b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p,",
"xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f,",
"[f, g] d = n - m b = (-K.one)**(d+1) c = -K.one",
"= 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u,",
"c in f: result *= a result += c return result @cythonized(\"u,v\") def",
"K) else: F = dmp_content(f, u, K) G = dmp_LC(g, K) v =",
"GCD using subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if",
"to verify if the result is the correct GCD. This gives cofactors as",
"F) for r in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors) >",
"dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g,",
"d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if",
"K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K)",
"not u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain must be",
"F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4 =",
"`K[X]`. \"\"\" if not u: return dup_compose(f, g, K) if dmp_zero_p(f, u): return",
"in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u, K)): f",
"or t <= u): u, v = dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K)",
"K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of complex roots not",
"K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K)",
"in `K[x]`. \"\"\" d = dup_degree(f) if d <= 0: return K.zero else:",
"a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f,",
"= K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f =",
"v) == n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G,",
"== t: return (s, t) F = K.get_field() a, c = F.numer(s), F.denom(s)",
"\"\"\"m-th order derivative in `x_0` of a polynomial in `K[X]`. \"\"\" if not",
"f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h",
"k4 > 1: stack.append((cx, y, hx, hy, k4, F41, F42, F43, F44)) if",
"scheme. \"\"\" if not u: return dup_eval(f, a, K) if not a: return",
"w, i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f,",
"def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and cofactors of `f` and",
"hx, y + hy F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f,",
"cont, v, K) for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K):",
"while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def",
"dup_degree(r) > 0: return None else: g[i] = dup_LC(r, K) f, i =",
"_dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy,",
"F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K)",
"F2, F3, F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y, dx,",
"import random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform",
"n, t, P = len(f), K.one, [] if dup_LC(f, K) < 0: f",
"not int: cond = lambda a, b, c, d, i, F: abs(F(a, c)",
"in xrange(n-1, -1, -1): f[i], b = b*f[i], b*a return f def dup_taylor(f,",
"t, m) in enumerate(I_neg[i+1:]): while not (s >= v or t <= u):",
"evaluate a polynomial in `x_j` at `a` in `K[X]`. \"\"\" if j >",
"dup_neg(f, K) f = list(reversed(f)) for i in xrange(0, n): if f[i] >=",
"in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try:",
"c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h, u,",
"= [], 1 h = dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f,",
"primitive polynomial over a field. \"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns",
"K.zero else: s = (-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r =",
"K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K):",
"c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u,",
"dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f, m, a, u, 0,",
"b, c, d), cond, fast, K)] else: roots, stack = [], [(a, b,",
"s, t, step, fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i] = (u,",
"_dup_right_decompose(f, s, K) if h is not None: g = _dup_left_decompose(f, h, K)",
"v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c in",
"global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise",
"h = dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x,",
"def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\"",
"K) if k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a,",
"fast, K)) continue f1 = dup_taylor(f, K.one, K) a1, b1, c1, d1, r",
"polys = dmp_to_dict(f, u), [], [] for monom, coeff in F.iteritems(): if not",
"while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F,",
"return f else: return coeff, [] result, i = [], 1 h =",
"dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return h, cff, cfg def",
"lower = [], [] for group in groups.values(): while len(group) > 1: _max",
"a` in `K[x]` using Horner scheme. \"\"\" if not a: return dup_TC(f, K)",
"= stack.pop() A = dup_root_lower_bound(f, K) if A is not None: A =",
"K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite integral of",
"def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if not",
"def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real root's approximating interval to",
"K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f` in",
"F23, F24))) elif k2 > 1: stack.append((x, cy, hx, hy, k2, F21, F22,",
"u, K) else: F = dmp_content(f, u, K) G = dmp_LC(g, K) v",
"= dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r,",
"(F1, F2, F3, F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x, y,",
"hy, (F31, F32, F33, F34))) elif k3 > 1: stack.append((x, y, hx, hy,",
"if m <= 0 or not f: return f g = [K.zero]*m for",
"J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f,",
"gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd,",
"and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\"",
"\"\"\" if not u: return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and",
"dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u,",
"the integer image by interpolation. The evaluation proces reduces f and g variable",
"] + \\ [ (( u, v), k) for (u, v) in I_pos",
"not (s >= v or t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u,",
"K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B =",
"raise DomainError(\"isolation of complex roots not supported over %s\" % K) squarefree =",
"d) f, g = dup_taylor(f, K.one, K), f a1, b1, c1, d1 =",
"dmp_degree(g, u) if n < 0 or m < 0: return dmp_zero(u-1) K1",
"f else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K):",
"= u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c =",
"res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res, p, v, K),",
"== 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2),",
"`f` in `K[X]`, useful over algebraic domains. \"\"\" if not u: return dup_sqf_norm(f,",
"K) I_pos[i+j+1] = (s, t, m) I_pos[i] = (u, v, k) for i,",
"front=True) r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom): break else:",
"g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B,",
"image by interpolation. The evaluation proces reduces f and g variable by variable",
"K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators,",
"@cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at `x_0 = a`",
"A[-1], K) else: h = [ _rec_eval_tail(c, i+1, A, u, K) for c",
"dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h = dup_add(h, q, K)",
"g = g, r a, b = b, dup_sub_mul(a, q, b, K) a",
"if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of",
"df: F = dmp_LC(f, K) G = dmp_content(g, u, K) else: F =",
"resultant of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def",
"abs(dup_LC(g, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x,",
"sign, monom in zip(perm, monoms): if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G,",
"= dup_trunc(D, p, K) return r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper",
"K.zero, K): return F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K) if k",
"b, c, d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if",
"= [(x, y, dx, dy)] upper, lower = [], [] for group in",
"r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2 while not",
"@cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a",
"= dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1] _,",
"PRS of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def",
"if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g, K), [], [-K.one]",
"cythonized, variations ) from random import random as randfloat def dup_ground_to_ring(f, K0, K1=None,",
"F42, F43, F44, hx, hy, K) if k4 == 1: return (cx, y,",
"dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" result",
"K) else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and a",
"cont, f else: return cont, [ dmp_exquo(c, cont, v, K) for c in",
"dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul,",
"Journal of Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F = [] while",
"d, f, k)] F = K.get_field() while stack: a, b, c, d, f,",
"ch in h ] return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u,",
"K), ] return sum(v1 - v0 for v1, v0 in zip(V1, V0)) //",
"K) if k1 == 1: roots.append((cx, cy, hx, hy, (F11, F12, F13, F14)))",
"= K.quo(res*p, q) return res, R def dup_resultant(f, g, K): \"\"\"Computes resultant of",
"2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)),",
"1, K), K) sqf = dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact:",
"polynomial in `K[X]`. \"\"\" if not u: return dup_discriminant(f, K) d, v =",
"bound is not None: return 1.0 / bound else: return None def dup_inner_refine_real_root(f,",
"return (dup_LC(R[-1], K), R) s, i = 1, 1 p, q = K.one,",
"ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K) gc, g =",
"K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd):",
"c, n = c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n =",
"in `K[X]` using subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f, g, K)",
"of the heuristic polynomial GCD, International Symposium on Symbolic and Algebraic Computation (ISSAC),",
"<= j < %s expected, got %s\" % (u, u, j)) return _rec_integrate_in(f,",
"fast, K): \"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\" a, b, c,",
"for c in f ], u) def dup_monic(f, K): \"\"\"Divides all coefficients by",
"gc) if K.is_one(cont): break return cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD",
"K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc):",
"`K[x]`. \"\"\" if not f: return [] h, Q = [f[0]], [[K.one]] for",
"K.zero else: return K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients in `K[x]`.",
"// abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2) for i in xrange(0,",
"K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD:",
"g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i,",
"return K.zero else: return K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients in",
"u): return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f else:",
"k += 1 if coeff: prev = coeff return k def dup_root_upper_bound(f, K):",
"(%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast,",
"K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of",
"F22, F23, F24)) # Quadrant #3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy,",
"+ b) o (g - b)` 2. `x**n o x**m = x**m o",
"cond, fast, K) if negative: return (-t, -s) else: return ( s, t)",
"(u, v) in I_neg ] + I_pos) _, factors = dup_sqf_list(f, K) if",
"K), u-1 for coeff in f[1:]: result = dmp_mul_ground(result, a, v, K) result",
"K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i == u:",
"dup_mul_ground(h, gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h,",
"0: return f n = dmp_degree(f, u) if n < m: return dmp_zero(u)",
"given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for f in",
"\"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p) v =",
"r: cfg_, r = dup_div(g, h, K) if not r: h = dup_mul_ground(h,",
"u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff =",
"<NAME>, Computer Algebra Systems and Algorithms for Algebraic Computation, Academic Press, London, 1988,",
"if not (df or dg): F = dmp_LC(f, K) G = dmp_LC(g, K)",
"a polynomial `p` in `K[Y]`. \"\"\" return dmp_strip([ dmp_rem(c, p, u-1, K) for",
"= dmp_degree(g, u) if n < 0 or m < 0: return dmp_zero(u-1)",
"if the result is the correct GCD. This gives cofactors as a side",
"g, K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f` and `g`",
"K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else: return dup_neg(g, K), [], [-K.one] elif",
"polynomials are not unique, consider examples: 1. `f o g = f(x +",
"K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None",
"f, g = g, f n, m = m, n R = [f,",
"j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i ==",
"is not None: for i, (x, y, dx, dy, F) in enumerate(roots): roots[i]",
"n = i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c,",
"u) or dmp_one_p(cont, v, K): return cont, f else: return cont, [ dmp_exquo(c,",
"u, K) h = dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p, i))",
"= dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h,",
"- len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\" if",
"K0, K1) cg, g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1)",
"f else: return coeff, [] result, i = [], 1 h = dmp_diff(f,",
"return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s",
"g, p, q = dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g, u)",
"groups[x].append((x, y, dx, dy)) else: groups[x] = [(x, y, dx, dy)] upper, lower",
"cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants",
"if not r: cfg_, r = dup_div(g, h, K) if not r: h",
"u): return cont for c in f[1:]: cont = dmp_gcd(cont, c, v, K)",
"return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g",
"transform `K_0` to `K_1`. \"\"\" if K1 is None: K1 = K0.get_ring() common",
"\"\"\" df = dmp_degree(f, u) dg = dmp_degree(g, u) if df > 0",
"The final step is to verify if the interpolated polynomial is the correct",
"pp. 445-456 \"\"\" F = [] while True: result = _dup_decompose(f, K) if",
"Given an univariate, square-free polynomial `f(x)` returns the associated Sturm sequence `f_0(x), ...,",
"u) dg = dmp_degree(g, u) gcd, f, g = dmp_ground_extract(f, g, u, K)",
"g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm =",
"if dup_degree(f) <= 0: if args.get('include', False): return f else: return coeff, []",
"composition `f(-x)` in `K[x]`. \"\"\" f, n, a = list(f), dup_degree(f), -K.one for",
"\"\"\" return [ dup_mirror(f, K) for f in F ] def _dup_inner_zeros(F1, F2,",
"F24, hx, hy, K) if k2 == 1: roots.append((x, cy, hx, hy, (F21,",
"\"\"\"Extracts common content from a pair of polynomials in `K[X]`. \"\"\" fc =",
"+= K.one if a == p: raise HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a,",
"i.e. transform `K_0` to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0, K1)",
"// 2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K),",
"= dup_content(f, K) if not f or K.is_one(cont): return cont, f else: return",
"K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g = dup_exquo_ground(g, gcd, K) return gcd,",
"K0, K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0,",
"def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s positive roots. \"\"\" bound",
"// x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD in",
"dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) +",
"= dmp_primitive(h, u, K) h = dmp_mul_term(h, c, 0, u, K) h =",
"K), dup_gcd(f, g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K):",
"def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in",
"f: return f g = [K.zero]*m for i, c in enumerate(reversed(f)): n =",
"while not c or not cond(a, b, c, d, i, F): A =",
"= K(int(A)) else: A = K.zero if fast and A > 16: f",
"dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in",
"\"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\" a, b, c, d =",
"for c in f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h, c,",
"else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0`",
"a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f if K.is_negative(dmp_ground_LC(f, u,",
"return cont for c in f[1:]: cont = dmp_gcd(cont, c, v, K) if",
"u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K),",
"roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast, K)) else: stack.append((a1, b1, c1,",
"B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero, R)",
"F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one,",
"for c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q =",
"roots = multiplicity.keys() groups = {} for (x, y, dx, dy) in roots:",
"def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result =",
"dup_eval(f, x, K) gg = dup_eval(g, x, K) if ff and gg: h",
"a ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f, u, K) gc, g",
"for j in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return g",
"K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return common, f",
"dy, k, F1, F2, F3, F4)) while stack: x, y, dx, dy, k,",
"%s\" % K) if s == t: return (s, t) if s >",
"return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle trivial",
"F = dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while True: h, _",
"variations([-1, 1], len(monoms), repetition=True) for perm in perms: G = dict(F) for sign,",
"K): \"\"\"Evaluate functional composition `f(g)` in `K[X]`. \"\"\" if not u: return dup_compose(f,",
"if s == t: return (s, t) if s > t: s, t",
"K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) #",
"g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest def dup_extract(f, g,",
") from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg,",
"m b = (-K.one)**(d+1) c = -K.one B, D = [b], [d] if",
"v, k)) g = dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond, fast,",
"u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and cofactors",
"else: g.append(c) else: g = [ c % p for c in f",
"else: cond = lambda a, b, c, d, i, F: True if args.get('sqf',",
"m, u, K): \"\"\"m-th order derivative in `x_0` of a polynomial in `K[X]`.",
"and dv % 2: s = -s lc, i = dup_LC(R[i], K), i+1",
"u) gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u,",
"K) sqf = dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact: return dup_monic(sqf,",
"break g, p, q = dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g,",
"return K.one, f def dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial in",
"[K.one]: return (dup_LC(R[-1], K), R) s, i = 1, 1 p, q =",
"K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_,",
"h, K) if g is not None: return g, h return None def",
"switch to another GCD method. The algorithm computes the polynomial GCD by evaluating",
"dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h,",
"I_pos ]) I_pos, I_neg = [], [] F_pos, F_neg = {}, {} for",
"v, K) res = dmp_quo(dmp_mul(res, p, v, K), q, v, K) return res,",
"[u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1]",
"in h ] return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K):",
"K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f,",
"b = C(p, q), C(x, y) f = dup_convert(f, K, C) f =",
"= dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x,",
"d, K) d = dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e,",
"def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x = a` in `K[x]`",
"dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\")",
"_rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if not v: for c",
"(x, y, dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx,",
"K) if k4 == 1: return (cx, y, hx, hy, (F41, F42, F43,",
"K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0)",
"%s\" % K) squarefree = args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K,",
"K)) for c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q",
"a polynomial in `K[x]`. \"\"\" d = dup_degree(f) if d <= 0: return",
"precision. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif",
"B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f,",
"K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u) for (u,",
"u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd,",
"g, K) F = dup_sub_mul(h, s, f, K) t = dup_exquo(F, g, K)",
"c, d = a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K)",
"not None: return result fc, F = dup_primitive(f, K) gc, G = dup_primitive(g,",
"dx/2, dy/2 cx, cy = x + hx, y + hy Fx =",
"j < %s expected, got %s\" % (u, u, j)) return _rec_diff_in(f, m,",
"`K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K):",
"f, g = g, r a, b = b, dup_sub_mul(a, q, b, K)",
"g = [] for c in f: c = c % p if",
"in groups: groups[x].append((x, y, dx, dy)) else: groups[x] = [(x, y, dx, dy)]",
"v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g, K): \"\"\"Handle trivial",
"dup_degree(g) > 0: result.append((g, i)) i += 1 if not args.get('include', False): return",
"for c in f ]) v = dup_strip([ C.imag(c) for c in f",
"t, step, fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i] = (u, v,",
"dmp_degree(R[i+1], u) if du % 2 and dv % 2: s = -s",
"an univariate polynomial `f` with coefficients in a field of characteristic zero, returns",
"dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f, cont,",
"if not s-j in g: continue fc, gc = f[n+j-i], g[s-j] coeff +=",
"K.zero if fast and A > 16: f = dup_scale(f, A, K) a,",
"dmp_degree(f, u) m = dmp_degree(g, u) N = dmp_degree_in(f, 1, u) M =",
"c in g: common = K1.lcm(common, K0.denom(c)) else: w = v-1 for c",
"dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a field. \"\"\"",
"m) I_neg[i] = (u, v, k) return sorted([ ((-v, -u), k) for (u,",
"k3 > 1: stack.append((x, y, hx, hy, k3, F31, F32, F33, F34)) #",
"\"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h, K)",
"stack.append((x, y, hx, hy, k3, F31, F32, F33, F34)) # Quadrant #4: +-",
"s = 0 while True: h, _ = dmp_inject(f, u, K, front=True) r",
"= dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u,",
"= dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw, v, K), v,",
"b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f =",
"= F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13,",
"return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of",
"g = [ c % p for c in f ] return dup_strip(g)",
"return cont, [ dmp_exquo(c, cont, v, K) for c in f ] @cythonized(\"u\")",
"K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial GCD of `f` and",
"hx, hy, K) if k4 == 1: return (cx, y, hx, hy, (F41,",
"K) gc, g = dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u, K)[-1]",
"return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial",
"K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content",
"dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem,",
"-1): for j in xrange(0, i): f[j+1] += a*f[j] return f def dup_transform(f,",
"dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in f) while True: r",
"if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u):",
"b1, c1, d1), cond, fast, K)) else: stack.append((a1, b1, c1, d1, f1, k1))",
"res = K.quo(res*p, q) return res, R def dup_resultant(f, g, K): \"\"\"Computes resultant",
"of `f` given a Mobius transform. \"\"\" F, i = K.get_field(), 0 while",
"_dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43,",
"dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g, u) > 0: result.append((g, i))",
"cont, v = K.zero, u-1 for c in f: gc = dmp_rr_ground_content(c, v,",
"for i, r in enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r in",
"\"\"\"Square-free norm of `f` in `K[x]`, useful over algebraic domains. \"\"\" if not",
"== 1: return (cx, cy, hx, hy, (F11, F12, F13, F14)) # Quadrant",
"if not r: h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff",
"dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in `K[Y]`.",
"dx, dy, (F1, F2, F3, F4))) elif k > 1: stack.append((x, y, dx,",
"r2 while not ((x2 >= x1+dx1 or x2+dx2 <= x1) and (y2 >=",
"or dg == 0: return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm",
"v) in I_pos ]) I_pos, I_neg = [], [] F_pos, F_neg = {},",
"F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14,",
"def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if not",
"K) cfg = dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f,",
"dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v, -u), k)",
"g = dup_taylor(f, K.one, K), f a1, b1, c1, d1 = a, a+b,",
"c, K) h = dup_add(h, q, K) return h def dup_compose(f, g, K):",
"k2 = dup_sign_variations(f2, K) if k1 < k2: a1, a2, b1, b2 =",
"`f` given a Mobius transform. \"\"\" F, i = K.get_field(), 0 while not",
"0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative of a",
"approach. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif",
"dup_monic(f, K) return a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm in",
"return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u, K))",
"an interval `(s, t)`. \"\"\" if s == t: return (s, t) F",
"dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there",
"elif k3 > 1: stack.append((x, y, hx, hy, k3, F31, F32, F33, F34))",
"@cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if",
"i in xrange(0, m): c, n = c*K(n), n-1 for coeff in f[:-m]:",
"functional decomposition of `f` in `K[x]`. Given an univariate polynomial `f` with coefficients",
"o (g - b)` 2. `x**n o x**m = x**m o x**n` 3.",
"t: return (s, t) if s > t: s, t = t, s",
"u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a square-free polynomial",
"In this case you will need to switch to another GCD method. The",
"K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f,",
"f ], u) @cythonized(\"u,v\") def dmp_ground_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo",
"[] result, i = [], 1 h = dup_diff(f, 1, K) g, p,",
"K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n, b = list(f),",
"= dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f:",
"K): \"\"\"Computes subresultant PRS of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g,",
"K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers",
"1, K) a, b, c, d = b, a+b, d, c+d i +=",
"if g is not None: return g, h return None def dup_decompose(f, K):",
"if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1), cond, fast, K))",
"dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul,",
"groups[x] = [(x, y, dx, dy)] upper, lower = [], [] for group",
"\"\"\"Evaluate a polynomial at `x_j = a` in `K[X]` using Horner scheme. \"\"\"",
"p) else: g.append(c) else: g = [ c % p for c in",
"cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in `Q[X]`. \"\"\"",
"dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors import",
"n: eps = args.get('eps') if eps is not None: for i, (x, y,",
"extended Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can be",
"dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative in `x_j` of a polynomial",
"(g, i), rest = result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g,",
"coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c, K(n+m)), n-1 return deriv @cythonized(\"u,v,m,n,i\")",
"dmp_zero_p(f, u): return K.zero, f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u,",
"F4 k2 = _dup_inner_zeros(F21, F22, F23, F24, hx, hy, K) if k2 ==",
"= len(f), K.one, [] if dup_LC(f, K) < 0: f = dup_neg(f, K)",
"= dmp_inner_gcd(p, h, u, K) if all or dmp_degree(g, u) > 0: result.append((g,",
"f else: return cont, [ dmp_exquo(c, cont, v, K) for c in f",
"fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc,",
"coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True)",
"dmp_zeros(m, u-1, K), u-1 for i, c in enumerate(reversed(f)): n = i+1 for",
"of at least second degree. Unlike factorization, complete functional decompositions of polynomials are",
"HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper",
"dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\") def",
"x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K): \"\"\"Refine a",
"cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K) if not",
"\"\"\"Square-free norm of `f` in `K[X]`, useful over algebraic domains. \"\"\" if not",
"dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f,",
"result is not None: return result df = dmp_degree(f, u) dg = dmp_degree(g,",
"y, dx, dy, k, F1, F2, F3, F4)) while stack: x, y, dx,",
"K1, K0) c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0)",
"========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms for Algebraic",
"g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K)",
"cont @cythonized(\"u\") def dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a field.",
"K.one k = dup_sign_variations(f, K) if k == 0: return [] if k",
"= K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g,",
"in `K`. \"\"\" if not u: return dup_trunc(f, p, K) v = u-1",
"def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if not",
"if len(factors) > 1: for i, (f1, r1, k1) in enumerate(roots): x1, y1,",
"is a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True else:",
"else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g,",
"K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v,",
"compute disjoint positive root isolation intervals. \"\"\" a, b, c, d = K.one,",
"R, B, D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) > 0:",
"\"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" if not u: return",
"(h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K): \"\"\"Heuristic polynomial GCD",
"K.one, f def dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial in `K[x]`.",
"in f[1:]: cont = dmp_gcd(cont, c, v, K) if dmp_one_p(cont, v, K): break",
"GCD using subresultants over a field. \"\"\" if not u: return dup_ff_prs_gcd(f, g,",
"dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f else: return cont, [",
"if negative: return (-t, -s) else: return ( s, t) def dup_inner_isolate_real_roots(f, cond,",
"F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx,",
"(( u, v), k) for (u, v, k) in I_pos ]) def _dup_inner_sturm(f,",
"= u - 1 h = dmp_gcd(F, G, v, K) cff = [",
"== 1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f",
"if not u: return dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K)",
"1. `f o g = f(x + b) o (g - b)` 2.",
"K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns",
"w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K)",
"(_, f), K = dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real",
"K): \"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\" if not f: return",
"if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) gcd = dmp_gcd(f, dmp_diff(f,",
"K) b = dmp_ground_LC(g, u, K) v = u - 1 B =",
"\"\"\"Computes polynomial LCM of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or",
"(df or dg): F = dmp_LC(f, K) G = dmp_LC(g, K) else: if",
"if not d: q = c else: q = dmp_pow(c, d-1, v, K)",
"cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K)",
"derivative of a polynomial in `K[x]`. \"\"\" if m <= 0: return f",
"g, K) h = dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def dmp_compose(f,",
"f = dup_neg(f, K) coeff = -coeff if dup_degree(f) <= 0: if args.get('include',",
"k) for (u, v) in I_neg ] + \\ [ (( u, v),",
"global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain()",
"in `K[X]`. \"\"\" if dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f,",
"i == j: return dmp_integrate(g, m, v, K) w, i = v-1, i+1",
"return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u,",
"p, P = dmp_zero(v), K.one, K.one while P <= B: p = K(nextprime(p))",
"dmp_prem(f, g, u, K) h = [ dmp_exquo(ch, b, v, K) for ch",
"r = dup_div(f, h, K) if dup_degree(r) > 0: return None else: g[i]",
"_rec_diff_in(c, m, w, i, j, K) for c in g ], v) @cythonized(\"m,j,u\")",
"resultant of two polynomials in `K[X]`. \"\"\" if not u: return dup_resultant(f, g,",
"r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c, K(s),",
"def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a ring in `K[X]`.",
"D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of two polynomials",
"\"\"\" if not u: return dup_integrate(f, m, K) if m <= 0 or",
"= dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K)",
"= dmp_compose(f, F, u, K), s+1 return s, f, r def dup_sqf_part(f, K):",
"R, B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant PRS of two polynomials",
"k)) if len(factors) > 1: for i, (f1, r1, k1) in enumerate(roots): x1,",
"c) - F(b, d)) < eps else: cond = lambda a, b, c,",
"if not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K)",
"R, _collins_crt, (P, p, K), v, K) P *= p return r @cythonized(\"u,n,m\")",
"u, K)[1] cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_,",
"K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain() f = dup_convert(f, K0, K)",
"F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K) F42",
"(a % p) or not (b % p): p = K(nextprime(p)) F =",
"return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's global",
"cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a",
"1, u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of",
"polynomial modulo a constant `p` in `K`. \"\"\" if K.is_ZZ: g = []",
"\"\"\" if not u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground domain",
"K.quo(res*p, q) return res, R def dup_resultant(f, g, K): \"\"\"Computes resultant of two",
"u: return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i+1, A, u,",
"k1 if k1 == 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1,",
"dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant",
"= (u, v, k) return sorted([ ((-v, -u), k) for (u, v, k)",
"h, K) if dup_degree(r) > 0: return None else: g[i] = dup_LC(r, K)",
"coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s positive",
"K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not args.get('convert'):",
"in enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]): while not (s >=",
"dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not",
"K): \"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise",
"not (df or dg): F = dmp_LC(f, K) G = dmp_LC(g, K) else:",
"@cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a primitive polynomial. \"\"\"",
"[ dup_mirror(f, K) for f in F ] def _dup_inner_zeros(F1, F2, F3, F4,",
"/ bound else: return None def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast,",
"dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f if K.has_Field or not K.is_Exact:",
"dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u, K) v = u - 1",
"F(b, d), F(b, d) f, g = dup_taylor(f, K.one, K), f a1, b1,",
"j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f, m, a,",
"K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while True: h,",
"cy = x + hx, y + hy Fx = _dup_inner_sturm(f, K.one, K.zero,",
"F(b, d) f, g = dup_taylor(f, K.one, K), f a1, b1, c1, d1",
"not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p",
"in `Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`, returns their GCD",
"K) if not dup_eval(f, K.zero, K): f = dup_rshift(f, 1, K) a, b,",
"RefinementFailed(\"no roots in (%s, %s) x (%s, %s) rectangle\" % (x, y, x+dx,",
"y, dx, dy, _), k) in roots: multiplicity[(x, y, dx, dy)] = k",
"if not u: return dup_diff(f, m, K) if m <= 0: return f",
"dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u,",
"K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed:",
"= dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t,",
"K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm in",
"not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed:",
"= b, a+b, d, c+d if k2 > 1 or (k1 > 0",
"u, K0) return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def",
"break return cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over a field.",
"= dup_outer_refine_real_root(F_neg[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t,",
"K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K)",
"u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of sign variations of",
"K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\"",
"`K[x]`. Given an univariate polynomial `f` with coefficients in a field of characteristic",
"if k == 1: a, b, c, d = a1, b1, c1, d1",
"The final step is to verify if the result is the correct GCD.",
"b1, c1, d1, r = a, a+b, c, c+d, 0 if not dup_eval(f1,",
"in dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g = dup_mirror(f, K) for",
"u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast,",
"A*c + d if not dup_eval(f, K.zero, K): return F(b, d), F(b, d)",
"in f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c, K(n+m)),",
"dup_mul_ground(h, b, K) while h: k = dup_degree(h) R.append(h) lc = dup_LC(g, K)",
"not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not args.get('convert'): return common, f",
"roots: multiplicity[(x, y, dx, dy)] = k roots = multiplicity.keys() groups = {}",
"g) h = (h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g, K):",
"dup_ff_prs_gcd(f, g, K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result is not",
") from sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed,",
"dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c, K(s), v, K)",
"s, K) if h is not None: g = _dup_left_decompose(f, h, K) if",
"if not u: return dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact: coeff",
"_dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if k != n: return dup_inner_isolate_complex_roots(f,",
"y, dx, dy, eps, K): \"\"\"Refine a complex root using Wilf's global bisection",
"h = gcd(f, g), cff = quo(f, h) and cfg = quo(g, h)",
"1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)) continue f1 =",
"x, y, dx, dy, F, eps, K): \"\"\"Refine a complex root until the",
"None: return result df = dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f,",
"sorted(upper, key=lambda r: r[0]) lower = sorted(lower, key=lambda r: r[0]) if not squarefree:",
"0: return [] eps, fast = args.get('eps'), args.get('fast') if eps is not None:",
"dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes",
"returns their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg` such that::",
"@cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p`",
"@cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial in `K[x]`.",
"(s, t, m) I_pos[i] = (u, v, k) for i, (u, v, k)",
"1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant",
"k = dup_sign_variations(f, K) if k == 0: return [] if k ==",
"+ b, A*c + d if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b,",
"K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v, K) h, r",
"d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f, K) if k ==",
"K) if bound is not None: return 1.0 / bound else: return None",
"of `f` in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K) if h",
"a square-free polynomial in `K[x]`. \"\"\" if not f: return True else: return",
"u, K) h = [ dmp_exquo(ch, b, v, K) for ch in h",
"= c2, c1, d2, d1 f1, f2, k1, k2 = f2, f1, k2,",
"dx, dy, k, F1, F2, F3, F4)) while stack: x, y, dx, dy,",
"(-v, -u) for (u, v) in I_neg ] + I_pos) _, factors =",
"for s, t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k]",
"dmp_pow(c, m-k, v, K), v, K) f, g, m, d = g, h,",
"t = t, s negative = False if s < 0: if t",
"i, F: i >= n s, t = dup_outer_refine_real_root(f, s, t, cond, fast,",
"or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g, K) except",
"\"\"\"Computes polynomial LCM over a ring in `K[x]`. \"\"\" fc, f = dup_primitive(f,",
"g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f,",
"def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for s in xrange(2, df): if",
"m v = u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K)",
"or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation of complex roots not supported",
"dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29 x",
"g, K): \"\"\"Computes polynomial LCM over a ring in `K[x]`. \"\"\" fc, f",
"h, k, m-k B.append(b) D.append(d) h = dup_prem(f, g, K) h = dup_exquo_ground(h,",
"f, s = dmp_compose(f, F, u, K), s+1 return s, f, r def",
"`K[X]`. \"\"\" df = dmp_degree(f, u) dg = dmp_degree(g, u) if df >",
"= c % p if c > p // 2: g.append(c - p)",
"= u - 1 n = dmp_degree(f, u) m = dmp_degree(g, u) N",
"return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g,",
"dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)),",
"j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative of a polynomial",
"if result is not None: f, h = result F = [h] +",
"< 0: p = dmp_neg(p, v, K) i = dmp_degree(R[-2], u) res =",
"K) D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K) return",
"computation in `K[X]`. \"\"\" df = dmp_degree(f, u) dg = dmp_degree(g, u) if",
"(f2, (x2, y2, dx2, dy2, F2), k2) roots[i] = (f1, (x1, y1, dx1,",
"dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground,",
"u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of `f`",
"content and a primitive polynomial over a ring. \"\"\" cont = dup_content(f, K)",
"and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g,",
"g, K), K) return dup_mul_ground(h, c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial",
"return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform",
"== 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)) continue f1",
"u) N = dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B =",
"u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\"",
"def dup_transform(f, p, q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`.",
"K) for cg in g ] return [h], cff, cfg def dup_rr_prs_gcd(f, g,",
"**args): \"\"\"Returns square-free decomposition of a polynomial in `K[x]`. \"\"\" if K.has_Field or",
"dup_sign_variations(f, K): \"\"\"Compute the number of sign variations of `f` in `K[x]`. \"\"\"",
"= a, a+b, c, c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1),",
"u): return f h = [f[0]] for c in f[1:]: h = dmp_mul(h,",
"\"\"\" if j < 0 or j > u: raise IndexError(\"-%s <= j",
"u) m = dmp_degree(g, u) if n < 0 or m < 0:",
"K) v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P =",
"j: return dmp_diff(g, m, v, K) w, i = v-1, i+1 return dmp_strip([",
"at `x_j = a` in `K[X]` using Horner scheme. \"\"\" if j <",
"if K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients over",
"**args): \"\"\"Returns square-free decomposition of a polynomial in `K[X]`. \"\"\" if not u:",
"= dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c h = dup_mul_ground(h, c,",
"for g, k in factors: g = dup_convert(g, K, F) for r in",
"s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] = (s, t,",
"K.zero for j in xrange(0, i): if not n+j-i in f: continue if",
"approximating interval to the given precision. \"\"\" if K.is_QQ: (_, f), K =",
"<= 0: if args.get('include', False): return f else: return coeff, [] result, i",
"== -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u,",
"and homogeneous polynomials of at least second degree. Unlike factorization, complete functional decompositions",
"dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement not supported",
"univariate, square-free polynomial `f(x)` returns the associated Sturm sequence `f_0(x), ..., f_n(x)` defined",
"= dmp_gcd(f, dmp_diff(f, 1, u, K), u, K) sqf = dmp_exquo(f, gcd, u,",
"dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2] == [K.one]: return (dup_LC(R[-1], K),",
"in I_pos ]) def _dup_inner_sturm(f, p, q, x, y, K): \"\"\"Compute Sturm sequence",
"k in factors: g = dup_convert(g, K, F) for r in dup_inner_isolate_complex_roots(g, F,",
"\"\"\" if not f or not g: return (K.zero, []) R, B, D",
"a, v, i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def",
"not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v,",
"PRS algorithm in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g, K) n",
"dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff,",
"@cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a",
"until the desired precision is reached. \"\"\" while dx >= eps and dy",
"\"\"\" if not u: return dup_zz_heu_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u,",
"K0) cff = dmp_mul_ground(cff, K0.quo(c, cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg),",
"return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite",
"dup_to_raw_dict, dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term,",
"dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at `x_j = a_j, ...` in",
"[] h = [f[0]] for c in f[1:]: h = dup_mul(h, g, K)",
"= dup_exquo_ground(g, gcd, K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u,",
"k) for (u, v, k) in I_pos ]) def _dup_inner_sturm(f, p, q, x,",
"K.is_one(cont): return cont, f else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def",
"for ch in h ] return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g,",
"c*K(n), n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c,",
"should be exactly one root on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f,",
"K0.quo(c, cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD =",
"0: return K.zero else: s = (-1)**((d*(d-1)) // 2) c = dup_LC(f, K)",
"randfloat() if r < 0.5: break x, y, dx, dy = -B+r, -B-r,",
"hy, K) if k3 == 1: roots.append((x, y, hx, hy, (F31, F32, F33,",
"c, d, f, k = stack.pop() A = dup_root_lower_bound(f, K) if A is",
"s, t, step, fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i] = (u,",
"return sum(v1 - v0 for v1, v0 in zip(V1, V0)) // 2 def",
"and computing (fast) integer GCD of those evaluations. The polynomial GCD is recovered",
"- m v = u - 1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v,",
"K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g =",
"K) result = _dmp_ff_trivial_gcd(f, g, u, K) if result is not None: return",
"cff_, r = dup_div(f, h, K) if not r: h = dup_mul_ground(h, gcd,",
"K): \"\"\"Reduce `K[X]` polynomial modulo a constant `p` in `K`. \"\"\" if not",
"v, K), a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c,",
"return dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)): return f,",
"[d] if not f or not g: return R, B, D h =",
"b = b*f[i], b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor",
"1 if not args.get('include', False): return coeff, result else: (g, i), rest =",
"h = dup_mul_ground(h, b, K) while h: k = dup_degree(h) R.append(h) lc =",
"0 or not f: return f g = [K.zero]*m for i, c in",
"dmp_exquo(f, gcd, u, K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K)",
"K) r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v, K)",
"dy)] = k roots = multiplicity.keys() groups = {} for (x, y, dx,",
"K) q = dmp_one(v, K) for b, d in zip(B, D)[:-1]: du =",
"K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases",
"DomainError(\"isolation of complex roots not supported over %s\" % K) squarefree = args.get('sqf',",
"not h: result.append((p, i)) break g, p, q = dup_inner_gcd(p, h, K) if",
"[K.one] else: return dup_neg(g, K), [], [-K.one] elif not g: if K.is_nonnegative(dup_LC(f, K)):",
"dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u,",
"be done only in a field') a, b = [K.one], [] while g:",
"-1, -1): f[i], a = a*f[i], -a return f def dup_scale(f, a, K):",
"u, K): \"\"\"Computes indefinite integral of `f` in `x_0` in `K[X]`. \"\"\" if",
"not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m = dmp_degree(g,",
"K): roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1, 1, K), 1 k1",
"t: return (s, t) else: return (t, s) def dup_outer_refine_real_root(f, s, t, cond,",
"dmp_LC(f, K), u-1 for coeff in f[1:]: result = dmp_mul_ground(result, a, v, K)",
"zip(f[1:], Q[1:]): h = dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h",
"_dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1, F2, F3, F4) x, y,",
"dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a polynomial in `K[X]`. \"\"\" if",
"xrange(n, 0, -1): for j in xrange(0, i): f[j+1] += a*f[j] return f",
"`Q[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if n <",
"\"\"\"Returns content and a primitive polynomial over a ring. \"\"\" cont = dup_content(f,",
"dx2, dy2, F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1] =",
"if dmp_zero_p(f, u): return K.zero, f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f,",
"result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff = dup_exquo(f,",
"dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`. \"\"\" f, n, a =",
"= [f, g] d = n - m b = (-K.one)**(d+1) c =",
"y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2,",
"K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`, useful",
"in `F[x]/(g(x))`. \"\"\" s, h = dup_half_gcdex(f, g, K) if h == [K.one]:",
"1: stack.append((x, y, dx, dy, k, F1, F2, F3, F4)) while stack: x,",
"for (x, y, dx, dy) in roots: if x in groups: groups[x].append((x, y,",
"d), F(b, d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if",
"luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result =",
"== u: return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c, i+1, A,",
"x, y, dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy, F, K)",
"@cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a polynomial in `K[X]`.",
"dup_taylor(f, b, C) f = dup_scale(f, a, C) u = dup_strip([ C.real(c) for",
"-1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K,",
"P *= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular",
"= 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x,",
"v or t <= u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast,",
"algorithm. \"\"\" if K.is_ZZ or K.is_QQ: K0, K = K, K.float_domain() f =",
"K.is_Exact: coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) else: coeff,",
"negative = False if s < 0: if t <= 0: f, s,",
"= dmp_ground_to_ring(g, u, K0, K1) f = dmp_convert(f, u, K0, K1) g =",
"in f ]) seq = [u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1],",
"v: for c in g: common = K1.lcm(common, K0.denom(c)) else: w = v-1",
"y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K) if k",
"p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p` in `K`. \"\"\" if",
"2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute LMQ lower bound for `f`'s positive roots. \"\"\"",
"def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f,",
"hx, hy, (F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1,",
"n = c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c, n = K(n)*K.exquo(c,",
"domains. \"\"\" if not u: return dup_sqf_norm(f, K) if not K.is_Algebraic: raise DomainError(\"ground",
"y, dx, dy, F def dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine",
"return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of `f` and",
"result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is not None: return result",
"a positive root of `f` given an interval `(s, t)`. \"\"\" if s",
"K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1, r = dup_rshift(f1, 1, K), 1",
"polynomial LCM over a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K),",
"h, _ = dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h, u+1, K.dom)",
"u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K)",
"dx, dy)] upper, lower = [], [] for group in groups.values(): while len(group)",
"K0) if not args.get('convert'): return common, f else: return common, dmp_convert(f, u, K0,",
"else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K) P *=",
"v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont for c in",
"\"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while h: g",
"1: stack.append((x, cy, hx, hy, k2, F21, F22, F23, F24)) # Quadrant #3:",
"+ hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx, cy, K) Fy = _dup_inner_sturm(f,",
"pair of polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc =",
"integral of `f` in `x_j` in `K[X]`. \"\"\" if j < 0 or",
"int: cond = lambda a, b, c, d, i, F: abs(F(a, c) -",
"u, K) gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h",
"c, n = c*K(n), n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff, c,",
"u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a",
"K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f, K, **args): \"\"\"Compute disjoint complex",
"K.one, K) if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K) k2",
"> 1: stack.append((cx, y, hx, hy, k4, F41, F42, F43, F44)) if len(roots)",
"\"\"\" if not K.is_Algebraic: raise DomainError('computation can be done only in an algebraic",
"K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f,",
"((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f,",
"cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants",
"evaluations. The polynomial GCD is recovered from the integer image by interpolation. The",
"h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K) t =",
"fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1] =",
"return (cx, y, hx, hy, (F41, F42, F43, F44)) raise RefinementFailed(\"no roots in",
"hx, hy, k2, F21, F22, F23, F24)) # Quadrant #3: -- F31 =",
"if r < 0.5: break x, y, dx, dy = -B+r, -B-r, 2*B+r,",
"s, t, n, K, **args): \"\"\"Refine real root's approximating interval to the given",
"`K[x]` using subresultant PRS. \"\"\" if not f or not g: return (K.zero,",
"b = (-K.one)**(d+1) c = -K.one B, D = [b], [d] if not",
"K), i, v, K) res = dmp_quo(dmp_mul(res, p, v, K), q, v, K)",
"LCM over a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K),",
"if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u):",
"u) if n < m: return dmp_zero(u) deriv, c, v = [], K.one,",
"u, K): \"\"\"Extracts common content from a pair of polynomials in `K[X]`. \"\"\"",
"in `K[X]`. \"\"\" if j < 0 or j > u: raise IndexError(\"-%s",
"K) h, r = dup_div(f, cff, K) if not r: cfg_, r =",
"(ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if not u:",
"u, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[X]`. \"\"\" if",
"gcd, u, K) return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition",
"roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K)",
"if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg",
"1, u, K), u, K) sqf = dmp_exquo(f, gcd, u, K) if K.has_Field",
"<= B: p = K(nextprime(p)) while not (a % p) or not (b",
"dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u, K) h = dmp_subresultants(f, g,",
"} r = n // s for i in xrange(1, s): coeff =",
"GCD in `Z[x]`. Given univariate polynomials `f` and `g` in `Z[x]`, returns their",
"in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is not",
"K)) else: stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K,",
"K0.denom(c)) else: w = v-1 for c in g: common = K1.lcm(common, _rec_ground_to_ring(c,",
"dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw, v, K), v, K)",
"K) else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]`",
"u) if n < 0 or m < 0: return dmp_zero(u-1) K1 =",
"in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a",
"K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K),",
"dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f,",
"= _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3",
"a polynomial in `K[x]`. \"\"\" if m <= 0: return f n =",
"for cf in f ] cfg = [ dmp_exquo(cg, h, v, K) for",
"None: return result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg,",
"dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f, u) <= 0: if args.get('include',",
"of complex roots not supported over %s\" % K) squarefree = args.get('sqf', False)",
"x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u,",
"2*max(abs(c)/lc for c in f) while True: r = randfloat() if r <",
"`q**n * f(p/q)` in `K[x]`. \"\"\" if not f: return [] h, Q",
"u = dup_strip([ C.real(c) for c in f ]) v = dup_strip([ C.imag(c)",
"a real number `c`. \"\"\" return [ dup_taylor(f, c, K) for f in",
"_rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g,",
"dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate",
"K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation",
"b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently Taylor shift `f(x +",
"K) if dmp_zero_p(f, u): return f h = [f[0]] for c in f[1:]:",
"r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2 = k",
"u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f`",
"K, K.float_domain() f = dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex roots",
"= dup_degree(f) for s in xrange(2, df): if df % s != 0:",
"if k4 == 1: return (cx, y, hx, hy, (F41, F42, F43, F44))",
"f: return [] h = [f[0]] for c in f[1:]: h = dup_mul(h,",
"c in f: cont = K.gcd(cont, c) if K.is_one(cont): break return cont def",
"F31, F32, F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K)",
"dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f,",
"are monic and homogeneous polynomials of at least second degree. Unlike factorization, complete",
"= (u, v, k) for i, (u, v, k) in enumerate(I_neg): for j,",
"[K.one], [] while g: q, r = dup_div(f, g, K) f, g =",
"F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2, y2, dx2, dy2,",
"dmp_eval(r, a, v, K) if not v: R = dup_strip([R]) e = dup_strip([e])",
"raise DomainError(\"isolation of complex roots not supported over %s\" % K) F1 =",
"v, i, j, K) for c in g ], v) @cythonized(\"u\") def dmp_eval_in(f,",
"c, d, i, F): A = dup_root_lower_bound(f, K) if A is not None:",
"dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if K.has_Field",
"= dmp_content(f, u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return",
"the direction of a Sturm sequence at its origin. \"\"\" return [ dup_mirror(f,",
"== 0: return [] if k == 1: roots = [dup_inner_refine_real_root( f, (a,",
"v = u - 1 h = dmp_gcd(F, G, v, K) cff =",
"v, K) h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_,",
"\"\"\" if not u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f,",
"F3 = _dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy,",
"(s, t)) fast = args.get('fast') if type(n) is not int: cond = lambda",
"return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a, K): \"\"\"Evaluate a",
"positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return",
"\"\"\" d = dup_degree(f) if d <= 0: return K.zero else: s =",
"F: i >= n s, t = dup_outer_refine_real_root(f, s, t, cond, fast, K)",
"v, K): return cont, f else: return cont, [ dmp_exquo(c, cont, v, K)",
"\"\"\"Returns square-free decomposition of a polynomial in `K[X]`. \"\"\" if not u: return",
"i >= n s, t = dup_outer_refine_real_root(f, s, t, cond, fast, K) if",
"@cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i == j:",
"f2, k1, k2 = f2, f1, k2, k1 if k1 == 0: continue",
"in GCD algorithm over a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g =",
"K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom)",
"else: return dmp_rr_ground_content(f, u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive",
"randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`.",
"else: return dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial",
"F44)) raise RefinementFailed(\"no roots in (%s, %s) x (%s, %s) rectangle\" % (x,",
"(-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u,",
"g.insert(0, K.quo(c, K(n))) return g @cythonized(\"m,u,v,n,i,j\") def dmp_integrate(f, m, u, K): \"\"\"Computes indefinite",
"r a, b = b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f,",
"v = dmp_LC(f, K), u-1 for coeff in f[1:]: result = dmp_mul_ground(result, a,",
"cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g, u, K0,",
"a, b, c, d = a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g),",
"in `K[X]`. \"\"\" if not u: return dup_integrate(f, m, K) if m <=",
"algorithm in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g, K) n =",
"a1, a2, b1, b2 = a2, a1, b2, b1 c1, c2, d1, d2",
"b, d = A*a + b, A*c + d if not dup_eval(f, K.zero,",
"C(x, y) f = dup_convert(f, K, C) f = dup_taylor(f, b, C) f",
"supported over %s\" % K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K)",
"dmp_diff(g, m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m,",
"The polynomial GCD is recovered from the integer image by interpolation. The evaluation",
"\"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes polynomial",
"p, q = dup_inner_gcd(p, h, K) if all or dup_degree(g) > 0: result.append((g,",
"def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM of `f` and `g` in",
"K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x = a` in",
"> p // 2: g.append(c - p) else: g.append(c) else: g = [",
"= f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) and `f_2, ...,",
"d1) k = dup_sign_variations(f, K) if k == 1: a, b, c, d",
"result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return result df",
"g, h, k, m-k B.append(b) D.append(d) h = dup_prem(f, g, K) h =",
"K) while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g,",
"F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1 F32 =",
"u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h =",
"g, K) if h == [K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero",
"A, K) b, d = A*a + b, A*c + d if not",
"= dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f, h, K) all =",
"K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of sign variations",
"polynomials as a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of",
"dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return x, y, dx, dy, F",
"g = dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g, K1) h",
"[], 1 h = dmp_diff(f, 1, u, K) g, p, q = dmp_inner_gcd(f,",
"= R else: r = dmp_apply_pairs(r, R, _collins_crt, (P, p, K), v, K)",
"1 h = dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf, h, v,",
"d))) f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k ==",
"t + a - K.log(f[j], 2) Q.append(q // (j - i)) t +=",
"\"\"\"Refine a complex root until the desired precision is reached. \"\"\" while dx",
"(y2 >= y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1, dy1, F1 =",
"= dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f, g, K) if",
"not f: return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns",
"in I_neg ] + \\ [ (( u, v), k) for (u, v)",
"f = list(reversed(f)) for i in xrange(0, n): if f[i] >= 0: continue",
"J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f,",
"<= t: return (s, t) else: return (t, s) def dup_outer_refine_real_root(f, s, t,",
"gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if K.is_one(cont): break return",
"u, K): \"\"\"Try to eliminate `x_0` from GCD computation in `K[X]`. \"\"\" df",
"USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD",
"f a1, b1, c1, d1 = a, a+b, c, c+d if not dup_eval(f,",
"cond, fast, K)] else: roots, stack = [], [(a, b, c, d, f,",
"v = u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h,",
"\"\"\"Advanced tools for dense recursive polynomials in `K[x]` or `K[X]`. \"\"\" from sympy.polys.densebasic",
"K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy,",
"f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f, common, K0)",
": K.one } r = n // s for i in xrange(1, s):",
"= dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q, v, K) b =",
"1 h = dup_diff(f, 1, K) g, p, q = dup_inner_gcd(f, h, K)",
"q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _, p, q =",
"not f or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont, K)",
"on (%s, %s)\" % (s, t)) fast = args.get('fast') if type(n) is not",
"= dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise",
"g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]`",
"polynomial over a ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f else: return",
"cofactors as a side effect. References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of",
"= dmp_div(f, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u,",
"F23 = _dup_sturm_shift(F3, hx, K) F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23,",
"multiplicity[(x, y, dx, dy)] = k roots = multiplicity.keys() groups = {} for",
"not K.is_Exact: return dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f,",
"K)] elif not g: return dup_monic(f, K), [dup_LC(f, K)], [] else: return None",
"dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f, h, u, K) cfg =",
"K) return h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise",
"[(a, b, c, d, f, k)] F = K.get_field() while stack: a, b,",
"K)): f = dup_neg(f, K) coeff = -coeff if dup_degree(f) <= 0: if",
"= dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d, v, K) if not",
"= dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s))",
"of `f` and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if",
"%s\" % (u, u, j)) return _rec_diff_in(f, m, u, 0, j, K) def",
"29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g,",
"h, cff, cfg @cythonized(\"u\") def dmp_qq_heu_gcd(f, g, u, K0): \"\"\"Heuristic polynomial GCD in",
"= dup_convert(f, K, C) f = dup_taylor(f, b, C) f = dup_scale(f, a,",
"h = dup_mul_ground(h, gcd, K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x,",
"hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 =",
"roots[i+j+1] = (f2, (x2, y2, dx2, dy2, F2), k2) roots[i] = (f1, (x1,",
"if not dup_eval(f, K.zero, K): return F(b, d), F(b, d) f, g =",
"> 16: f = dup_scale(f, A, K) a, c, A = A*a, A*c,",
"v, K)) return g @cythonized(\"m,v,w,i,j\") def _rec_integrate_in(g, m, v, i, j, K): \"\"\"XXX\"\"\"",
"= result[0], result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest",
"+ hx, y + hy F1, F2, F3, F4 = F Fx =",
"return cont, f else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f,",
"if K.has_Field or not K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f, K)",
"coefficients in a field of characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`,",
"= dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c = dmp_mul_ground(c, K(s), v,",
"j: return dmp_integrate(g, m, v, K) w, i = v-1, i+1 return dmp_strip([",
"result = _dup_decompose(f, K) if result is not None: f, h = result",
"b, c, d), cond, fast, K): \"\"\"Refine a positive root of `f` given",
"c, 0, u, K) h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h,",
"y, dx, dy)) del group[i] break upper = sorted(upper, key=lambda r: r[0]) lower",
"g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for `dmp_inner_gcd()`. \"\"\"",
"LMQ lower bound for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if",
"= _dup_rr_trivial_gcd(f, g, K) if result is not None: return result fc, F",
"if not j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f,",
"dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\")",
"for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg =",
"K.one while P <= B: p = K(nextprime(p)) while not (a % p)",
"step is to verify if the result is the correct GCD. This gives",
"dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {}, 0",
"f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra",
"is not None: f, h = result F = [h] + F else:",
"K): \"\"\"Refine a positive root of `f` given an interval `(s, t)`. \"\"\"",
"[], [] for monom, coeff in F.iteritems(): if not coeff.is_ground: monoms.append(monom) perms =",
"by:: f_0(x), f_1(x) = f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== ..",
"< k2: a1, a2, b1, b2 = a2, a1, b2, b1 c1, c2,",
"**args): \"\"\"Compute disjoint complex root isolating rectangles for all quadrants. \"\"\" n, lc",
"v) B, D = [b], [d] if dmp_zero_p(f, u) or dmp_zero_p(g, u): return",
"\"\"\"Reduce `K[X]` polynomial modulo a constant `p` in `K`. \"\"\" if not u:",
"if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return",
"algorithm in `Q[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if",
"a1, b1, c1, d1, r = a, a+b, c, c+d, 0 if not",
"\"\"\" fc, f = dup_primitive(f, K) gc, g = dup_primitive(g, K) c =",
"dmp_pow(lc, du-dw, v, K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K),",
"% p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u, K) G =",
"`cff` and `cfg` such that:: h = gcd(f, g), cff = quo(f, h)",
"C = K.complex_domain() a, b = C(p, q), C(x, y) f = dup_convert(f,",
"GCD using subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if",
"< %s expected, got %s\" % (u, u, j)) return _rec_eval_in(f, a, u,",
"dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field:",
"K) for c in g ] if i < u - len(A) +",
"`h`, `cff` and `cfg` such that:: h = gcd(f, g), cff = quo(f,",
"<NAME>, Evaluation of the heuristic polynomial GCD, International Symposium on Symbolic and Algebraic",
"[]) R, B, D = dmp_inner_subresultants(f, g, u, K) if dmp_degree(R[-1], u) >",
"only in a field') f = dup_sqf_part(f, K) sturm = [f, dup_diff(f, 1,",
"dup_taylor(f, A, K) b, d = A*a + b, A*c + d if",
"v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial",
"== j: return dmp_integrate(g, m, v, K) w, i = v-1, i+1 return",
"cond, fast, K): \"\"\"Refine a positive root of `f` given an interval `(s,",
"u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]` using",
"K) try: R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if",
"K) h = dup_exquo_ground(h, b, K) return R, B, D def dup_subresultants(f, g,",
"gc, g = dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u, K)[-1] c,",
"% (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps,",
"== 0 or dg == 0: return [gcd], f, g f_norm = dup_max_norm(f,",
"@cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two polynomials in `K[X]`.",
"bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain() else: raise DomainError(\"isolation",
"dup_rshift(f2, 1, K) k2 = dup_sign_variations(f2, K) if k1 < k2: a1, a2,",
"h = _dup_right_decompose(f, s, K) if h is not None: g = _dup_left_decompose(f,",
"K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial in",
"K) if not dup_eval(f2, K.zero, K): f2 = dup_rshift(f2, 1, K) k2 =",
"PRS. \"\"\" if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or",
"dmp_ff_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a field. \"\"\" if not",
"= 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)),",
"m = dmp_degree(g, u) if n < m: f, g = g, f",
"`F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can be done only in a",
"dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC,",
"dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def",
"0: return [gcd], f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K)",
"discriminant of a polynomial in `K[x]`. \"\"\" d = dup_degree(f) if d <=",
"3. `T_n o T_m = T_m o T_n` where `T_n` and `T_m` are",
"dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K)",
"= max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K)))",
"= variations([-1, 1], len(monoms), repetition=True) for perm in perms: G = dict(F) for",
"K): \"\"\"Extracts common content from a pair of polynomials in `K[X]`. \"\"\" fc",
"is purely heuristic which means it may fail to compute the GCD. This",
"`T_n o T_m = T_m o T_n` where `T_n` and `T_m` are Chebyshev",
"f in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4",
"(k1 > 0 and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if",
"K), i+1 p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s <",
"for f in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for f in",
"dup_add_term, dmp_add_term, dup_mul_term, dmp_mul_term, dup_lshift, dup_rshift, dup_neg, dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul,",
"f = dup_rshift(f, 1, K) k = dup_sign_variations(f, K) if k == 0:",
"if k3 == 1: roots.append((x, y, hx, hy, (F31, F32, F33, F34))) elif",
"// s for i in xrange(1, s): coeff = K.zero for j in",
"h = dup_convert(h, K1, K0) c = dup_LC(h, K0) h = dup_monic(h, K0)",
"def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K): \"\"\"Refine a positive root",
"u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast,",
"algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if",
"v, K) if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont,",
"u, K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g, u, K) B",
"sequence at its origin. \"\"\" return [ dup_mirror(f, K) for f in F",
"field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and",
"in f ] cfg = [ dmp_exquo(cg, h, v, K) for cg in",
"`K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can be done only in an",
"% p, p) v = u - 1 n = dmp_degree(f, u) m",
"else: return cont, dmp_exquo_ground(f, cont, u, K) @cythonized(\"u\") def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns",
"= n // s for i in xrange(1, s): coeff = K.zero for",
"h, v, K) for cf in f ] cfg = [ dmp_exquo(cg, h,",
"dup_sqf_list(f, K) for g, k in factors: g = dup_convert(g, K, F) for",
"K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K)",
"f, K) t = dup_exquo(F, g, K) return s, t, h def dup_invert(f,",
"dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return x, y, dx, dy",
"b) o (g - b)` 2. `x**n o x**m = x**m o x**n`",
"dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K) t = dup_exquo(F, g,",
"s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while True: h, _ =",
"= dup_sign_variations(f1, K) k2 = k - k1 - r a2, b2, c2,",
"u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u)",
"`K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f,",
"cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant #1:",
"D h = dmp_prem(f, g, u, K) h = dmp_mul_term(h, b, 0, u,",
"= dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u,",
"`f(x + a)` in `K[x]`. \"\"\" f, n = list(f), dup_degree(f) for i",
"`K[X]`. \"\"\" if not A: return f if dmp_zero_p(f, u): return dmp_zero(u -",
"K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\")",
"done only in an algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [],",
"dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\"",
"f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u,",
"step, fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i] = (u, v, k)",
"\"\"\"Refine real root's approximating interval to the given precision. \"\"\" if K.is_QQ: (_,",
"fast, K) return sorted([ ((-v, -u), k) for (u, v) in I_neg ]",
"1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df = dup_degree(f) for",
"cf), u, K0) cfg = dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff,",
"not (f or g): return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g,",
"h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD",
"g, K) h = dup_exquo_ground(h, b, K) return R, B, D def dup_subresultants(f,",
"`f(g)` in `K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)])",
"f in F4 ], K), ] return sum(v1 - v0 for v1, v0",
"dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h",
"K) if h is not None: g = _dup_left_decompose(f, h, K) if g",
"A >= K.one: f = dup_taylor(f, A, K) b, d = A*a +",
"= dmp_ground_LC(h, u, K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u,",
"polynomial `f(x)` returns the associated Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x),",
"K) def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a ring.",
"f: gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if K.is_one(cont): break",
"not dup_degree(dup_gcd(f, dup_diff(f, 1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True`",
"polynomial in `K[x]`. \"\"\" d = dup_degree(f) if d <= 0: return K.zero",
"K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h,",
"K) return [(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns",
"_dup_ff_trivial_gcd(f, g, K0) if result is not None: return result K1 = K0.get_ring()",
"< 0: k += 1 if coeff: prev = coeff return k def",
"over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not",
"- K.log(f[j], 2) Q.append(q // (j - i)) t += 1 if not",
".. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation 7 (1989),",
"= K1.one for c in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common):",
"lambda a, b, c, d, i, F: i >= n s, t =",
"s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f,",
"K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and cofactors of",
"h = dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K) h =",
"dx, dy, F, K) return x, y, dx, dy, F def dup_refine_complex_root(f, x,",
"<= 0: continue q = t + a - K.log(f[j], 2) Q.append(q //",
"g, K), K) return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM",
"integer. The final step is to verify if the interpolated polynomial is the",
"g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def",
"= dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return x, y, dx,",
"h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg,",
"roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is not None: return 1.0",
"29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K)))",
"A, K) a, c, A = A*a, A*c, K.one if A >= K.one:",
"= x + hx, y + hy Fx = _dup_inner_sturm(f, K.one, K.zero, cx,",
"K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if not u:",
"@cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u, K): \"\"\"Compute resultant of `f` and `g`",
"g, m, d = g, h, k, m-k B.append(b) D.append(d) h = dmp_prem(f,",
"f: return f lc = dup_LC(f, K) if K.is_one(lc): return f else: return",
"u, K0, K1) g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g,",
"dy) in enumerate(group): if y == _min: lower.append((x, y, dx, dy)) del group[i]",
"common, f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0,",
"dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a field in `K[x]`. \"\"\" h",
"u - 1 if not (dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg",
"F = dmp_LC(f, K) G = dmp_content(g, u, K) else: F = dmp_content(f,",
"K, C) f = dup_taylor(f, b, C) f = dup_scale(f, a, C) u",
"I_pos[i] = (u, v, k) for i, (u, v, k) in enumerate(I_neg): for",
"algorithm in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can be done only",
"b, 0, u, K) while not dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h)",
"return s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f`",
"u, K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K)",
"denominators, i.e. transform `K_0` to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0,",
"K) cfg = dup_exquo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g,",
"K0, K1) g = dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u,",
"g is not None: return g, h return None def dup_decompose(f, K): \"\"\"Computes",
"// 2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One bisection step",
"@cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of two polynomials in",
"prev = coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for",
"P, p, K): \"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r,",
"return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g ],",
"in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p, u, K): \"\"\"Reduce `K[X]`",
"dup_compose(f, g, K) if dmp_zero_p(f, u): return f h = [f[0]] for c",
"K) sqf = dmp_exquo(f, gcd, u, K) if K.has_Field or not K.is_Exact: return",
"stack.append((cx, cy, hx, hy, k1, F11, F12, F13, F14)) # Quadrant #2: -+",
"K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g,",
"dy, k, F1, F2, F3, F4 = stack.pop() hx, hy = dx/2, dy/2",
"in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else: return",
"+= (i - r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def",
"cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h,",
"K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K):",
"def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if not v: for",
"cff = quo(f, h) and cfg = quo(g, h) The algorithm is purely",
"fast, K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return",
"= dup_ground_to_ring(f, K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real roots",
"for (u, v) in I_neg ] + \\ [ (( u, v), k)",
"m, v, K) w, i = v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w,",
"dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\" cont",
"if eps is not None: cond = lambda a, b, c, d, i,",
"else: return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over",
"in enumerate(group): if y == _min: lower.append((x, y, dx, dy)) del group[i] break",
"i)] + rest def dup_extract(f, g, K): \"\"\"Extracts common content from a pair",
"K) a1, b1, c1, d1, r = a, a+b, c, c+d, 0 if",
"k1) in enumerate(roots): x1, y1, dx1, dy1, F1 = r1 for j, (f2,",
"return gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K):",
"polynomial GCD using subresultants over a ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K)",
"return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g,",
"K) h = dup_add(h, q, K) return h def dup_compose(f, g, K): \"\"\"Evaluate",
"u: return dup_eval(f, a, K) if not a: return dmp_TC(f, K) result, v",
"lower = sorted(lower, key=lambda r: r[0]) if not squarefree: for i, r in",
"`Z[x]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg` such",
"in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return",
"`f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f,",
"`x_j` in `K[X]`. \"\"\" if j < 0 or j > u: raise",
"B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g,",
"not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u,",
"g, K): \"\"\"Extracts common content from a pair of polynomials in `K[x]`. \"\"\"",
"This gives cofactors of the input polynomials as a side effect. References ==========",
"break else: f, s = dmp_compose(f, F, u, K), s+1 return s, f,",
"B, D = [b], [d] if not f or not g: return R,",
"K.get_field() a, c = F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f =",
"over algebraic domains. \"\"\" if not u: return dup_sqf_norm(f, K) if not K.is_Algebraic:",
"is not None: return g, h return None def dup_decompose(f, K): \"\"\"Computes functional",
"if d <= 0: return K.zero else: s = (-1)**((d*(d-1)) // 2) c",
"g, K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f) m =",
"return g, [], [K.one] else: return dup_neg(g, K), [], [-K.one] elif not g:",
"max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) +",
"in `F[x]`. Given an univariate, square-free polynomial `f(x)` returns the associated Sturm sequence",
"% 2: s = -s lc, i = dmp_LC(R[i], K), i+1 p =",
"K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return (dmp_inflate(h, J, u,",
"+= 1 if not Q: continue P.append(min(Q)) if not P: return None else:",
"-K.one B, D = [b], [d] if not f or not g: return",
"%s) rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx, dy,",
"if dup_degree(r) > 0: return None else: g[i] = dup_LC(r, K) f, i",
"cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer",
"return result fc, F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u,",
"dmp_rr_lcm(f, g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a",
"References ========== .. [Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial GCD, International",
"a)` in `K[x]`. \"\"\" f, n = list(f), dup_degree(f) for i in xrange(n,",
"dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u,",
"g, u, K) h = dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\")",
"not K.is_Exact: return dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def",
"+= 1 if not args.get('include', False): return coeff, result else: (g, i), rest",
"n): if f[j] <= 0: continue q = t + a - K.log(f[j],",
"`K_1`. \"\"\" if K1 is None: K1 = K0.get_ring() common = K1.one for",
"GCD of `f` and `g` in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0]",
"if not u: return dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f,",
"K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J, u,",
"] cfg = [ dmp_exquo(cg, h, v, K) for cg in g ]",
"= max(min(B, 99*K.sqrt(B)), 2*min(f_norm // abs(dup_LC(f, K)), g_norm // abs(dup_LC(g, K))) + 2)",
"x1+dx1 or x2+dx2 <= x1) and (y2 >= y1+dy1 or y2+dy2 <= y1)):",
"K) F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero,",
"= K.zero, 0 for coeff in f: if coeff*prev < 0: k +=",
"dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\"",
"def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of a polynomial in `K[X]`. \"\"\"",
"K): \"\"\"Returns multivariate content and a primitive polynomial. \"\"\" cont, v = dmp_content(f,",
"[]) R, B, D = dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return",
"K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F =",
"i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a, v, K)",
"\"\"\"Divides all coefficients by `LC(f)` in `K[x]`. \"\"\" if not f: return f",
"b2, b1 c1, c2, d1, d2 = c2, c1, d2, d1 f1, f2,",
"dmp_convert(g, u, K0, K1) r = dmp_zz_collins_resultant(f, g, u, K1) r = dmp_convert(r,",
"dup_exquo_ground(h, b, K) return R, B, D def dup_subresultants(f, g, K): \"\"\"Computes subresultant",
"deriv, c = [], K.one for i in xrange(0, m): c, n =",
"b = b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K)",
"dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step,",
"dup_prem(f, g, K) h = dup_exquo_ground(h, b, K) return R, B, D def",
"u, K), u, K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c,",
"return h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants",
"= dup_monic(h, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g, h, K)",
"0, u, K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h,",
"dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if K.is_one(P): r = R",
"u) > 0: result.append((g, i)) i += 1 if not args.get('include', False): return",
"K1) h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h, u, K0) h",
"perms = variations([-1, 1], len(monoms), repetition=True) for perm in perms: G = dict(F)",
"dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c in g ], v)",
"i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df =",
"and `g` in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g, K) J,",
"n = dup_degree(f) if n < m: return [] deriv, c = [],",
"u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K): \"\"\"Square-free norm of `f` in `K[x]`,",
"for coeff in f[1:]: result = dmp_mul_ground(result, a, v, K) result = dmp_add(result,",
"return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at `x_0",
"0, K) s = 0 while True: h, _ = dmp_inject(f, u, K,",
"return [] deriv, c = [], K.one for i in xrange(0, m): c,",
"f.insert(0, g) h = (h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f, g,",
"common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0`",
"IndexError(\"-%s <= j < %s expected, got %s\" % (u, u, j)) if",
"k2, k1 if k1 == 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1,",
"dup_refine_complex_root(f, x, y, dx, dy, eps, K): \"\"\"Refine a complex root using Wilf's",
"c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots",
"in `K[x]`. \"\"\" prev, k = K.zero, 0 for coeff in f: if",
"\"\"\" if not u: return dup_eval(f, a, K) if not a: return dmp_TC(f,",
"c in f ]) v = dup_strip([ C.imag(c) for c in f ])",
"// 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial",
"K) d = dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v,",
"r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a], K) D",
"b, C) f = dup_scale(f, a, C) u = dup_strip([ C.real(c) for c",
"dx2, dy2, F2), k2) roots[i] = (f1, (x1, y1, dx1, dy1, F1), k1)",
"\"\"\" if not (f or g): return [], [], [] elif not f:",
"= dmp_LC(g, K) else: if not df: F = dmp_LC(f, K) G =",
"K) squarefree = args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F,",
"dup_eval(f, K.zero, K): return F(b, d), F(b, d) f, g = dup_taylor(f, K.one,",
"fast = args.get('eps'), args.get('fast') if eps is not None: cond = lambda a,",
"F34))) elif k3 > 1: stack.append((x, y, hx, hy, k3, F31, F32, F33,",
"f n = dup_degree(f) if n < m: return [] deriv, c =",
"over a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if",
"= dup_content(f, K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if not",
"`f` in `x_j` in `K[X]`. \"\"\" if j < 0 or j >",
"K) gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h =",
"K0) c = K0.convert(cf**m * cg**n, K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT",
"dmp_zero_p(g, u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return",
"k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K)",
"K) g_norm = dmp_max_norm(g, u, K) B = 2*min(f_norm, g_norm) + 29 x",
"dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u,",
"if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d))) f = dup_rshift(f, 1,",
"o x**m = x**m o x**n` 3. `T_n o T_m = T_m o",
"integer image by interpolation. The evaluation proces reduces f and g variable by",
"B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one while P <=",
"subresultant PRS of two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0]",
"d = g, h, k, m-k B.append(b) D.append(d) h = dmp_prem(f, g, u,",
"s, K): \"\"\"XXX\"\"\" n = dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f)",
"= dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p, K) return r def",
"= dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h, g, v, K)",
"v, K) if s < 0: p = dmp_neg(p, v, K) i =",
"1: roots.append((x, y, hx, hy, (F31, F32, F33, F34))) elif k3 > 1:",
"b, K) while h: k = dup_degree(h) R.append(h) lc = dup_LC(g, K) if",
"c, K) def dup_ff_lcm(f, g, K): \"\"\"Computes polynomial LCM over a field in",
"+ \\ [ (( u, v), k) for (u, v) in I_pos ])",
"hy F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero, cx,",
"\"\"\"Computes polynomial GCD of `f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g,",
"K) sturm = [f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1],",
"R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue if K.is_one(P): r",
"not f: return [] h = [f[0]] for c in f[1:]: h =",
"h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_, r =",
"\"\"\" f, n = list(f), dup_degree(f) for i in xrange(n, 0, -1): for",
"return dmp_qq_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K)",
"dup_inner_subresultants(f, g, K) if dup_degree(R[-1]) > 0: return (K.zero, R) if R[-2] ==",
"F ] def _dup_inner_zeros(F1, F2, F3, F4, hx, hy, K): \"\"\"Return the exact",
"dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\" if",
"+ F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f` in `F[x]`.",
"t <= 0: f, s, t, negative = dup_mirror(f, K), -t, -s, True",
"K.zero, K): f = dup_rshift(f, 1, K) a, b, c, d = b,",
"f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in `K[X]`,",
"<= 0 or not f: return f g = [K.zero]*m for i, c",
"u, j)) return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i,",
"dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u, K)",
"Polynomial decomposition algorithms, Journal of Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F",
"u: return dup_content(f, K) if K.has_Field or not K.is_Exact: return dmp_ff_ground_content(f, u, K)",
"r = dup_div(f, h, K) if not r: cfg_, r = dup_div(g, h,",
"False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg =",
"u: return dup_trunc(f, p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v,",
"continue f1 = dup_taylor(f, K.one, K) a1, b1, c1, d1, r = a,",
"dmp_exquo(cg, h, v, K) for cg in g ] return [h], cff, cfg",
"j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j,",
"`K[x]`. \"\"\" if not f: return True else: return not dup_degree(dup_gcd(f, dup_diff(f, 1,",
"< 0: p = -p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res",
"gc = dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f =",
"K) f, i = q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def",
"cond, fast, K)) else: stack.append((a1, b1, c1, d1, f1, k1)) if k2 ==",
"not None: A = K(int(A)) else: A = K.zero if fast and A",
"polynomial over a field. \"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns content",
"HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g, x, K) if ff",
"i, A, u, K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1], K)",
"continued fractions approach. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K, convert=True),",
"p, K) return r def _collins_crt(r, R, P, p, K): \"\"\"Wrapper of CRT",
"return cont, f else: return cont, [ dmp_exquo(c, cont, v, K) for c",
"if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if not f: return",
"D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw = dup_degree(R[i+1]) if du",
"b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw",
"K.one, [] if dup_LC(f, K) < 0: f = dup_neg(f, K) f =",
"[] for group in groups.values(): while len(group) > 1: _max = max([ r[1]",
"\"\"\"XXX\"\"\" g, i = {}, 0 while f: q, r = dup_div(f, h,",
"K) G = dmp_LC(g, K) v = u - 1 h = dmp_gcd(F,",
"not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg x =",
"[(g, i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition",
"...` in `K[X]`. \"\"\" if not A: return f if dmp_zero_p(f, u): return",
"dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res, R def",
"F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2 ], K),",
"u, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if not",
"in `K[x]`. \"\"\" f, n, b = list(f), dup_degree(f), a for i in",
"dup_primitive(f, K) gc, G = dup_primitive(g, K) c = K.gcd(fc, gc) h =",
"K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p` in `K`. \"\"\" if K.is_ZZ:",
"= dup_LC(f, K) if K.is_one(lc): return f else: return dup_quo_ground(f, lc, K) @cythonized(\"u\")",
"trivial cases in GCD algorithm over a ring. \"\"\" if not (f or",
"f = dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f, u) <= 0:",
"if dup_sqf_p(r, K.dom): break else: f, s = dup_taylor(f, -K.unit, K), s+1 return",
"R, B, D h = dup_prem(f, g, K) h = dup_mul_ground(h, b, K)",
"u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f,",
"raise RefinementFailed(\"no roots in (%s, %s) x (%s, %s) rectangle\" % (x, y,",
"] return [h], cff, cfg def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using",
"= K1.one if not v: for c in g: common = K1.lcm(common, K0.denom(c))",
"field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u,",
"in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g, K) J, (f, g)",
"o T_m = T_m o T_n` where `T_n` and `T_m` are Chebyshev polynomials.",
"hx, hy, k4, F41, F42, F43, F44)) if len(roots) == n: eps =",
"q, K): \"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if not",
"if f[j] <= 0: continue q = t + a - K.log(f[j], 2)",
"f = dmp_ground_monic(f, u, K) else: coeff, f = dmp_ground_primitive(f, u, K) if",
"q, i + 1 return dup_from_raw_dict(g, K) @cythonized(\"df,s\") def _dup_decompose(f, K): \"\"\"XXX\"\"\" df",
"squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots = [] _,",
"`Z[X]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg` such",
"c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h",
"roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return roots else:",
"P = dmp_zero(v), K.one, K.one while P <= B: p = K(nextprime(p)) while",
"x, K) h, r = dup_div(f, cff, K) if not r: cfg_, r",
"result is the correct GCD. This gives cofactors as a side effect. References",
"h = dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h)",
"_dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 == 1: roots.append((cx, y,",
"\"\"\"Computes polynomial LCM over a ring in `K[X]`. \"\"\" fc, f = dmp_ground_primitive(f,",
"u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else:",
"% p for c in f ] return dup_strip(g) @cythonized(\"u\") def dmp_trunc(f, p,",
"in f: continue if not s-j in g: continue fc, gc = f[n+j-i],",
"return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers in",
"K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j,",
"hy, K) if k4 == 1: return (cx, y, hx, hy, (F41, F42,",
"a field. \"\"\" if not f: return K.zero else: return K.one def dup_content(f,",
"dx/2, dy/2 cx, cy = x + hx, y + hy F1, F2,",
"transform `K_0` to `K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0, K1) if",
"K.zero for c in f: result *= a result += c return result",
"two polynomials in `K[X]`. \"\"\" return dmp_inner_subresultants(f, g, u, K)[0] @cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f,",
"c, K) for f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction",
"= dmp_mul_ground(cfg, K0.quo(c, cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD = 1",
"u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u, K), dmp_zero(u),",
"dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic",
"c2, d1, d2 = c2, c1, d2, d1 f1, f2, k1, k2 =",
"dup_mirror(f, K) for f in F ] def _dup_inner_zeros(F1, F2, F3, F4, hx,",
"K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else:",
"K) if k3 == 1: roots.append((x, y, hx, hy, (F31, F32, F33, F34)))",
"h, v, K) for cg in g ] return [h], cff, cfg def",
"K) if result is not None: return result fc, F = dmp_primitive(f, u,",
"zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and zero_g: return",
"hy, K): \"\"\"Return the exact number of zeros in the given rectangle. \"\"\"",
"K) f.insert(0, g) h = dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x,",
"b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be",
"`Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is not None:",
"K.dom): break else: f, s = dup_taylor(f, -K.unit, K), s+1 return s, f,",
"i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m, v, K)",
"= -lc * c**(m-k) f, g, m, d = g, h, k, m-k",
"return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u,",
"= dup_degree(R[-2]) res = dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res, R",
"v, K) result = dmp_add(result, coeff, v, K) return result @cythonized(\"v,i,j\") def _rec_eval_in(g,",
"= dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff, v, K) return result",
"f: return K.zero else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD",
"USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f,",
"= A*a, A*c, K.one if A >= K.one: f = dup_taylor(f, A, K)",
"@cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if i == j:",
"% (s, t)) fast = args.get('fast') if type(n) is not int: cond =",
"K): \"\"\"Heuristic polynomial GCD in `Z[x]`. Given univariate polynomials `f` and `g` in",
"dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x, y, dx, dy, F,",
"of polynomials in `K[x]`. \"\"\" fc = dup_content(f, K) gc = dup_content(g, K)",
"c1, d1, f1, k1)) if k2 == 0: continue if k2 == 1:",
"domain must be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom) while",
"K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u),",
"\"\"\" fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd =",
"# Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 =",
"K), dmp_pow(lc, du-dw, v, K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v,",
"args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg",
"u, K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes",
"dmp_zero(u) deriv, c, v = [], K.one, u-1 for i in xrange(0, m):",
"(a, b, c, d), cond, fast, K)) continue f1 = dup_taylor(f, K.one, K)",
"in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg = dup_eval(g, x, K)",
"v, K) h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return",
"cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h,",
"d, v, K) if not d: q = c else: q = dmp_pow(c,",
"v, K) e = dmp_eval(r, a, v, K) if not v: R =",
"v, K), v, K) r = dmp_add(r, c, v, K) r = dmp_ground_trunc(r,",
"d, f, k = stack.pop() A = dup_root_lower_bound(f, K) if A is not",
"K): \"\"\"Computes polynomial LCM over a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f,",
"K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg",
"xrange(0, m): c, n = c*K(n), n-1 for coeff in f[:-m]: deriv.append(coeff*c) c,",
"return cont @cythonized(\"u,v\") def dmp_rr_ground_content(f, u, K): \"\"\"Returns GCD of coefficients over a",
"g variable by variable into a large integer. The final step is to",
"and a primitive polynomial. \"\"\" cont, v = dmp_content(f, u, K), u-1 if",
"dmp_one_p(cont, v, K): return cont, f else: return cont, [ dmp_exquo(c, cont, v,",
"of `f` in `K[x]`, useful over algebraic domains. \"\"\" if not K.is_Algebraic: raise",
"G, K)[-1] _, h = dup_primitive(h, K) if K.is_negative(dup_LC(h, K)): c = -c",
"zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g,",
"K)], [] else: return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u,",
"def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f",
"m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v, K)) return g @cythonized(\"m,v,w,i,j\") def",
"return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u)",
"e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v,",
"= quo(g, h) The algorithm is purely heuristic which means it may fail",
"K) return gcd, f, g @cythonized(\"u\") def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common",
"None: g = _dup_left_decompose(f, h, K) if g is not None: return g,",
"useful over algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must be",
"if not f: return f lc = dup_LC(f, K) if K.is_one(lc): return f",
"v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and evaluate a",
"d = a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one, K) if",
"fast, K) def dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real root's approximating",
"\"\"\" if not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u,",
"K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g =",
"k2: a1, a2, b1, b2 = a2, a1, b2, b1 c1, c2, d1,",
"K)): return g, [], [K.one] else: return dup_neg(g, K), [], [-K.one] elif not",
"return f lc = dup_LC(f, K) if K.is_one(lc): return f else: return dup_quo_ground(f,",
"and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero,",
"= K.zero if fast and A > 16: f = dup_scale(f, A, K)",
"p, v, K) D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D, p,",
"in GCD algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g =",
"not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u) @cythonized(\"s\") def dup_sqf_norm(f, K):",
"f def dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\"",
"on (%s, %s)\" % (s, t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond,",
"Sturm sequence by a real number `c`. \"\"\" return [ dup_taylor(f, c, K)",
"#3: -- F31 = F1 F32 = _dup_sturm_shift(Fy,-hy, K) F33 = _dup_sturm_mirror(Fx, K)",
"s, f, r @cythonized(\"s,u\") def dmp_sqf_norm(f, u, K): \"\"\"Square-free norm of `f` in",
"t, step, fast, K) I_pos[i+j+1] = (s, t, m) I_pos[i] = (u, v,",
"q, r = dup_div(f, g, K) f, g = g, r a, b",
"y, dx, dy, F, eps, K) return x, y, dx, dy def dup_inner_isolate_complex_roots(f,",
"], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative in",
"or not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f,",
"dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h, u, K) return h, cff,",
"v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K)",
"dup_sub(q, d, K) if not h: result.append((p, i)) break g, p, q =",
"K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u, K) else: return dmp_ground_primitive(sqf,",
"b = list(f), dup_degree(f), a for i in xrange(n-1, -1, -1): f[i], b",
"common, f else: return common, dmp_convert(f, u, K0, K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m,",
"else: return dup_neg(f, K), [-K.one], [] return None def _dup_ff_trivial_gcd(f, g, K): \"\"\"Handle",
"-t, -s, True else: raise ValueError(\"can't refine a real root on (%s, %s)\"",
"of those evaluations. The polynomial GCD is recovered from the integer image by",
"`K[x]` using Horner scheme. \"\"\" if not a: return dup_TC(f, K) result =",
"x, K) if ff and gg: h = K.gcd(ff, gg) cff = ff",
"v, K) h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r, u): cfg_,",
"and (y2 >= y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1, dy1, F1",
"\"\"\"Shift origin of a Sturm sequence by a real number `c`. \"\"\" return",
"f1, k1)) if k2 == 0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2,",
"or not K.is_Exact: return dmp_ff_ground_content(f, u, K) else: return dmp_rr_ground_content(f, u, K) def",
"u, K), u-1 if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f",
"continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast,",
"t in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f,",
"in xrange(0, i): if not n+j-i in f: continue if not s-j in",
"K): \"\"\"m-th order derivative of a polynomial in `K[x]`. \"\"\" if m <=",
"`f` in `x_0` in `K[X]`. \"\"\" if not u: return dup_integrate(f, m, K)",
"for c in f: gc = dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc)",
"v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else: return f",
"B: while True: a += K.one if a == p: raise HomomorphismFailed('no luck')",
"dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f = dmp_exquo_ground(f,",
"\"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P, p],",
"c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th",
"if A is not None: A = K(int(A)) else: A = K.zero if",
"dmp_ground_trunc(h, x, v, K) f.insert(0, g) h = dmp_sub(h, g, v, K) h",
"dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m = dmp_degree(g, u) if n",
"K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u,",
"def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's global bisection algorithm. \"\"\"",
"K) if not f or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f,",
"if k2 > 1 or (k1 > 0 and k2 == 1): f2",
"not supported over %s\" % K) if dup_degree(f) <= 0: return [] eps,",
"Euclidean algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K) F =",
"g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative",
"= b, a+b, d, c+d i += 1 s, t = F(a, c),",
"dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\")",
"b, c, d, i, F: i >= 1 for i, (u, v, k)",
"continue P.append(min(Q)) if not P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K):",
"return h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition `f(g)` in",
"c % p if c > p // 2: g.append(c - p) else:",
"if not K.has_Field: raise DomainError('computation can be done only in a field') f",
"\"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g,",
"means it may fail to compute the GCD. This will be signaled by",
"in a field of characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`, where::",
"None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1) if not K1.is_one(common):",
"u): return K.zero, f if K.has_Field or not K.is_Exact: return dmp_ff_ground_primitive(f, u, K)",
"F2 = dup_inner_refine_complex_root(f2, x1, y1, dx1, dy1, F2, K) roots[i+j+1] = (f2, (x2,",
"dup_neg(f, K) coeff = -coeff if dup_degree(f) <= 0: if args.get('include', False): return",
"u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant `p`",
"F4)) while stack: x, y, dx, dy, k, F1, F2, F3, F4 =",
"= dup_neg(f, K) f = list(reversed(f)) for i in xrange(0, n): if f[i]",
"and dv % 2: s = -s lc, i = dmp_LC(R[i], K), i+1",
"%s\" % (u, u, j)) return _rec_integrate_in(f, m, u, 0, j, K) @cythonized(\"m,n,i\")",
"polynomial at `x = a` in `K[x]` using Horner scheme. \"\"\" if not",
"% K) squarefree = args.get('sqf', False) if squarefree: roots = dup_inner_isolate_complex_roots(dup_convert(f, K, F),",
"else: A = K.zero if fast and A > 16: f = dup_scale(f,",
"dv*(1+d), v, K), v, K) _, p, q = dmp_inner_gcd(p, q, v, K)",
"0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s,",
"ring in `K[x]`. \"\"\" fc, f = dup_primitive(f, K) gc, g = dup_primitive(g,",
"dmp_mul(h, g, u, K) h = dmp_add_term(h, c, 0, u, K) return h",
"= min([ r[1] for r in group ]) for i, (x, y, dx,",
"K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while not",
"dmp_zero_p(f, u) or dmp_zero_p(g, u): return R, B, D h = dmp_prem(f, g,",
"\"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`. \"\"\" if",
"_rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K):",
"if not h: result.append((p, i)) break g, p, q = dup_inner_gcd(p, h, K)",
"\"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g, K)",
"GCD and cofactors of `f` and `g` in `K[X]`. \"\"\" if not u:",
"examples: 1. `f o g = f(x + b) o (g - b)`",
"a polynomial in `K[X]`. \"\"\" if not u: return dup_discriminant(f, K) d, v",
"= 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes polynomial GCD and",
"= dmp_rr_ground_content(c, v, K) cont = K.gcd(cont, gc) if K.is_one(cont): break return cont",
"over a field. \"\"\" if not f: return K.zero else: return K.one @cythonized(\"u\")",
"K.is_Algebraic: raise DomainError('computation can be done only in an algebraic domain') F, monoms,",
"dup_prem(f, g, K) h = dup_mul_ground(h, b, K) while h: k = dup_degree(h)",
"K) if result is not None: f, h = result F = [h]",
"return e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a,",
"dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4 ], K), ] return sum(v1",
"`K[X]` using Horner scheme. \"\"\" if j < 0 or j > u:",
"124-128 \"\"\" if not K.has_Field: raise DomainError('computation can be done only in a",
"def dup_compose(f, g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if len(g)",
"(F41, F42, F43, F44))) elif k4 > 1: stack.append((cx, y, hx, hy, k4,",
"if s < 0: p = dmp_neg(p, v, K) i = dmp_degree(R[-2], u)",
"sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to",
"len(factors) == 1: ((f, k),) = factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K)",
"k, F1, F2, F3, F4)) while stack: x, y, dx, dy, k, F1,",
"= dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one, v) B, D =",
"K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in `F[x]`. \"\"\" if",
"dup_degree(f), -K.one for i in xrange(n-1, -1, -1): f[i], a = a*f[i], -a",
"- 1 h = dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf, h,",
"not u: return dup_inner_gcd(f, g, K) J, (f, g) = dmp_multi_deflate((f, g), u,",
"dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u-1, K), u-1 for i,",
"= dict(F) for sign, monom in zip(perm, monoms): if sign == -1: G[monom]",
"raise DomainError(\"real root refinement not supported over %s\" % K) if s ==",
"== 1: return (x, y, hx, hy, (F31, F32, F33, F34)) # Quadrant",
"q, K)) for c, q in zip(f[1:], Q[1:]): h = dup_mul(h, p, K)",
"fast, K)) else: stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots) def dup_isolate_real_roots(f,",
"c, d), cond, fast, K)] else: roots, stack = [], [(a, b, c,",
"`f` is a square-free polynomial in `K[x]`. \"\"\" if not f: return True",
"i, j, K) for c in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a,",
"= dmp_degree(g, u) if n < m: f, g = g, f n,",
"enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r in enumerate(lower): lower[i] = (r,",
"raise DomainError(\"isolation of real roots not supported over %s\" % K) if dup_degree(f)",
"f in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3",
"f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1):",
"u, j)) return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a, K):",
"list(reversed(f)) for i in xrange(0, n): if f[i] >= 0: continue a, Q",
"if dmp_one_p(cont, v, K): break if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K)",
"g, f n, m = m, n R = [f, g] d =",
"lower.append((x, y, dx, dy)) del group[i] break upper = sorted(upper, key=lambda r: r[0])",
"The evaluation proces reduces f and g variable by variable into a large",
"dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f, u): return f g,",
"K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g = dmp_ground_to_ring(g, u,",
"root's approximating interval to the given precision. \"\"\" if K.is_QQ: (_, f), K",
"None: return g, h return None def dup_decompose(f, K): \"\"\"Computes functional decomposition of",
"f_n)`, where:: f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))",
"dmp_neg, dup_add, dmp_add, dup_sub, dmp_sub, dup_mul, dmp_mul, dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem,",
"m: break R = dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a,",
"if n < m: f, g = g, f n, m = m,",
"g, u, K), dmp_gcd(f, g, u, K), u, K) return dmp_mul_ground(h, c, u,",
"random as randfloat def dup_ground_to_ring(f, K0, K1=None, **args): \"\"\"Clear denominators, i.e. transform `K_0`",
"d: q = c else: q = c**(d-1) c = K.exquo((-lc)**d, q) b",
"dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients. \"\"\"",
"K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if",
"dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h,",
"dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a], K) D = dup_trunc(D,",
"f or K.is_one(cont): return cont, f else: return cont, dup_exquo_ground(f, cont, K) def",
"i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for",
"PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g) if n",
"F1, F2, F3, F4 = stack.pop() hx, hy = dx/2, dy/2 cx, cy",
"\"\"\" if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g,",
"k, F1, F2, F3, F4 = stack.pop() hx, hy = dx/2, dy/2 cx,",
"or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h =",
"dup_degree(f) lc = dup_LC(f, K) f = dup_to_raw_dict(f) g = { s :",
"t: return (s, t) F = K.get_field() a, c = F.numer(s), F.denom(s) b,",
"dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in `K[X]`. \"\"\" if not u:",
"return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in f ], u) def",
"and a primitive polynomial over a ring. \"\"\" cont = dmp_ground_content(f, u, K)",
"continue q = t + a - K.log(f[j], 2) Q.append(q // (j -",
"\"\"\" s, h = dup_half_gcdex(f, g, K) if h == [K.one]: return dup_rem(s,",
"return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS",
"u, K, front=True) r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r, u, K.dom):",
"dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K) k2 = k - k1",
"a polynomial in `K[X]`. \"\"\" if j < 0 or j > u:",
"and Algorithms for Algebraic Computation, Academic Press, London, 1988, pp. 124-128 \"\"\" if",
"K), K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx,",
"to the given precision. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K,",
"`K_1`. \"\"\" if not u: return dup_ground_to_ring(f, K0, K1) if K1 is None:",
"or `K[X]`. \"\"\" from sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree,",
"< m: return [] deriv, c = [], K.one for i in xrange(0,",
"\"\"\" if not u: return dup_inner_subresultants(f, g, K) n = dmp_degree(f, u) m",
"h = [f[0]] for c in f[1:]: h = dup_mul(h, g, K) h",
"else: f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f =",
"s) def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine a positive root of",
"of a polynomial in `K[x]`. \"\"\" if not f: return f if K.is_negative(dup_LC(f,",
"a, K): \"\"\"Evaluate efficiently Taylor shift `f(x + a)` in `K[x]`. \"\"\" f,",
"in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: coeff = dup_LC(f, K) f",
"(u, v, k) in I_neg ] + \\ [ (( u, v), k)",
"K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f, u, K0, K1=None,",
"@cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative of a polynomial in `K[x]`.",
"return None @cythonized(\"u,v,df,dg\") def _dmp_simplify_gcd(f, g, u, K): \"\"\"Try to eliminate `x_0` from",
"cff_, r = dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r =",
"K1) f = dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h, cff,",
"case you will need to switch to another GCD method. The algorithm computes",
"in `K[x]`. \"\"\" f, n = list(f), dup_degree(f) for i in xrange(n, 0,",
"x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1,",
"v) @cythonized(\"m,j,u\") def dmp_diff_in(f, m, j, u, K): \"\"\"m-th order derivative in `x_j`",
"dup_exquo(f, h, K) cfg = dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\")",
"dy)) del group[i] break _min = min([ r[1] for r in group ])",
"p = dmp_mul(dmp_mul(p, dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw, v, K),",
"positive roots. \"\"\" n, t, P = len(f), K.one, [] if dup_LC(f, K)",
"not f: return dup_monic(g, K), [], [dup_LC(g, K)] elif not g: return dup_monic(f,",
"over a ring. \"\"\" if not u: return dup_rr_content(f, K) cont, v =",
"return dup_trunc(f, p, K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K)",
"dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v) == n: G =",
"for i, c in enumerate(reversed(f)): n = i+1 for j in xrange(1, m):",
"u, K) def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a",
"@cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common = K1.one if not v:",
"`Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`, returns their GCD and",
"`g` in `Z[x]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and",
"F33, F34)) # Quadrant #4: +- F41 = _dup_sturm_shift(F1, hx, K) F42 =",
"g, K): \"\"\"Computes resultant of two polynomials in `K[x]`. \"\"\" return dup_prs_resultant(f, g,",
"hy, K) if k2 == 1: roots.append((x, cy, hx, hy, (F21, F22, F23,",
"dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p, i)) break g, p, q",
"K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _, p, q",
"= [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B: while True: a",
"F4, dx, dy, K) if k != n: return dup_inner_isolate_complex_roots(f, K) if k",
"if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u,",
"signaled by raising an exception. In this case you will need to switch",
"b, c, d, i, F): A = dup_root_lower_bound(f, K) if A is not",
"= -s lc, i = dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw)",
"\"\"\"m-th order derivative in `x_j` of a polynomial in `K[X]`. \"\"\" if j",
"if i == j: return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v,",
"== 1: roots.append((x, y, dx, dy, (F1, F2, F3, F4))) elif k >",
"-1, -1): f[i], b = b*f[i], b*a return f def dup_taylor(f, a, K):",
"F(a, c), F(b, d) if s <= t: return (s, t) else: return",
"= [], [] for group in groups.values(): while len(group) > 1: _max =",
"dmp_LC(f, K) G = dmp_content(g, u, K) else: F = dmp_content(f, u, K)",
"= [f[0]] for c in f[1:]: h = dup_mul(h, g, K) h =",
"if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and",
"c > p // 2: g.append(c - p) else: g.append(c) else: g =",
"> 1 or (k1 > 0 and k2 == 1): f2 = dup_taylor(dup_reverse(f),",
"continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond, fast,",
"k2, F21, F22, F23, F24)) # Quadrant #3: -- F31 = F1 F32",
"n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c, n",
"square-free decomposition of a polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact:",
"a field. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f",
"result fc, f = dmp_primitive(f, u, K) gc, g = dmp_primitive(g, u, K)",
"f_n` are monic and homogeneous polynomials of at least second degree. Unlike factorization,",
"return ( s, t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive",
"cond = lambda a, b, c, d, i, F: abs(F(a, c) - F(b,",
"@cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and evaluate a polynomial",
"algorithm in `K[X]` using subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f, g,",
"K.zero, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for",
"hy, (F11, F12, F13, F14))) elif k1 > 1: stack.append((cx, cy, hx, hy,",
"_dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K) if not r: cfg_,",
"GCD from integer GCD. \"\"\" f = [] while h: g = h",
"cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a",
"return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD",
"u, 0, K) s = 0 while True: h, _ = dmp_inject(f, u,",
"domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit],",
"u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g,",
"the number of sign variations of `f` in `K[x]`. \"\"\" prev, k =",
"gf_int(gf_crt([r, R], [P, p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's",
"in `Z[x]`, returns their GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg`",
"\"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s, g =",
"K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_,",
"u, K) return h, cff, cfg HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K):",
"[R] e = [e] d = K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D,",
"common = K1.lcm(common, K0.denom(c)) else: w = v-1 for c in g: common",
"if h == [K.one]: return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\")",
"\"\"\"Returns multivariate content and a primitive polynomial. \"\"\" cont, v = dmp_content(f, u,",
"`g` in `K[X]`. \"\"\" if not u: return dup_inner_gcd(f, g, K) J, (f,",
"h = dmp_gcd(F, G, v, K) cff = [ dmp_exquo(cf, h, v, K)",
"gc) if not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g,",
"P.append(min(Q)) if not P: return None else: return 2.0**(max(P)+1) def dup_root_lower_bound(f, K): \"\"\"Compute",
"def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[x]`.",
"sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic",
"= dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K) def _dup_rr_trivial_gcd(f, g,",
"dmp_zz_heu_gcd(f, g, u, K1) h = dmp_convert(h, u, K1, K0) c = dmp_ground_LC(h,",
"return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes polynomial LCM over",
"def dmp_ground_extract(f, g, u, K): \"\"\"Extracts common content from a pair of polynomials",
"%s\" % (u, u, j)) return _rec_eval_in(f, a, u, 0, j, K) @cythonized(\"i,u\")",
"c in f ]) seq = [u, v] while seq[-1]: s = dup_rem(seq[-2],",
"GCD, International Symposium on Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec,",
"None: return result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff",
"u, K) h = dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc,",
"at certain points and computing (fast) integer GCD of those evaluations. The polynomial",
"cond(a, b, c, d, i, F): A = dup_root_lower_bound(f, K) if A is",
"dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand,",
"[ dup_sign_variations([ dup_eval(f, hx, K) for f in F1 ], K), dup_sign_variations([ dup_eval(f,",
"== 0: continue if k1 == 1: roots.append(dup_inner_refine_real_root( f1, (a1, b1, c1, d1),",
"using continued fractions approach. \"\"\" if K.is_QQ: (_, f), K = dup_ground_to_ring(f, K,",
"hx, hy, K) if k2 == 1: return (x, cy, hx, hy, (F21,",
"enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2 while not ((x2 >= x1+dx1",
"f else: return coeff, [] result, i = [], 1 h = dup_diff(f,",
"dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K)",
"result df = dmp_degree(f, u) dg = dmp_degree(g, u) gcd, f, g =",
"raise DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F",
"cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def",
"v, K) v, i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i,",
"not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f if K.has_Field",
"gc, g = dmp_ground_primitive(g, u, K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f,",
"return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate coefficients.",
"k1 == 1: return (cx, cy, hx, hy, (F11, F12, F13, F14)) #",
"returns tuple `(f_1, f_2, ..., f_n)`, where:: f = f_1 o f_2 o",
"dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors",
"import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict,",
"zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g,",
"GCD in `Q[X]`. \"\"\" result = _dmp_ff_trivial_gcd(f, g, u, K0) if result is",
"in f[1:]: h = dup_mul(h, g, K) h = dup_add_term(h, c, 0, K)",
"u) <= 0: if args.get('include', False): return f else: return coeff, [] result,",
"= dmp_degree(f, u) m = dmp_degree(g, u) if n < 0 or m",
"Algorithms for Algebraic Computation, Academic Press, London, 1988, pp. 124-128 \"\"\" if not",
"hx, hy, K) if k3 == 1: roots.append((x, y, hx, hy, (F31, F32,",
"+ hy F1, F2, F3, F4 = F Fx = _dup_inner_sturm(f, K.one, K.zero,",
"( gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError",
"res, R def dup_resultant(f, g, K): \"\"\"Computes resultant of two polynomials in `K[x]`.",
"r = dup_div(g, cfg, K) if not r: cff_, r = dup_div(f, h,",
"[ dmp_exquo(ch, b, v, K) for ch in h ] return R, B,",
"args.get('convert'): return common, f else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g,",
"= dup_sqf_list(f, K) for g, k in factors: g = dup_convert(g, K, F)",
"K): \"\"\"Wrapper of CRT for Collins's resultant algorithm. \"\"\" return gf_int(gf_crt([r, R], [P,",
"= dup_mul_ground(g, coeff, K) return [(g, i)] + rest def dup_extract(f, g, K):",
"discriminant of a polynomial in `K[X]`. \"\"\" if not u: return dup_discriminant(f, K)",
"K) if k1 == 1: return (cx, cy, hx, hy, (F11, F12, F13,",
"dup_pow, dmp_pow, dup_div, dmp_div, dup_rem, dmp_rem, dup_quo, dmp_quo, dup_exquo, dmp_exquo, dup_prem, dmp_prem, dup_expand,",
"K) else: return dmp_ground_primitive(sqf, u, K)[1] @cythonized(\"i\") def dup_sqf_list(f, K, **args): \"\"\"Returns square-free",
"return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u, K): \"\"\"Helper function for",
"f: c = c % p if c > p // 2: g.append(c",
"`K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f,",
"return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns",
"K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of a Sturm sequence",
"result is not None: return result h = dup_subresultants(f, g, K)[-1] h =",
"except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g, u,",
"in enumerate(I_neg[i+1:]): while not (s >= v or t <= u): u, v",
"dup_strip([e]) else: R = [R] e = [e] d = K.invert(dup_eval(D, a, K),",
"r in group ]) for i, (x, y, dx, dy) in enumerate(group): if",
"a complex root using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ:",
"G = dup_primitive(g, K) c = K.gcd(fc, gc) h = dup_subresultants(F, G, K)[-1]",
"h, u, K) cfg = dmp_exquo(g, h, u, K) return h, cff, cfg",
"HEU_GCD_MAX = 6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer GCD.",
"K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i",
"def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g,",
"d2, d1 f1, f2, k1, k2 = f2, f1, k2, k1 if k1",
"dup_div(f, g, K) f, g = g, r a, b = b, dup_sub_mul(a,",
"dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from",
"i = [], 1 h = dup_diff(f, 1, K) g, p, q =",
"_dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 == 1: roots.append((x, y,",
"h = K.gcd(ff, gg) cff = ff // h cfg = gg //",
"return dmp_eval(dmp_diff(f, m, u, K), a, u, K) return _rec_diff_eval(f, m, a, u,",
"_, factors = dup_sqf_list(f, K) for g, k in factors: g = dup_convert(g,",
"return f, [K.one], [] else: return dup_neg(f, K), [-K.one], [] return None def",
"seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def _dup_sturm_shift(F, c, K): \"\"\"Shift origin of",
"dup_qq_heu_gcd(f, g, K) except HeuristicGCDFailed: pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD:",
"dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't refine a real root on",
"= dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1, K0) cff =",
"v, k) for i, (u, v, k) in enumerate(I_neg): for j, (s, t,",
"r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2",
"while not (s >= v or t <= u): u, v = dup_outer_refine_real_root(F_pos[k],",
"x (%s, %s) rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y,",
"is not None: return result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u,",
"2. `x**n o x**m = x**m o x**n` 3. `T_n o T_m =",
"GCD algorithm over a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g,",
"u, K) c = K.lcm(fc, gc) h = dmp_exquo(dmp_mul(f, g, u, K), dmp_gcd(f,",
"K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K), K)",
"@cythonized(\"u,v,s,i,d,du,dv,dw\") def dmp_prs_resultant(f, g, u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS.",
"hx, hy, K) if k1 == 1: roots.append((cx, cy, hx, hy, (F11, F12,",
"dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u, K1) h",
"hx, hy, K) if k2 == 1: roots.append((x, cy, hx, hy, (F21, F22,",
"or dup_degree(g) > 0: result.append((g, i)) i += 1 if not args.get('include', False):",
"else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's",
"g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B,",
"s, f, r def dup_sqf_part(f, K): \"\"\"Returns square-free part of a polynomial in",
"a polynomial in `K[X]`. \"\"\" if not u: return dup_diff(f, m, K) if",
"<NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation 7 (1989), pp. 445-456 \"\"\"",
"hx, hy, (F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx,",
"dup_monic(f, K) if dmp_zero_p(f, u): return f lc = dmp_ground_LC(f, u, K) if",
"= dup_to_raw_dict(f) g = { s : K.one } r = n //",
"\"\"\"Evaluate a polynomial at `x = a` in `K[x]` using Horner scheme. \"\"\"",
"0, K) return h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional composition",
"\"\"\" if not u: return dup_lcm(f, g, K) if K.has_Field or not K.is_Exact:",
"in xrange(0, m): c, n = c*K(n), n-1 for coeff in f[:-m]: h",
"not K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd, u,",
"K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[x]`. \"\"\" if",
"a ring. \"\"\" cont = dup_content(f, K) if not f or K.is_one(cont): return",
"u, K) if result is not None: return result fc, F = dmp_primitive(f,",
"r = dmp_resultant(g, h, 1, K.dom) if dup_sqf_p(r, K.dom): break else: f, s",
"= dup_mirror(f, K), -t, -s, True else: raise ValueError(\"can't refine a real root",
"v, i, j, K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m, v,",
"a = list(f), dup_degree(f), -K.one for i in xrange(n-1, -1, -1): f[i], a",
"= dup_gcd(f, dup_diff(f, 1, K), K) sqf = dup_exquo(f, gcd, K) if K.has_Field",
"factors I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg =",
"q, v, K) b = dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v,",
"= lambda a, b, c, d, i, F: abs(F(a, c) - F(b, d))",
"g, u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f` and",
"dup_convert(cff, K1, K0) cfg = dup_convert(cfg, K1, K0) cff = dup_mul_ground(cff, K0.quo(c, cf),",
"g step = lambda a, b, c, d, i, F: i >= 1",
"def dmp_discriminant(f, u, K): \"\"\"Computes discriminant of a polynomial in `K[X]`. \"\"\" if",
"g, K) if dmp_zero_p(f, u): return f h = [f[0]] for c in",
"K), a, u, K) return _rec_diff_eval(f, m, a, u, 0, j, K) def",
"A, u, K): \"\"\"Evaluate a polynomial at `x_j = a_j, ...` in `K[X]`.",
"du-dw, v, K), v, K) q = dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v,",
"be signaled by raising an exception. In this case you will need to",
"import nextprime from sympy.utilities import ( cythonized, variations ) from random import random",
"in dup_inner_isolate_real_roots(g, cond, fast, K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g",
"K) cff = dmp_exquo(f, h, u, K) cfg = dmp_exquo(g, h, u, K)",
"r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`.",
"= list(f), dup_degree(f), a for i in xrange(n-1, -1, -1): f[i], b =",
"= {} for (_, (x, y, dx, dy, _), k) in roots: multiplicity[(x,",
"F43, F44)) if len(roots) == n: eps = args.get('eps') if eps is not",
"1, K), K)) @cythonized(\"u\") def dmp_sqf_p(f, u, K): \"\"\"Returns `True` if `f` is",
"i, (u, v, k) in enumerate(I_pos): for j, (s, t, m) in enumerate(I_pos[i+1:]):",
"else: raise ValueError(\"can't refine a real root on (%s, %s)\" % (s, t))",
"will need to switch to another GCD method. The algorithm computes the polynomial",
"g = dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g, u,",
"raising an exception. In this case you will need to switch to another",
"cx, cy = x + hx, y + hy F1, F2, F3, F4",
"\"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f,",
"for f in F ] def _dup_sturm_mirror(F, K): \"\"\"Flip the direction of a",
"K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f, v+1, K) else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f,",
"K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G, u, K)[-1]",
"cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K) if",
"decomposition of a polynomial in `K[X]`. \"\"\" if not u: return dup_sqf_list(f, K,",
"= dup_LC(g, K) if not d: q = c else: q = c**(d-1)",
"return dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f,",
"= c*K(n), n-1 for coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v, K)",
"p, v, K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g,",
"k, m-k B.append(b) D.append(d) h = dup_prem(f, g, K) h = dup_exquo_ground(h, b,",
"K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\" if not u:",
"= [ dmp_exquo(cf, h, v, K) for cf in f ] cfg =",
"[[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K)) for c, q in",
"g, K) J, (f, g) = dmp_multi_deflate((f, g), u, K) h, cff, cfg",
"False): return f else: return coeff, [] result, i = [], 1 h",
"if eps is not None: for i, (x, y, dx, dy, F) in",
"= dmp_degree(f, u) if n < m: return dmp_zero(u) deriv, c, v =",
"h ] return R, B, D @cythonized(\"u\") def dmp_subresultants(f, g, u, K): \"\"\"Computes",
"R = dup_strip([R]) e = dup_strip([e]) else: R = [R] e = [e]",
"and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return",
"K)) else: stack.append((a1, b1, c1, d1, f1, k1)) if k2 == 0: continue",
"F34, hx, hy, K) if k3 == 1: return (x, y, hx, hy,",
"= dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg,",
"= dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h,",
"c, v, K) r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one,",
"cond, fast, K): \"\"\"Iteratively compute disjoint positive root isolation intervals. \"\"\" a, b,",
"ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if not u: return",
"K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate",
"sympy.polys.densebasic import ( dup_strip, dmp_strip, dup_reverse, dup_convert, dmp_convert, dup_degree, dmp_degree, dmp_degree_in, dup_to_dict, dmp_to_dict,",
"t, P = len(f), K.one, [] if dup_LC(f, K) < 0: f =",
"for c in f[1:]: h = dmp_mul(h, g, u, K) h = dmp_add_term(h,",
"= dmp_convert(f, u, K0, K1) g = dmp_convert(g, u, K0, K1) h, cff,",
"into a large integer. The final step is to verify if the interpolated",
"r < 0.5: break x, y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r",
"d = n - m b = (-K.one)**(d+1) c = -K.one B, D",
"dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K) c =",
"if df % s != 0: continue h = _dup_right_decompose(f, s, K) if",
"g, u, K0): \"\"\"Collins's modular resultant algorithm in `Q[X]`. \"\"\" n = dmp_degree(f,",
"def dmp_ground_monic(f, u, K): \"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\" if",
"K0, K1): \"\"\"XXX\"\"\" common = K1.one if not v: for c in g:",
"K) if A is not None: A = K(int(A)) else: A = K.zero",
"= (s, t, m) I_pos[i] = (u, v, k) for i, (u, v,",
"cg), u, K0) return h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1",
"d, i, F: abs(F(a, c) - F(b, d)) < eps else: cond =",
"= [f, dup_diff(f, 1, K)] while sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s,",
"part of a polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return f if",
"], v) @cythonized(\"m,j,u\") def dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and evaluate",
"= _dup_sturm_shift(Fx,-hx, K) F22 = Fy F23 = _dup_sturm_shift(F3, hx, K) F24 =",
"-K.one for i in xrange(n-1, -1, -1): f[i], a = a*f[i], -a return",
"cx, cy, K) Fy = _dup_inner_sturm(f, K.zero, K.one, cx, cy, K) # Quadrant",
"w, i, j, K) for c in g ], v) @cythonized(\"m,j,u\") def dmp_diff_in(f,",
"return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u,",
"\"\"\"Reduce `K[x]` polynomial modulo a constant `p` in `K`. \"\"\" if K.is_ZZ: g",
"len(monoms), repetition=True) for perm in perms: G = dict(F) for sign, monom in",
"K) k = dup_sign_variations(f, K) if k == 0: continue if k ==",
"0 or j > u: raise IndexError(\"-%s <= j < %s expected, got",
"polynomials `h`, `cff` and `cfg` such that:: h = gcd(f, g), cff =",
"in zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K):",
"u, v), k) for (u, v, k) in I_pos ]) def _dup_inner_sturm(f, p,",
"prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0] % p, p)",
"u, 0, j, K) def dup_half_gcdex(f, g, K): \"\"\"Half extended Euclidean algorithm in",
"_dup_sturm_shift(F1, hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44",
"% x if g > x // 2: g -= x f.insert(0, g)",
"_dup_inner_zeros(F11, F12, F13, F14, hx, hy, K) if k1 == 1: return (cx,",
"if j < 0 or j > u: raise IndexError(\"-%s <= j <",
"cx, cy = x + hx, y + hy Fx = _dup_inner_sturm(f, K.one,",
"0, A, u, K) if u == len(A)-1: return e else: return dmp_strip(e,",
"i.e. polynomials `h`, `cff` and `cfg` such that:: h = gcd(f, g), cff",
"K): \"\"\"Returns GCD of coefficients in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact:",
"coeff in f[:-m]: h = dmp_mul_ground(coeff, c, v, K) c, n = K(n)*K.exquo(c,",
"j, K) def dup_eval(f, a, K): \"\"\"Evaluate a polynomial at `x = a`",
"`g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ:",
"a primitive polynomial over a ring. \"\"\" cont = dup_content(f, K) if not",
"v, K) c, n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def",
"result is not None: return result fc, F = dup_primitive(f, K) gc, G",
"= dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K) g_norm = dmp_max_norm(g,",
"in `K[x]`. \"\"\" return dup_prs_resultant(f, g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K):",
"{}, {} for f, k in factors: for u, v in dup_inner_isolate_real_roots(f, cond,",
"stack.pop() A = dup_root_lower_bound(f, K) if A is not None: A = K(int(A))",
"h) The algorithm is purely heuristic which means it may fail to compute",
"dmp_ff_ground_primitive(f, u, K) else: return dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True`",
"dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j, K):",
"with coefficients in a field of characteristic zero, returns tuple `(f_1, f_2, ...,",
"ring. \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not None: return",
"K(int(A)) else: A = K.zero if fast and A > 16: f =",
"Canada, 1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is",
"variable by variable into a large integer. The final step is to verify",
"dup_degree(f) for i in xrange(n, 0, -1): for j in xrange(0, i): f[j+1]",
"f else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content and",
"K.is_one(gcd): f = dmp_exquo_ground(f, gcd, u, K) g = dmp_exquo_ground(g, gcd, u, K)",
"K) return x, y, dx, dy, F def dup_refine_complex_root(f, x, y, dx, dy,",
"= dmp_div(f, h, u, K) if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h,",
"K) h, r = dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r",
"enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]): while not (s >= v",
"F3, F4))) elif k > 1: stack.append((x, y, dx, dy, k, F1, F2,",
"u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1),",
"g, p, q = dup_inner_gcd(p, h, K) if all or dup_degree(g) > 0:",
"u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K) res = dmp_quo(dmp_mul(res, p, v,",
"dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground, dup_max_norm, dmp_max_norm ) from sympy.polys.galoistools import ( gf_int, gf_crt",
"for i, (f1, r1, k1) in enumerate(roots): x1, y1, dx1, dy1, F1 =",
"[Liao95] <NAME>, <NAME>, Evaluation of the heuristic polynomial GCD, International Symposium on Symbolic",
"u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative of",
"K) for c in g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u,",
"K), u, K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v,",
"c in f: c = c % p if c > p //",
"`f` in `K[x]`, useful over algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground",
"v, K) i = dmp_degree(R[-2], u) res = dmp_pow(dmp_LC(R[-1], K), i, v, K)",
"u, K0) h = dmp_ground_monic(h, u, K0) cff = dmp_convert(cff, u, K1, K0)",
"dmp_zero_p(f, u): return f h = [f[0]] for c in f[1:]: h =",
"hy, (F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K)",
"\"\"\"Extended Euclidean algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K) F",
"i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in g",
"_dmp_zz_gcd_interpolate(cff, x, v, K) h, r = dmp_div(f, cff, u, K) if dmp_zero_p(r,",
"return dmp_neg(f, u, K), dmp_ground(-K.one, u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u,",
"g): return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g,",
"h = dup_mul(h, g, K) h = dup_add_term(h, c, 0, K) return h",
"t, cond, fast, K) if negative: return (-t, -s) else: return ( s,",
"-u), k) for (u, v) in I_neg ] + \\ [ (( u,",
"GCD and cofactors, i.e. polynomials `h`, `cff` and `cfg` such that:: h =",
"dmp_LC(g, K) p = dmp_pow(dmp_neg(lc, v, K), d, v, K) if not d:",
"u) dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if du %",
"= dmp_LC(f, K) G = dmp_LC(g, K) else: if not df: F =",
"27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic polynomial GCD in `Q[x]`.",
"cff = dup_mul_ground(cff, K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return",
"(x1, y1, dx1, dy1, F1), k1) multiplicity = {} for (_, (x, y,",
"a, b, c, d, i, F: abs(F(a, c) - F(b, d)) < eps",
"dmp_rr_ground_primitive(f, u, K) def dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a square-free",
"dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff = -coeff if",
"resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u)",
"0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K)",
"in `K`. \"\"\" if K.is_ZZ: g = [] for c in f: c",
"def dup_rr_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\"",
"dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f, g, K) if df",
"**args): \"\"\"Isolate complex roots using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or",
"= dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while True: h, _ =",
"if i == u: return dup_eval(g, A[-1], K) else: h = [ _rec_eval_tail(c,",
"def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not",
"or m < 0: return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B =",
"gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from",
"2) Q.append(q // (j - i)) t += 1 if not Q: continue",
"a complex root until the desired precision is reached. \"\"\" while dx >=",
"`p` in `K`. \"\"\" if not u: return dup_trunc(f, p, K) v =",
"f, g = dup_taylor(f, K.one, K), f a1, b1, c1, d1 = a,",
"0: if t <= 0: f, s, t, negative = dup_mirror(f, K), -t,",
"\"\"\"Computes polynomial GCD using subresultants over a field. \"\"\" if not u: return",
"D, a = [K.one], -K.one r = dmp_zero(v) while dup_degree(D) <= B: while",
"<= 0: return K.zero else: s = (-1)**((d*(d-1)) // 2) c = dup_LC(f,",
"u, K) try: R = dmp_zz_modular_resultant(F, G, p, u, K) except HomomorphismFailed: continue",
"g, K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if len(g) <= 1:",
"2) c = dup_LC(f, K) r = dup_resultant(f, dup_diff(f, 1, K), K) return",
"K0, K) else: raise DomainError(\"isolation of complex roots not supported over %s\" %",
"dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert",
"\"\"\"Evaluate functional transformation `q**n * f(p/q)` in `K[x]`. \"\"\" if not f: return",
"d = dup_degree(f) if d <= 0: return K.zero else: s = (-1)**((d*(d-1))",
"USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g,",
"I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f,",
"c = F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a,",
"f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer Algebra Systems and Algorithms",
"r = dup_div(f, cff, K) if not r: cfg_, r = dup_div(g, h,",
"in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def",
"(u, u, j)) return _rec_diff_in(f, m, u, 0, j, K) def dup_eval(f, a,",
"1, 0, K.dom) while True: h, _ = dmp_inject(f, 0, K, front=True) r",
"list(f), dup_degree(f), a for i in xrange(n-1, -1, -1): f[i], b = b*f[i],",
"result[1:] g = dup_mul_ground(g, coeff, K) return [(g, i)] + rest def dup_extract(f,",
"> 1: stack.append((x, y, hx, hy, k3, F31, F32, F33, F34)) # Quadrant",
"or not (b % p): p = K(nextprime(p)) F = dmp_ground_trunc(f, p, u,",
"(dmp_zero_p(ff, v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K)",
"s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h, s, f, K) t",
"dup_eval(g, x, K) if ff and gg: h = K.gcd(ff, gg) cff =",
"lambda a, b, c, d, i, F: i >= 1 for i, (u,",
"dy1, F1 = r1 for j, (f2, r2, k2) in enumerate(roots[i+1:]): x2, y2,",
"= [f[0]] for c in f[1:]: h = dmp_mul(h, g, u, K) h",
"algorithm in `F[x]`. \"\"\" s, h = dup_half_gcdex(f, g, K) F = dup_sub_mul(h,",
"group ]) for i, (x, y, dx, dy) in enumerate(group): if y ==",
"result, i = [], 1 h = dup_diff(f, 1, K) g, p, q",
"= dup_degree(f) m = dup_degree(g) if n < m: f, g = g,",
"@cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a ring in",
"GCD method. The algorithm computes the polynomial GCD by evaluating polynomials f and",
"Mobius transform. \"\"\" F, i = K.get_field(), 0 while not c or not",
"dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc,",
"K.has_Field or not K.is_Exact: return dup_monic(sqf, K) else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def",
"(1989), pp. 445-456 \"\"\" F = [] while True: result = _dup_decompose(f, K)",
"i in xrange(0, n): if f[i] >= 0: continue a, Q = K.log(-f[i],",
"dmp_exquo(ch, b, v, K) for ch in h ] return R, B, D",
"= dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f,",
"K) return dmp_mul_ground(h, c, u, K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes",
"in f: cont = K.gcd(cont, c) if K.is_one(cont): break return cont def dup_ff_content(f,",
"K) else: coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f",
"i = dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d))",
"cases in GCD algorithm over a field. \"\"\" if not (f or g):",
"K) if result is not None: return result fc, f = dmp_primitive(f, u,",
"K), dmp_pow(c, m-k, v, K), v, K) f, g, m, d = g,",
"else: return common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\"",
"field. \"\"\" if not (f or g): return [], [], [] elif not",
"dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a field in `K[X]`. \"\"\"",
"K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u) m",
"gc, u-1, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c,",
"`K[x]`. \"\"\" if K.has_Field or not K.is_Exact: return dup_ff_lcm(f, g, K) else: return",
"for (u, v, k) in I_neg ] + \\ [ (( u, v),",
"> 1: for i, (f1, r1, k1) in enumerate(roots): x1, y1, dx1, dy1,",
"if K1 is None: K1 = K0.get_ring() common = _rec_ground_to_ring(f, u, K0, K1)",
"u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one, K.one",
"K.zero, K): return F(b, d), F(b, d) f, g = dup_taylor(f, K.one, K),",
"n = K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v,",
"K0, K1) if not K1.is_one(common): f = dmp_mul_ground(f, common, u, K0) if not",
"got %s\" % (u, u, j)) return _rec_diff_in(f, m, u, 0, j, K)",
"R) s, i = 1, 1 p, q = K.one, K.one for b,",
"in xrange(n, 0, -1): for j in xrange(0, i): f[j+1] += a*f[j] return",
"a, v, K) v, i = v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a,",
"d, v = dmp_degree(f, u), u-1 if d <= 0: return dmp_zero(v) else:",
"v = [], K.one, u-1 for i in xrange(0, m): c, n =",
"i, v = 1, 1, u-1 p = dmp_one(v, K) q = dmp_one(v,",
"u, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" if not u:",
"dup_inner_isolate_real_roots(f, cond, fast, K): I_pos.append((u, v, k)) g = dup_mirror(f, K) for s,",
"[], K.one for i in xrange(0, m): c, n = c*K(n), n-1 for",
"in `K[X]`. \"\"\" return dmp_inner_gcd(f, g, u, K)[0] def dup_rr_lcm(f, g, K): \"\"\"Computes",
"... f_n = f_1(f_2(... f_n)) and `f_2, ..., f_n` are monic and homogeneous",
"x1, y1, dx1, dy1, F1, K) x2, y2, dx2, dy2, F2 = dup_inner_refine_complex_root(f2,",
"i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, K.quo(c, K(n))) return",
"F(b1, d1))) f1, r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1, K)",
"while stack: a, b, c, d, f, k = stack.pop() A = dup_root_lower_bound(f,",
"= Fy F23 = _dup_sturm_shift(F3, hx, K) F24 = F4 k2 = _dup_inner_zeros(F21,",
"`g` in `K[X]`. \"\"\" if not u: return dup_lcm(f, g, K) if K.has_Field",
"h, Q = [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q, K))",
"dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\" f, n, b",
"if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f, g,",
"dmp_div(f, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd, u, K)",
"\"\"\" cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u): return cont for",
"over a field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g,",
"g, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`.",
"k) in I_neg ] + \\ [ (( u, v), k) for (u,",
"heuristic which means it may fail to compute the GCD. This will be",
"fast, K): I_pos.append((u, v, k)) g = dup_mirror(f, K) for s, t in",
"return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes polynomial LCM",
"a+b, c, c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1)))",
"A is not None: A = K(int(A)) else: A = K.zero if fast",
"K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial",
"K) if m <= 0 or dmp_zero_p(f, u): return f g, v =",
"K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a ring",
"`K[X]`. \"\"\" if not u: return dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT",
"scheme. \"\"\" if not a: return dup_TC(f, K) result = K.zero for c",
"refine a real root on (%s, %s)\" % (s, t)) fast = args.get('fast')",
"K1) g = dmp_convert(g, u, K0, K1) h, cff, cfg = dmp_zz_heu_gcd(f, g,",
"return dmp_eval(dmp_diff(g, m, v, K), a, v, K) v, i = v-1, i+1",
"t, m) in enumerate(I_pos[i+1:]): while not (s >= v or t <= u):",
"K) gc = dup_content(g, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f",
"= dmp_exquo(f, gcd, u, K) if K.has_Field or not K.is_Exact: return dmp_ground_monic(sqf, u,",
"c, 0, K) return h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate functional",
"C) f = dup_taylor(f, b, C) f = dup_scale(f, a, C) u =",
"e = dmp_eval(r, a, v, K) if not v: R = dup_strip([R]) e",
"c = -c h = dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K)",
"dmp_diff(f, 1, u, K) g, p, q = dmp_inner_gcd(f, h, u, K) all",
"for c in g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K):",
"return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K)",
"K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f, g,",
"dmp_neg(h, u, K) _, h = dmp_primitive(h, u, K) h = dmp_mul_term(h, c,",
"for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f, u, K): \"\"\"Returns content and",
"= dup_degree(R[i+1]) if du % 2 and dv % 2: s = -s",
"dmp_exquo, dup_prem, dmp_prem, dup_expand, dmp_expand, dup_add_mul, dup_sub_mul, dup_mul_ground, dmp_mul_ground, dup_quo_ground, dmp_quo_ground, dup_exquo_ground, dmp_exquo_ground,",
"International Symposium on Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal, Quebec, Canada,",
"Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F = K.float_domain() else:",
"dx2, dy2, F2 = r2 while not ((x2 >= x1+dx1 or x2+dx2 <=",
"u, K) B = 2*min(f_norm, g_norm) + 29 x = max(min(B, 99*K.sqrt(B)), 2*min(f_norm",
"f2, f1, k2, k1 if k1 == 0: continue if k1 == 1:",
"= 0 @cythonized(\"u\") def dmp_resultant(f, g, u, K): \"\"\"Computes resultant of two polynomials",
"[Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms, Journal of Symbolic Computation 7 (1989), pp.",
"DomainError(\"real root refinement not supported over %s\" % K) if s == t:",
"HomomorphismFailed: continue if K.is_one(P): r = R else: r = dmp_apply_pairs(r, R, _collins_crt,",
"= dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u, K) b = dmp_ground_LC(g, u,",
"dup_resultant(f, dup_diff(f, 1, K), K) return K.quo(r, c*K(s)) @cythonized(\"u,v,d,s\") def dmp_discriminant(f, u, K):",
"// 2: g.append(c - p) else: g.append(c) else: g = [ c %",
"K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K) coeff = -coeff if dmp_degree(f,",
"cff = ff // h cfg = gg // h h = _dup_zz_gcd_interpolate(h,",
"] + I_pos) _, factors = dup_sqf_list(f, K) if len(factors) == 1: ((f,",
"dmp_add(r, c, v, K) r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D,",
"y2+dy2 <= y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1,",
"return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD",
"else: break return [f] + F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence",
"= dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc) if not K.is_one(gcd): f =",
"F.denom(t) f = dup_transform(f, dup_strip([a, b]), dup_strip([c, d]), K) if dup_sign_variations(f, K) !=",
"j, K): \"\"\"XXX\"\"\" if i == j: return dmp_integrate(g, m, v, K) w,",
"dv = dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if du % 2",
"polynomial in `K[x]`. \"\"\" if not f: return True else: return not dup_degree(dup_gcd(f,",
"fc, gc = f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i] = K.exquo(coeff,",
"m <= 0 or dmp_zero_p(f, u): return f g, v = dmp_zeros(m, u-1,",
"\"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m, v, K) w, i =",
"x f.insert(0, g) h = (h-g) // x return f @cythonized(\"i,df,dg\") def dup_zz_heu_gcd(f,",
"0: continue if k2 == 1: roots.append(dup_inner_refine_real_root( f2, (a2, b2, c2, d2), cond,",
"disjoint complex root isolating rectangles for all quadrants. \"\"\" n, lc = dup_degree(f),",
"f g, v = dmp_zeros(m, u-1, K), u-1 for i, c in enumerate(reversed(f)):",
"@cythonized(\"u\") def dmp_lift(f, u, K): \"\"\"Convert algebraic coefficients to integers in `K[X]`. \"\"\"",
"K), K) return dup_monic(h, K) def dup_lcm(f, g, K): \"\"\"Computes polynomial LCM of",
"K.complex_domain() a, b = C(p, q), C(x, y) f = dup_convert(f, K, C)",
"K) h = dmp_exquo_ground(h, x, v, K) if K.is_negative(dmp_ground_LC(f, v+1, K)): return dmp_neg(f,",
"_dmp_zz_gcd_interpolate(h, x, v, K) h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f,",
"bound else: return None def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K):",
"k2 = k - k1 - r a2, b2, c2, d2 = b,",
"_ = dup_outer_refine_complex_root(f, x, y, dx, dy, F, eps, K) return x, y,",
"= dmp_mul(dmp_neg(lc, v, K), dmp_pow(c, m-k, v, K), v, K) f, g, m,",
"HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible, DomainError ) from sympy.ntheory import nextprime from sympy.utilities import",
"polynomial GCD in `Z[X]`. Given univariate polynomials `f` and `g` in `Z[X]`, returns",
"dmp_ground_trunc(f, p, u, K) G = dmp_ground_trunc(g, p, u, K) try: R =",
"dmp_zero_p(f, u): return cont for c in f[1:]: cont = dmp_gcd(cont, c, v,",
"dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f,",
"_dup_inner_sturm(f, K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y,",
"r[1] for r in group ]) for i, (x, y, dx, dy) in",
"def dmp_ff_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial over a ring.",
"d, c+d if k2 > 1 or (k1 > 0 and k2 ==",
"q = dmp_pow(c, d-1, v, K) c = dmp_exquo(p, q, v, K) b",
"quo(g, h) The algorithm is purely heuristic which means it may fail to",
"not df: F = dmp_LC(f, K) G = dmp_content(g, u, K) else: F",
"`K[x]`. \"\"\" if not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero,",
"cfg_, r = dup_div(g, h, K) if not r: h = dup_mul_ground(h, gcd,",
"dmp_diff_eval_in(f, m, a, j, u, K): \"\"\"Differentiate and evaluate a polynomial in `x_j`",
"return coeff, [] result, i = [], 1 h = dup_diff(f, 1, K)",
"if dmp_zero_p(f, u) or dmp_one_p(cont, v, K): return cont, f else: return cont,",
"= dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v, K) h =",
"(x, y, dx, dy) in roots: if x in groups: groups[x].append((x, y, dx,",
"r = dmp_div(g, h, u, K) if dmp_zero_p(r, u): h = dmp_mul_ground(h, gcd,",
"a2, b1, b2 = a2, a1, b2, b1 c1, c2, d1, d2 =",
"u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u,v,df,dg\")",
"dup_degree(R[i+1]) if du % 2 and dv % 2: s = -s lc,",
"c in enumerate(reversed(f)): n = i+1 for j in xrange(1, m): n *=",
"K), dmp_gcd(f, g, u, K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def",
"K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff, cfg_",
"v-1, i+1 return dmp_strip([ _rec_diff_eval(c, m, a, v, i, j, K) for c",
"if K.is_nonnegative(dmp_ground_LC(f, u, K)): return f, dmp_one(u, K), dmp_zero(u) else: return dmp_neg(f, u,",
"F: i >= 1 for i, (u, v, k) in enumerate(I_pos): for j,",
"i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0, dmp_quo_ground(c, K(n), v,",
"m, u, 0, j, K) @cythonized(\"m,n,i\") def dup_diff(f, m, K): \"\"\"m-th order derivative",
"u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ: return dmp_zz_collins_resultant(f, g, u, K) return",
"K) return h, cff, cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial",
"over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result is not",
"= dup_LC(R[-1], K)**i res = K.quo(res*p, q) return res, R def dup_resultant(f, g,",
"def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a",
"else: return f @cythonized(\"u,v,i,dg,df\") def dmp_zz_heu_gcd(f, g, u, K): \"\"\"Heuristic polynomial GCD in",
"dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h = dmp_subresultants(F, G,",
"i = {}, 0 while f: q, r = dup_div(f, h, K) if",
"= dup_monic(f, K) return a, f def dup_gcdex(f, g, K): \"\"\"Extended Euclidean algorithm",
"u, K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[X]`.",
"@cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m, a, v, i, j, K): \"\"\"XXX\"\"\" if i ==",
"sequence at x+I*y in p+I*q direction. \"\"\" C = K.complex_domain() a, b =",
"= _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K) if not r:",
"a - K.log(f[j], 2) Q.append(q // (j - i)) t += 1 if",
"c = dmp_ground(-K.one, v) B, D = [b], [d] if dmp_zero_p(f, u) or",
"R) if dmp_one_p(R[-2], u, K): return (dmp_LC(R[-1], K), R) s, i, v =",
"roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)) continue f1 = dup_taylor(f,",
"dmp_zero(u-1) K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1) cg, g",
"xrange(0, i): f[j+1] += a*f[j] return f def dup_transform(f, p, q, K): \"\"\"Evaluate",
"dup_strip([c, d]), K) if dup_sign_variations(f, K) != 1: raise RefinementFailed(\"there should be exactly",
"dg): F = dmp_LC(f, K) G = dmp_LC(g, K) else: if not df:",
"return dup_integrate(f, m, K) if m <= 0 or dmp_zero_p(f, u): return f",
"K): \"\"\"Differentiate and evaluate a polynomial in `x_j` at `a` in `K[X]`. \"\"\"",
"= v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for c",
"cont = dmp_ground_content(f, u, K) if K.is_one(cont): return cont, f else: return cont,",
"= (F1, F2, F3, F4) x, y, dx, dy, _ = dup_outer_refine_complex_root(f, x,",
"DomainError(\"ground domain must be algebraic\") g = dmp_raise(K.mod.rep, u+1, 0, K.dom) F =",
"if `f` is a square-free polynomial in `K[X]`. \"\"\" if dmp_zero_p(f, u): return",
"], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2 ], K), dup_sign_variations([",
"[ dmp_exquo(c, cont, v, K) for c in f ] @cythonized(\"u\") def dmp_rr_ground_primitive(f,",
"u, K): \"\"\"Resultant algorithm in `K[X]` using subresultant PRS. \"\"\" if not u:",
"GCD algorithm over a ring. \"\"\" if not (f or g): return [],",
"F = [] while True: result = _dup_decompose(f, K) if result is not",
"else: return None @cythonized(\"u\") def _dmp_ff_trivial_gcd(f, g, u, K): \"\"\"Handle trivial cases in",
"K): \"\"\"Returns content and a primitive polynomial over a ring. \"\"\" if dmp_zero_p(f,",
"\"\"\" a, b, c, d = K.one, K.zero, K.zero, K.one k = dup_sign_variations(f,",
"// 2: g -= x f.insert(0, g) h = (h-g) // x return",
"-1): f[i], b = b*f[i], b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate",
"dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u) for (u, v) in I_neg",
"lc = dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in f) while",
"m, n R = [f, g] d = n - m v =",
"done only in a field') a, b = [K.one], [] while g: q,",
"subresultants over a field. \"\"\" result = _dup_ff_trivial_gcd(f, g, K) if result is",
"cy, hx, hy, (F21, F22, F23, F24))) elif k2 > 1: stack.append((x, cy,",
"y, dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return",
"v, K) w, i = v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i,",
"in f: result *= a result += c return result @cythonized(\"u,v\") def dmp_eval(f,",
"dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast,",
"abs(dmp_ground_LC(g, u, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff = dmp_eval(f,",
"`f_2, ..., f_n` are monic and homogeneous polynomials of at least second degree.",
"f(x), f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>,",
"u, K) G = dmp_LC(g, K) v = u - 1 h =",
"g, K)[0] % p, p) v = u - 1 n = dmp_degree(f,",
"luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v) ==",
"u): h = dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg x =",
"res = dmp_quo(dmp_mul(res, p, v, K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\")",
"f = dup_taylor(dup_reverse(g), K.one, K) if not dup_eval(f, K.zero, K): f = dup_rshift(f,",
"method. The algorithm computes the polynomial GCD by evaluating polynomials f and g",
"enumerate(reversed(f)): n = i+1 for j in xrange(1, m): n *= i+j+1 g.insert(0,",
"**args): \"\"\"Clear denominators, i.e. transform `K_0` to `K_1`. \"\"\" if K1 is None:",
"0 and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2,",
"dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground,",
">= y1+dy1 or y2+dy2 <= y1)): x1, y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1,",
"def dup_invert(f, g, K): \"\"\"Compute multiplicative inverse of `f` in `F[x]/(g(x))`. \"\"\" s,",
"F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11, F12, F13, F14, hx,",
"g = { s : K.one } r = n // s for",
"n = list(f), dup_degree(f) for i in xrange(n, 0, -1): for j in",
"c in g ] if i < u - len(A) + 1: return",
"dup_resultant(f, g, K) if K.has_Field: if USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u,",
"cfg = dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c = dup_LC(h,",
"not u: return dup_diff(f, m, K) if m <= 0: return f n",
"result *= a result += c return result @cythonized(\"u,v\") def dmp_eval(f, a, u,",
"dmp_raise(d, v, 0, K) c = dmp_mul(d, dmp_sub(R, e, v, K), v, K)",
"not K.is_Exact: if USE_DMP_HEU_GCD: if K.is_QQ: try: return dmp_qq_heu_gcd(f, g, u, K) except",
"u-1 for i in xrange(0, m): c, n = c*K(n), n-1 for coeff",
"Horner scheme. \"\"\" if not u: return dup_eval(f, a, K) if not a:",
"return f if dmp_zero_p(f, u): return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0,",
"i = [], 1 h = dmp_diff(f, 1, u, K) g, p, q",
"elif k4 > 1: stack.append((cx, y, hx, hy, k4, F41, F42, F43, F44))",
"dmp_zero_p(h, u): k = dmp_degree(h, u) R.append(h) lc = dmp_LC(g, K) p =",
"K0.quo(c, cf), K0) cfg = dup_mul_ground(cfg, K0.quo(c, cg), K0) return h, cff, cfg",
"= _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42,",
"f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) coeff =",
"0, j, K) @cythonized(\"i,u\") def _rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i",
"(%s, %s) x (%s, %s) rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f,",
"evaluating polynomials f and g at certain points and computing (fast) integer GCD",
"_dmp_ff_trivial_gcd(f, g, u, K0) if result is not None: return result K1 =",
"j, u, K): \"\"\"Evaluate a polynomial at `x_j = a` in `K[X]` using",
"= dmp_content(f, u, K) G = dmp_LC(g, K) v = u - 1",
"u, K): \"\"\"Heuristic polynomial GCD in `Z[X]`. Given univariate polynomials `f` and `g`",
"K.zero, f else: return K.one, f @cythonized(\"u\") def dmp_ground_primitive(f, u, K): \"\"\"Returns content",
"constant `p` in `K`. \"\"\" if not u: return dup_trunc(f, p, K) v",
"K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K):",
"K): \"\"\"XXX\"\"\" if i == j: return dmp_eval(g, a, v, K) v, i",
"composition `f(g)` in `K[X]`. \"\"\" if not u: return dup_compose(f, g, K) if",
"!= n: return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y, dx, dy,",
"m: f, g = g, f n, m = m, n R =",
"tuple(dmp_zeros(3, u, K)) elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K),",
"or not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K)",
"d, i, F: i >= n s, t = dup_outer_refine_real_root(f, s, t, cond,",
"dy >= eps: x, y, dx, dy, F = dup_inner_refine_complex_root(f, x, y, dx,",
"algebraic domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s,",
"= dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h, cff, cfg =",
"f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1, K), K) sqf =",
"ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f and",
"K) v = u-1 return dmp_strip([ dmp_ground_trunc(c, p, v, K) for c in",
"else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients",
"K): \"\"\"Subresultant PRS algorithm in `K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g)",
"f, n = list(f), dup_degree(f) for i in xrange(n, 0, -1): for j",
"1, K) k = dup_sign_variations(f, K) if k == 0: continue if k",
"g, u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes",
"= K0.get_ring() common = K1.one for c in f: common = K1.lcm(common, K0.denom(c))",
"polynomial GCD in `Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result is",
"g, u, K) except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if",
"convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"real root refinement not supported over %s\"",
"= dmp_mul(q, dmp_pow(lc, dv*(1+d), v, K), v, K) _, p, q = dmp_inner_gcd(p,",
"y, dx, dy) in enumerate(group): if y == _max: upper.append((x, y, dx, dy))",
"d), cond, fast, K)) continue f1 = dup_taylor(f, K.one, K) a1, b1, c1,",
"K) G = dmp_LC(g, K) else: if not df: F = dmp_LC(f, K)",
"K): \"\"\"Computes resultant of two polynomials in `K[X]`. \"\"\" if not u: return",
"1 b = dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one, v) B,",
"def dmp_ground_primitive(f, u, K): \"\"\"Returns content and a primitive polynomial in `K[x]`. \"\"\"",
"norm of `f` in `K[x]`, useful over algebraic domains. \"\"\" if not K.is_Algebraic:",
"field in `K[x]`. \"\"\" h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K)",
"domains. \"\"\" if not K.is_Algebraic: raise DomainError(\"ground domain must be algebraic\") s, g",
"def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of a polynomial in `K[X]`.",
"may fail to compute the GCD. This will be signaled by raising an",
"Euclidean algorithm in `F[x]`. \"\"\" if not K.has_Field: raise DomainError('computation can be done",
"`True` if `f` is a square-free polynomial in `K[x]`. \"\"\" if not f:",
"you will need to switch to another GCD method. The algorithm computes the",
"got %s\" % (u, u, j)) return _rec_eval_in(f, a, u, 0, j, K)",
"h = dmp_ground_monic(h, u, K) cff = dmp_exquo(f, h, u, K) cfg =",
"K): \"\"\"Computes subresultant PRS of two polynomials in `K[x]`. \"\"\" return dup_inner_subresultants(f, g,",
"bound for `f`'s positive roots. \"\"\" bound = dup_root_upper_bound(dup_reverse(f), K) if bound is",
"= k - k1 - r a2, b2, c2, d2 = b, a+b,",
"upper bound for `f`'s positive roots. \"\"\" n, t, P = len(f), K.one,",
"roots.append((cx, cy, hx, hy, (F11, F12, F13, F14))) elif k1 > 1: stack.append((cx,",
"t, n, K, **args): \"\"\"Refine real root's approximating interval to the given precision.",
"\"\"\"Returns content and a primitive polynomial over a ring. \"\"\" if dmp_zero_p(f, u):",
"pass return dup_ff_prs_gcd(f, g, K) else: if USE_DUP_HEU_GCD: if K.is_ZZ: try: return dup_zz_heu_gcd(f,",
"= dmp_inject(f, u, K, front=True) r = dmp_resultant(g, h, u+1, K.dom) if dmp_sqf_p(r,",
"g, u, K): \"\"\"Computes polynomial GCD of `f` and `g` in `K[X]`. \"\"\"",
"t) def dup_inner_isolate_real_roots(f, cond, fast, K): \"\"\"Iteratively compute disjoint positive root isolation intervals.",
"def dup_rr_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\"",
"content and a primitive polynomial in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact:",
"return dmp_zero(u-1) A = dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a",
"dmp_degree(f, u) if n < m: return dmp_zero(u) deriv, c, v = [],",
"= [ _rec_eval_tail(c, i+1, A, u, K) for c in g ] if",
"dup_root_upper_bound(f, K): \"\"\"Compute LMQ upper bound for `f`'s positive roots. \"\"\" n, t,",
"dup_sqf_p(f, K): \"\"\"Returns `True` if `f` is a square-free polynomial in `K[x]`. \"\"\"",
"u, K) for c in g ] if i < u - len(A)",
"i)] + rest @cythonized(\"u,i\") def dmp_sqf_list(f, u, K, **args): \"\"\"Returns square-free decomposition of",
"< 0: f = dup_neg(f, K) f = list(reversed(f)) for i in xrange(0,",
"dup_refine_real_root(f, s, t, n, K, **args): \"\"\"Refine real root's approximating interval to the",
"i = v-1, i+1 return dmp_strip([ _rec_eval_in(c, a, v, i, j, K) for",
"m, K) if m <= 0 or dmp_zero_p(f, u): return f g, v",
"0: return [] if k == 1: roots = [dup_inner_refine_real_root( f, (a, b,",
"K), u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u))",
"@cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order derivative in `x_0` of a",
"dup_prs_resultant(f, g, K) if dmp_zero_p(f, u) or dmp_zero_p(g, u): return (dmp_zero(u-1), []) R,",
"f.insert(0, g) h = dmp_sub(h, g, v, K) h = dmp_exquo_ground(h, x, v,",
"j, K): \"\"\"XXX\"\"\" if i == j: return dmp_diff(g, m, v, K) w,",
"{ s : K.one } r = n // s for i in",
"`K[x]`. \"\"\" f, n = list(f), dup_degree(f) for i in xrange(n, 0, -1):",
"K.gcd(cont, c) if K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns GCD of",
"dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f, A, u, K): \"\"\"Evaluate a polynomial at",
"cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes polynomial GCD using subresultants over a field.",
"dup_add_term(h, c, 0, K) return h @cythonized(\"u\") def dmp_compose(f, g, u, K): \"\"\"Evaluate",
"c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u, K)",
"k)) g = dup_mirror(f, K) for s, t in dup_inner_isolate_real_roots(g, cond, fast, K):",
"while not (a % p) or not (b % p): p = K(nextprime(p))",
"\"\"\" if not a: return dup_TC(f, K) result = K.zero for c in",
"\"\"\" F = [] while True: result = _dup_decompose(f, K) if result is",
"coeff in f[1:]: result = dmp_mul_ground(result, a, v, K) result = dmp_add(result, coeff,",
"= v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c",
"not u: return dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if",
"\"\"\"Computes indefinite integral of `f` in `x_0` in `K[X]`. \"\"\" if not u:",
"v = 1, 1, u-1 p = dmp_one(v, K) q = dmp_one(v, K)",
"of multivariate coefficients. \"\"\" cont, v = dmp_LC(f, K), u-1 if dmp_zero_p(f, u):",
"b, c, d = a1, b1, c1, d1 else: f = dup_taylor(dup_reverse(g), K.one,",
"xrange(n-1, -1, -1): f[i], a = a*f[i], -a return f def dup_scale(f, a,",
"\"\"\" if dmp_zero_p(f, u): return True else: return not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u,",
"an univariate, square-free polynomial `f(x)` returns the associated Sturm sequence `f_0(x), ..., f_n(x)`",
"not K.is_ZZ: raise DomainError(\"real root refinement not supported over %s\" % K) if",
"for c in f ]) seq = [u, v] while seq[-1]: s =",
"dup_isolate_real_roots(f, K, **args): \"\"\"Isolate real roots using continued fractions approach. \"\"\" if K.is_QQ:",
"fast, K) if negative: return (-t, -s) else: return ( s, t) def",
"Q.append(q // (j - i)) t += 1 if not Q: continue P.append(min(Q))",
"elif zero_f: return (dmp_ground_monic(g, u, K), dmp_zero(u), dmp_ground(dmp_ground_LC(g, u, K), u)) elif zero_g:",
"u, K1) r = dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m * cg**n,",
"K) if k != n: return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x,",
"[], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one]",
"hx, hy, k3, F31, F32, F33, F34)) # Quadrant #4: +- F41 =",
"K) h = dmp_add_term(h, c, 0, u, K) return h @cythonized(\"s,n,r,i,j\") def _dup_right_decompose(f,",
"if dmp_zero_p(r, u): cfg_, r = dmp_div(g, h, u, K) if dmp_zero_p(r, u):",
"A*c, K.one if A >= K.one: f = dup_taylor(f, A, K) b, d",
"coeff.is_ground: monoms.append(monom) perms = variations([-1, 1], len(monoms), repetition=True) for perm in perms: G",
"f else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of",
"f: cont = K.gcd(cont, c) if K.is_one(cont): break return cont def dup_ff_content(f, K):",
"u, K)) return dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute",
"in `K[x]`. \"\"\" if m <= 0: return f n = dup_degree(f) if",
"F: abs(F(a, c) - F(b, d)) < eps else: cond = lambda a,",
"= -c h = dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K) cfg",
"only in an algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [], []",
"a, b, c, d, f, k = stack.pop() A = dup_root_lower_bound(f, K) if",
"not v: for c in g: common = K1.lcm(common, K0.denom(c)) else: w =",
"u-1 if d <= 0: return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2)",
"roots = [dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)] else: roots,",
"_dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4",
"Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F = [] while True: result",
"i >= 1 for i, (u, v, k) in enumerate(I_pos): for j, (s,",
"result is not None: return result df = dup_degree(f) dg = dup_degree(g) gcd,",
"if not args.get('include', False): return coeff, result else: (g, i), rest = result[0],",
"= dmp_ground_LC(g, u, K) v = u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r,",
"u == len(A)-1: return e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def",
"d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ]) dw =",
"and dg > 0: return None if not (df or dg): F =",
"len(A)-1: return e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\") def _rec_diff_eval(g, m,",
"of the input polynomials as a side effect. References ========== .. [Liao95] <NAME>,",
"return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant algorithm in",
"lc, i = dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw) q *=",
"u-1 if dmp_zero_p(f, u): return cont for c in f[1:]: cont = dmp_gcd(cont,",
"h = dup_exquo(dup_mul(f, g, K), dup_gcd(f, g, K), K) return dup_monic(h, K) def",
"x, y, K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q direction. \"\"\" C",
"%s)\" % (s, t)) fast = args.get('fast') if type(n) is not int: cond",
"or not K.is_Exact: return dup_ff_primitive(f, K) else: return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f,",
"h = dup_mul_ground(h, gcd, K) return h, cff, cfg x = 73794*x *",
"for i in xrange(n-1, -1, -1): f[i], b = b*f[i], b*a return f",
"not f: return f g = [K.zero]*m for i, c in enumerate(reversed(f)): n",
"c in f: common = K1.lcm(common, K0.denom(c)) if not K1.is_one(common): f = dup_mul_ground(f,",
"to switch to another GCD method. The algorithm computes the polynomial GCD by",
"u, K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD",
"K1) @cythonized(\"m,n,i,j\") def dup_integrate(f, m, K): \"\"\"Computes indefinite integral of `f` in `K[x]`.",
"if K.is_nonnegative(dmp_ground_LC(g, u, K)): return g, dmp_zero(u), dmp_one(u, K) else: return dmp_neg(g, u,",
"a field of characteristic zero, returns tuple `(f_1, f_2, ..., f_n)`, where:: f",
"1988, pp. 124-128 \"\"\" if not K.has_Field: raise DomainError('computation can be done only",
"Given an univariate polynomial `f` with coefficients in a field of characteristic zero,",
"step of complex root refinement algorithm. \"\"\" hx, hy = dx/2, dy/2 cx,",
"using Horner scheme. \"\"\" if not a: return dup_TC(f, K) result = K.zero",
"of a polynomial in `K[X]`. \"\"\" if not u: return dup_diff(f, m, K)",
"in GCD algorithm over a field. \"\"\" if not (f or g): return",
"K) if dmp_zero_p(h, u): result.append((p, i)) break g, p, q = dmp_inner_gcd(p, h,",
"g, K): \"\"\"Computes polynomial LCM over a field in `K[x]`. \"\"\" h =",
"K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1, F2, F3, F4, dx, dy, K)",
"K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm) + 29 x =",
"\"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\" if not (f",
"u, K) return (dmp_inflate(h, J, u, K), dmp_inflate(cff, J, u, K), dmp_inflate(cfg, J,",
"g: continue fc, gc = f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i]",
"m) I_pos[i] = (u, v, k) for i, (u, v, k) in enumerate(I_neg):",
"p], K), P*p) @cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm",
"`Q[x]`. \"\"\" result = _dup_ff_trivial_gcd(f, g, K0) if result is not None: return",
"< 0.5: break x, y, dx, dy = -B+r, -B-r, 2*B+r, 2*B+r roots,",
"dmp_sqf_p(r, u, K.dom): break else: f, s = dmp_compose(f, F, u, K), s+1",
"hx, K), K) F44 = _dup_sturm_mirror(Fy, K) k4 = _dup_inner_zeros(F41, F42, F43, F44,",
"GCD of those evaluations. The polynomial GCD is recovered from the integer image",
"\"\"\"Returns GCD of coefficients over a ring. \"\"\" if not u: return dup_rr_content(f,",
"integer GCD. \"\"\" f = [] while h: g = h % x",
"cfg = dup_exquo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K):",
"%s\" % (u, u, j)) if not j: return dmp_eval(dmp_diff(f, m, u, K),",
"in F3 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F4 ],",
"K) h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u, K)",
"c) if K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns GCD of coefficients",
"None: return result K1 = K0.get_ring() cf, f = dmp_ground_to_ring(f, u, K0, K1)",
"dmp_zero_p(g, u): return (dmp_zero(u-1), []) R, B, D = dmp_inner_subresultants(f, g, u, K)",
"dy1, F1), k1) multiplicity = {} for (_, (x, y, dx, dy, _),",
"+= c return result @cythonized(\"u,v\") def dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial",
"f = dup_mirror(f, K) I_neg = dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ ((-v,",
"step is to verify if the interpolated polynomial is the correct GCD. This",
"g, K), dup_gcd(f, g, K), K) return dup_monic(h, K) def dup_lcm(f, g, K):",
"dup_inner_subresultants(f, g, K)[0] @cythonized(\"s,i,du,dv,dw\") def dup_prs_resultant(f, g, K): \"\"\"Resultant algorithm in `K[x]` using",
"This will be signaled by raising an exception. In this case you will",
"upper, lower = [], [] for group in groups.values(): while len(group) > 1:",
"\"\"\" f, n, b = list(f), dup_degree(f), a for i in xrange(n-1, -1,",
"= dmp_rr_prs_gcd(fc, gc, u-1, K) if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u,",
"seq = [u, v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K))",
"if sign == -1: G[monom] = -G[monom] polys.append(dmp_from_dict(G, u, K)) return dmp_convert(dmp_expand(polys, u,",
"dup_sign_variations(f, K) if k == 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f,",
"zip(V1, V0)) // 2 def dup_inner_refine_complex_root(f, x, y, dx, dy, F, K): \"\"\"One",
"v] while seq[-1]: s = dup_rem(seq[-2], seq[-1], K) seq.append(dup_neg(s, K)) return seq[:-1] def",
"K) else: if not df: F = dmp_LC(f, K) G = dmp_content(g, u,",
"DomainError(\"ground domain must be algebraic\") s, g = 0, dmp_raise(K.mod.rep, 1, 0, K.dom)",
"coefficients over a ring. \"\"\" if not u: return dup_rr_content(f, K) cont, v",
"f'(x) f_n = -rem(f_{n-2}(x), f_{n-1}(x)) References ========== .. [Davenport88] <NAME>, <NAME>, <NAME>, Computer",
"u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m],",
"except HeuristicGCDFailed: pass return dmp_ff_prs_gcd(f, g, u, K) else: if USE_DMP_HEU_GCD: if K.is_ZZ:",
"stack = [], [] F1 = _dup_inner_sturm(f, K.one, K.zero, x, y, K) F2",
"f = dup_neg(f, K) f = list(reversed(f)) for i in xrange(0, n): if",
"def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a ring. \"\"\" cont =",
"sympy.ntheory import nextprime from sympy.utilities import ( cythonized, variations ) from random import",
"step, fast, K) s, t = dup_outer_refine_real_root(F_pos[m], s, t, step, fast, K) I_pos[i+j+1]",
"K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2) for i in xrange(0, HEU_GCD_MAX):",
"dup_degree(f) for s in xrange(2, df): if df % s != 0: continue",
"[] while True: result = _dup_decompose(f, K) if result is not None: f,",
"if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p), 1, u, K)",
"coeff, [] result, i = [], 1 h = dmp_diff(f, 1, u, K)",
"else: return dup_primitive(sqf, K)[1] @cythonized(\"u\") def dmp_sqf_part(f, u, K): \"\"\"Returns square-free part of",
"A, u, K) if u == len(A)-1: return e else: return dmp_strip(e, u",
"zeros in the given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K)",
"sqf = dup_exquo(f, gcd, K) if K.has_Field or not K.is_Exact: return dup_monic(sqf, K)",
"polynomial GCD from integer GCD. \"\"\" f = [] while not dmp_zero_p(h, v):",
"rectangles for all quadrants. \"\"\" n, lc = dup_degree(f), abs(dup_LC(f, K)) B =",
"u: return dup_discriminant(f, K) d, v = dmp_degree(f, u), u-1 if d <=",
"len(A) + 1: return h else: return dup_eval(h, A[-u+i-1], K) @cythonized(\"u\") def dmp_eval_tail(f,",
"of `f` in `x_j` in `K[X]`. \"\"\" if j < 0 or j",
"len(A)) e = _rec_eval_tail(f, 0, A, u, K) if u == len(A)-1: return",
"polynomial in `K[x]`. \"\"\" if not u: return dup_primitive(f, K) if dmp_zero_p(f, u):",
"gcd, K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r",
"dy, K) if k != n: return dup_inner_isolate_complex_roots(f, K) if k == 1:",
"raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K): \"\"\"Subresultant PRS algorithm in `K[x]`.",
"[] h, Q = [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)): Q.append(dup_mul(Q[-1], q,",
"g_norm // abs(dup_LC(g, K))) + 2) for i in xrange(0, HEU_GCD_MAX): ff =",
"u)) elif zero_g: return (dmp_ground_monic(f, u, K), dmp_ground(dmp_ground_LC(f, u, K), u), dmp_zero(u)) elif",
"univariate polynomial `f` with coefficients in a field of characteristic zero, returns tuple",
"bisection step of complex root refinement algorithm. \"\"\" hx, hy = dx/2, dy/2",
"_, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h = dmp_primitive(h, u, K)",
"d1), F(b1, d1) k = dup_sign_variations(f, K) if k == 1: a, b,",
"K) h = dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f, h, u,",
"h = dup_prem(f, g, K) h = dup_exquo_ground(h, b, K) return R, B,",
"e = _rec_eval_tail(f, 0, A, u, K) if u == len(A)-1: return e",
"v-1, i+1 return dmp_strip([ _rec_diff_in(c, m, w, i, j, K) for c in",
"= dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)): f = dmp_neg(f, u, K)",
"Sturm sequence of `f` in `F[x]`. Given an univariate, square-free polynomial `f(x)` returns",
"else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD of multivariate",
"return [], [], [] elif not f: return dup_monic(g, K), [], [dup_LC(g, K)]",
"I_neg = [], [] F_pos, F_neg = {}, {} for f, k in",
"= dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K) I_neg[i+j+1] = (s, t, m) I_neg[i]",
"return K.zero else: s = (-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r",
"F), F, **args) else: roots = [] _, factors = dup_sqf_list(f, K) for",
"fast, K) return sorted([ (-v, -u) for (u, v) in I_neg ] +",
"2 and dv % 2: s = -s lc, i = dmp_LC(R[i], K),",
"_rec_diff_eval(c, m, a, v, i, j, K) for c in g ], v)",
"dx, dy, eps, K): \"\"\"Refine a complex root using Wilf's global bisection algorithm.",
"u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g, u, K) @cythonized(\"u\") def dmp_inner_gcd(f,",
"u, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" if not",
"h = dmp_mul_term(h, c, 0, u, K) cff = dmp_exquo(f, h, u, K)",
"return None USE_DMP_SIMPLIFY_GCD = 1 @cythonized(\"u\") def _dmp_rr_trivial_gcd(f, g, u, K): \"\"\"Handle trivial",
"g ], v) @cythonized(\"u\") def dmp_eval_in(f, a, j, u, K): \"\"\"Evaluate a polynomial",
"= K(n)*K.exquo(c, K(n+m)), n-1 deriv.append(h) return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i,",
"not d: q = c else: q = dmp_pow(c, d-1, v, K) c",
"return f def dup_scale(f, a, K): \"\"\"Evaluate efficiently composition `f(a*x)` in `K[x]`. \"\"\"",
"dup_ff_lcm(f, g, K) else: return dup_rr_lcm(f, g, K) @cythonized(\"u\") def dmp_rr_lcm(f, g, u,",
"dmp_inner_gcd(p, q, v, K) if s < 0: p = dmp_neg(p, v, K)",
"y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K) F3 = _dup_inner_sturm(f,-K.one,",
"hx, hy, K) if k3 == 1: return (x, y, hx, hy, (F31,",
"K): \"\"\"Subresultant PRS algorithm in `K[X]`. \"\"\" if not u: return dup_inner_subresultants(f, g,",
"return (dmp_LC(R[-1], K), R) s, i, v = 1, 1, u-1 p =",
"if k1 == 1: roots.append((cx, cy, hx, hy, (F11, F12, F13, F14))) elif",
"c = -K.one B, D = [b], [d] if not f or not",
"not a: return dup_TC(f, K) result = K.zero for c in f: result",
"the integer image by interpolation. The final step is to verify if the",
"(_, (x, y, dx, dy, _), k) in roots: multiplicity[(x, y, dx, dy)]",
"a primitive polynomial in `K[x]`. \"\"\" if not u: return dup_primitive(f, K) if",
"dmp_mul_ground(h, gcd, u, K) return h, cff, cfg_ cfg = _dmp_zz_gcd_interpolate(cfg, x, v,",
"F, i = K.get_field(), 0 while not c or not cond(a, b, c,",
"_dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 == 1: return (x,",
"HomomorphismFailed('no luck') F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v)",
"K, convert=True), K.get_ring() elif not K.is_ZZ: raise DomainError(\"isolation of real roots not supported",
"result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not None: return result",
"dmp_primitive(g, u, K) h = dmp_subresultants(f, g, u, K)[-1] c, _, _ =",
"or not g: return (K.zero, []) R, B, D = dup_inner_subresultants(f, g, K)",
"dmp_pow(b, dv, v, K), v, K), dmp_pow(lc, du-dw, v, K), v, K) q",
"dup_sqf_list(f, K, **args) if K.has_Field or not K.is_Exact: coeff = dmp_ground_LC(f, u, K)",
"if dmp_sqf_p(r, u, K.dom): break else: f, s = dmp_compose(f, F, u, K),",
"for j, (s, t, m) in enumerate(I_pos[i+1:]): while not (s >= v or",
"h = dmp_subresultants(F, G, u, K)[-1] c, _, _ = dmp_rr_prs_gcd(fc, gc, u-1,",
"common content from a pair of polynomials in `K[x]`. \"\"\" fc = dup_content(f,",
"None: A = K(int(A)) else: A = K.zero if fast and A >",
"= -K.one B, D = [b], [d] if not f or not g:",
"K), q, v, K) return res, R @cythonized(\"u,v,n,m,N,M,B\") def dmp_zz_modular_resultant(f, g, p, u,",
"import ( gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed, RefinementFailed, NotInvertible,",
"F = dmp_primitive(f, u, K) gc, G = dmp_primitive(g, u, K) h =",
"*= p return r @cythonized(\"u,n,m\") def dmp_qq_collins_resultant(f, g, u, K0): \"\"\"Collins's modular resultant",
"dmp_multi_deflate((f, g), u, K) h, cff, cfg = _dmp_inner_gcd(f, g, u, K) return",
"dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p,",
"True: a += K.one if a == p: raise HomomorphismFailed('no luck') F =",
"1, u) M = dmp_degree_in(g, 1, u) B = n*M + m*N D,",
"[ dmp_exquo(cg, h, v, K) for cg in g ] return [h], cff,",
"= (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1,",
"K) for b, d in zip(B, D)[:-1]: du = dmp_degree(R[i-1], u) dv =",
"an algebraic domain') F, monoms, polys = dmp_to_dict(f, u), [], [] for monom,",
"True if args.get('sqf', False): I_pos = dup_inner_isolate_real_roots(f, cond, fast, K) f = dup_mirror(f,",
"g, u, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[X]`. \"\"\"",
"u, K) return _rec_diff_eval(f, m, a, u, 0, j, K) def dup_half_gcdex(f, g,",
"gcd(f, g), cff = quo(f, h) and cfg = quo(g, h) The algorithm",
"f in F1 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F2",
"s for i in xrange(1, s): coeff = K.zero for j in xrange(0,",
"f = dup_primitive(f, K) gc, g = dup_primitive(g, K) c = K.lcm(fc, gc)",
"to integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can be done",
"hy, k4, F41, F42, F43, F44)) if len(roots) == n: eps = args.get('eps')",
"dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G, p, u, K) except",
"s in xrange(2, df): if df % s != 0: continue h =",
"polynomial GCD, International Symposium on Symbolic and Algebraic Computation (ISSAC), ACM Press, Montreal,",
"K.float_domain() else: raise DomainError(\"isolation of complex roots not supported over %s\" % K)",
"6 def _dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f",
"u, K): \"\"\"m-th order derivative in `x_j` of a polynomial in `K[X]`. \"\"\"",
"u): u, v = dup_outer_refine_real_root(F_pos[k], u, v, step, fast, K) s, t =",
"reduces f and g variable by variable into a large integer. The final",
"number of sign variations of `f` in `K[x]`. \"\"\" prev, k = K.zero,",
"g, K): \"\"\"Computes polynomial GCD using subresultants over a ring. \"\"\" result =",
"dmp_eval(g, x, u, K) v = u - 1 if not (dmp_zero_p(ff, v)",
"R[-2] == [K.one]: return (dup_LC(R[-1], K), R) s, i = 1, 1 p,",
"= dmp_div(g, cfg, u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h,",
"hy, K) if k2 == 1: return (x, cy, hx, hy, (F21, F22,",
"f: if coeff*prev < 0: k += 1 if coeff: prev = coeff",
"= dup_LC(R[i], K), i+1 p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if",
"and `g` in `K[x]`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if",
"g, K) if result is not None: return result df = dup_degree(f) dg",
"= 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0):",
"k2 > 1 or (k1 > 0 and k2 == 1): f2 =",
"in dup_inner_isolate_complex_roots(g, F, **args): roots.append((g, r, k)) if len(factors) > 1: for i,",
"for i, (x, y, dx, dy) in enumerate(group): if y == _min: lower.append((x,",
"\"\"\" if not u: return dup_content(f, K) if K.has_Field or not K.is_Exact: return",
"eps = args.get('eps') if eps is not None: for i, (x, y, dx,",
"= K.gcd(fc, gc) if not K.is_one(gcd): f = dup_exquo_ground(f, gcd, K) g =",
"u, K): \"\"\"Evaluate a polynomial at `x_0 = a` in `K[X]` using Horner",
"= _dup_zz_gcd_interpolate(cff, x, K) h, r = dup_div(f, cff, K) if not r:",
"if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K))",
"those evaluations. The polynomial GCD is recovered from the integer image by interpolation.",
"K) except HeuristicGCDFailed: pass return dup_rr_prs_gcd(f, g, K) @cythonized(\"u\") def _dmp_inner_gcd(f, g, u,",
"g, K)[0] @cythonized(\"u,v,n,m,d,k\") def dmp_inner_subresultants(f, g, u, K): \"\"\"Subresultant PRS algorithm in `K[X]`.",
"is None: K1 = K0.get_ring() common = K1.one for c in f: common",
"1, u, K) if dmp_degree(F, v) == n: G = dmp_eval_in(g, gf_int(a, p),",
"h) and cfg = quo(g, h) The algorithm is purely heuristic which means",
"u, K) else: coeff, f = dmp_ground_primitive(f, u, K) if K.is_negative(dmp_ground_LC(f, u, K)):",
"dx, dy)) else: groups[x] = [(x, y, dx, dy)] upper, lower = [],",
"K) if dup_degree(f) <= 0: return [] eps, fast = args.get('eps'), args.get('fast') if",
"K) c = dmp_mul_ground(c, K(s), v, K) return dmp_quo(r, c, v, K) def",
"t) else: return (t, s) def dup_outer_refine_real_root(f, s, t, cond, fast, K): \"\"\"Refine",
"dup_LC(f, K) f = dup_to_raw_dict(f) g = { s : K.one } r",
"dup_rr_prs_gcd(f, g, K) result = _dmp_rr_trivial_gcd(f, g, u, K) if result is not",
"K): \"\"\"Evaluate functional composition `f(g)` in `K[x]`. \"\"\" if len(g) <= 1: return",
"u, K0) cff = dmp_convert(cff, u, K1, K0) cfg = dmp_convert(cfg, u, K1,",
"= F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f = dup_transform(f, dup_strip([a, b]),",
"K0, K1) g = dup_convert(g, K0, K1) h, cff, cfg = dup_zz_heu_gcd(f, g,",
"= dup_degree(f), abs(dup_LC(f, K)) B = 2*max(abs(c)/lc for c in f) while True:",
"not K.is_Exact: coeff = dup_LC(f, K) f = dup_monic(f, K) else: coeff, f",
"not f: return [] h, Q = [f[0]], [[K.one]] for i in xrange(0,",
"in F2 ], K), dup_sign_variations([ dup_eval(f, hx, K) for f in F3 ],",
"and evaluate a polynomial in `x_j` at `a` in `K[X]`. \"\"\" if j",
"F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) F = (F1, F2, F3, F4)",
"h, K) if not r: h = dup_mul_ground(h, gcd, K) return h, cff_,",
"dx, dy)] = k roots = multiplicity.keys() groups = {} for (x, y,",
"i)) break g, p, q = dup_inner_gcd(p, h, K) if all or dup_degree(g)",
"in `K[x]`. \"\"\" if not u: return dup_primitive(f, K) if dmp_zero_p(f, u): return",
"\"\"\"XXX\"\"\" common = K1.one if not v: for c in g: common =",
"u, K) cfg = dmp_exquo(g, h, u, K) return h, cff, cfg HEU_GCD_MAX",
"v, K) c = dmp_exquo(p, q, v, K) b = dmp_mul(dmp_neg(lc, v, K),",
"2) c = dmp_LC(f, K) r = dmp_resultant(f, dmp_diff(f, 1, u, K), u,",
"K)] else: roots, stack = [], [(a, b, c, d, f, k)] F",
"K), v, K) _, p, q = dmp_inner_gcd(p, q, v, K) if s",
"] return sum(v1 - v0 for v1, v0 in zip(V1, V0)) // 2",
"K) k4 = _dup_inner_zeros(F41, F42, F43, F44, hx, hy, K) if k4 ==",
"K): \"\"\"Computes polynomial GCD and cofactors of `f` and `g` in `K[x]`. \"\"\"",
"= dup_scale(f, A, K) a, c, A = A*a, A*c, K.one if A",
"in F2 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3 ],",
"cfg, u, K) if dmp_zero_p(r, u): cff_, r = dmp_div(f, h, u, K)",
"a, b = b, dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K),",
"args.get('all', False) while True: d = dmp_diff(p, 1, u, K) h = dmp_sub(q,",
"u, K0, K1) f = dmp_convert(f, u, K0, K1) g = dmp_convert(g, u,",
"else: raise DomainError(\"isolation of complex roots not supported over %s\" % K) squarefree",
"if K.is_one(lc): return f else: return dmp_quo_ground(f, lc, u, K) def dup_rr_content(f, K):",
"f = dup_convert(f, K0, K1) g = dup_convert(g, K0, K1) h, cff, cfg",
"True: h, _ = dmp_inject(f, 0, K, front=True) r = dmp_resultant(g, h, 1,",
"\"\"\" return K.one, f def dup_primitive(f, K): \"\"\"Returns content and a primitive polynomial",
"dup_sub_mul(a, q, b, K) a = dup_quo_ground(a, dup_LC(f, K), K) f = dup_monic(f,",
"of a polynomial in `K[X]`. \"\"\" if j < 0 or j >",
"f[i], b = b*f[i], b*a return f def dup_taylor(f, a, K): \"\"\"Evaluate efficiently",
"g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B = 2*min(f_norm, g_norm)",
"d = dmp_diff(p, 1, u, K) h = dmp_sub(q, d, u, K) if",
"return dup_rem(s, g, K) else: raise NotInvertible(\"zero divisor\") @cythonized(\"n,m,d,k\") def dup_inner_subresultants(f, g, K):",
"= dup_scale(f, a, C) u = dup_strip([ C.real(c) for c in f ])",
"= dup_inner_isolate_real_roots(f, cond, fast, K) return sorted([ (-v, -u) for (u, v) in",
"dmp_TC(f, K) result, v = dmp_LC(f, K), u-1 for coeff in f[1:]: result",
"if k != n: return dup_inner_isolate_complex_roots(f, K) if k == 1: roots.append((x, y,",
"\"\"\" n = dmp_degree(f, u) m = dmp_degree(g, u) if n < 0",
"u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in `K[x]`.",
"= dmp_mul(d, dmp_sub(R, e, v, K), v, K) r = dmp_add(r, c, v,",
"return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g,",
"a, a+b, c, c+d if not dup_eval(f, K.zero, K): return F(b1, d1), F(b1,",
"h = dmp_sub(q, d, u, K) if dmp_zero_p(h, u): result.append((p, i)) break g,",
"0: f, s, t, negative = dup_mirror(f, K), -t, -s, True else: raise",
"i+1, A, u, K) for c in g ] if i < u",
"dmp_zz_collins_resultant(f, g, u, K) return dmp_prs_resultant(f, g, u, K)[0] @cythonized(\"d,s\") def dup_discriminant(f, K):",
"K) return h, cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r =",
"K) r = dmp_ground_trunc(r, p, v, K) D = dup_mul(D, [K.one, -a], K)",
"k4, F41, F42, F43, F44)) if len(roots) == n: eps = args.get('eps') if",
"g, u, K): \"\"\"Handle trivial cases in GCD algorithm over a field. \"\"\"",
"= [R] e = [e] d = K.invert(dup_eval(D, a, K), p) d =",
"break R = dmp_zz_modular_resultant(F, G, p, v, K) e = dmp_eval(r, a, v,",
"_min: lower.append((x, y, dx, dy)) del group[i] break upper = sorted(upper, key=lambda r:",
"subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f, u)",
"u: return dup_primitive(f, K) if dmp_zero_p(f, u): return K.zero, f if K.has_Field or",
"the associated Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x),",
"precision is reached. \"\"\" while dx >= eps and dy >= eps: x,",
"1, K) h = dup_sub(q, d, K) if not h: result.append((p, i)) break",
"if u == len(A)-1: return e else: return dmp_strip(e, u - len(A)) @cythonized(\"m,v,i,j\")",
"= _dup_sturm_shift(F3, hx, K) F24 = F4 k2 = _dup_inner_zeros(F21, F22, F23, F24,",
"(f2, r2, k2) in enumerate(roots[i+1:]): x2, y2, dx2, dy2, F2 = r2 while",
"def dmp_diff(f, m, u, K): \"\"\"m-th order derivative in `x_0` of a polynomial",
"_dup_left_decompose(f, h, K): \"\"\"XXX\"\"\" g, i = {}, 0 while f: q, r",
"y2, dx2, dy2, F2 = r2 while not ((x2 >= x1+dx1 or x2+dx2",
"= K.zero for j in xrange(0, i): if not n+j-i in f: continue",
"K) a, c, A = A*a, A*c, K.one if A >= K.one: f",
"f_2, ..., f_n)`, where:: f = f_1 o f_2 o ... f_n =",
"raise DomainError('computation can be done only in an algebraic domain') F, monoms, polys",
"`K[X]`. \"\"\" if not u: return dup_monic(f, K) if dmp_zero_p(f, u): return f",
"u, K): \"\"\"Reduce `K[X]` polynomial modulo a polynomial `p` in `K[Y]`. \"\"\" return",
"root refinement algorithm. \"\"\" hx, hy = dx/2, dy/2 cx, cy = x",
"dmp_eval(f, a, u, K): \"\"\"Evaluate a polynomial at `x_0 = a` in `K[X]`",
"F = dmp_eval_in(f, gf_int(a, p), 1, u, K) if dmp_degree(F, v) == n:",
"g, u, K) h = [ dmp_exquo(ch, b, v, K) for ch in",
"p, q, x, y, K): \"\"\"Compute Sturm sequence at x+I*y in p+I*q direction.",
"image by interpolation. The final step is to verify if the result is",
"return [ dup_taylor(f, c, K) for f in F ] def _dup_sturm_mirror(F, K):",
"dmp_raise([K.one,-K.unit], u, 0, K) s = 0 while True: h, _ = dmp_inject(f,",
"m, a, v, i, j, K) for c in g ], v) @cythonized(\"m,j,u\")",
"of a Sturm sequence at its origin. \"\"\" return [ dup_mirror(f, K) for",
"of a polynomial in `K[X]`. \"\"\" if not u: return dup_sqf_list(f, K, **args)",
"n-1 return deriv @cythonized(\"u,v,m,n,i\") def dmp_diff(f, m, u, K): \"\"\"m-th order derivative in",
"m) in enumerate(I_pos[i+1:]): while not (s >= v or t <= u): u,",
"= v-1 for c in g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1))",
"h, k, m-k B.append(b) D.append(d) h = dmp_prem(f, g, u, K) h =",
"xrange(0, HEU_GCD_MAX): ff = dmp_eval(f, x, u, K) gg = dmp_eval(g, x, u,",
"args.get('eps'), args.get('fast') if eps is not None: cond = lambda a, b, c,",
"== 1: return (x, cy, hx, hy, (F21, F22, F23, F24)) # Quadrant",
"= dup_prem(f, g, K) h = dup_mul_ground(h, b, K) while h: k =",
"F42, F43, F44, hx, hy, K) if k4 == 1: roots.append((cx, y, hx,",
"[], [] elif not f: if K.is_nonnegative(dup_LC(g, K)): return g, [], [K.one] else:",
"v, K) f, g, m, d = g, h, k, m-k B.append(b) D.append(d)",
"another GCD method. The algorithm computes the polynomial GCD by evaluating polynomials f",
"cont = K.gcd(cont, c) if K.is_one(cont): break return cont def dup_ff_content(f, K): \"\"\"Returns",
"1 for i, (u, v, k) in enumerate(I_pos): for j, (s, t, m)",
"in F1 ], K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F2 ],",
"cfg @cythonized(\"u\") def dmp_ff_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over",
"K1) return dmp_exquo_ground(r, c, u-1, K0) USE_COLLINS_RESULTANT = 0 @cythonized(\"u\") def dmp_resultant(f, g,",
"u) if zero_f and zero_g: return tuple(dmp_zeros(3, u, K)) elif zero_f: if K.is_nonnegative(dmp_ground_LC(g,",
"x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k = _dup_inner_zeros(F1,",
"a primitive polynomial over a ring. \"\"\" if dmp_zero_p(f, u): return K.zero, f",
"lc, u, K) def dup_rr_content(f, K): \"\"\"Returns GCD of coefficients over a ring.",
"K.is_ZZ: try: return dmp_zz_heu_gcd(f, g, u, K) except HeuristicGCDFailed: pass return dmp_rr_prs_gcd(f, g,",
"dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K): \"\"\"Returns GCD",
"< n else: cond = lambda a, b, c, d, i, F: i",
"F44, hx, hy, K) if k4 == 1: roots.append((cx, y, hx, hy, (F41,",
"in `K[x]`. \"\"\" if len(g) <= 1: return dup_strip([dup_eval(f, dup_LC(g, K), K)]) if",
"K): I_neg.append((s, t, k)) F_pos[k], F_neg[k] = f, g step = lambda a,",
"return sorted([ (-v, -u) for (u, v) in I_neg ] + I_pos) _,",
"F = dup_inner_refine_complex_root(f, x, y, dx, dy, F, K) return x, y, dx,",
"if result is not None: return result df = dup_degree(f) dg = dup_degree(g)",
"\"\"\"Compute LMQ upper bound for `f`'s positive roots. \"\"\" n, t, P =",
"j, u, K): \"\"\"Computes indefinite integral of `f` in `x_j` in `K[X]`. \"\"\"",
"u), dmp_zero(u) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return None @cythonized(\"u\")",
"K) F13 = F3 F14 = _dup_sturm_mirror(_dup_sturm_shift(Fy, hy, K), K) k1 = _dup_inner_zeros(F11,",
"F33 = _dup_sturm_mirror(Fx, K) F34 = _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32,",
"u, K): \"\"\"Computes polynomial LCM of `f` and `g` in `K[X]`. \"\"\" if",
"dmp_raise(K.mod.rep, u+1, 0, K.dom) F = dmp_raise([K.one,-K.unit], u, 0, K) s = 0",
"dmp_degree_in, dup_to_dict, dmp_to_dict, dup_from_dict, dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one,",
"the given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for f",
"dup_from_raw_dict, dmp_raise, dmp_apply_pairs, dmp_inject, dmp_zeros ) from sympy.polys.densearith import ( dup_add_term, dmp_add_term, dup_mul_term,",
"algebraic coefficients to integers in `K[X]`. \"\"\" if not K.is_Algebraic: raise DomainError('computation can",
"(j - i)) t += 1 if not Q: continue P.append(min(Q)) if not",
"Computation (ISSAC), ACM Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" result =",
"= K.get_field() while stack: a, b, c, d, f, k = stack.pop() A",
"i, (f1, r1, k1) in enumerate(roots): x1, y1, dx1, dy1, F1 = r1",
"(f or g): return [], [], [] elif not f: if K.is_nonnegative(dup_LC(g, K)):",
"x, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = [] while",
"for i in xrange(n-1, -1, -1): f[i], a = a*f[i], -a return f",
"for (u, v) in I_pos ]) I_pos, I_neg = [], [] F_pos, F_neg",
"c, A = A*a, A*c, K.one if A >= K.one: f = dup_taylor(f,",
"v, step, fast, K) s, t = dup_outer_refine_real_root(F_neg[m], s, t, step, fast, K)",
"s < 0: p = -p i = dup_degree(R[-2]) res = dup_LC(R[-1], K)**i",
"- p) else: g.append(c) else: g = [ c % p for c",
"= u - 1 B = K(2)*K.factorial(n+m)*A**m*B**n r, p, P = dmp_zero(v), K.one,",
"h = dmp_ground_primitive(h, u, K)[1] cff_, r = dmp_div(f, h, u, K) if",
"= [K.one], [] while g: q, r = dup_div(f, g, K) f, g",
"else: s = (-1)**((d*(d-1)) // 2) c = dup_LC(f, K) r = dup_resultant(f,",
"+ F else: break return [f] + F def dup_sturm(f, K): \"\"\"Computes the",
"h = dup_mul_ground(h, c, K) cff = dup_exquo(f, h, K) cfg = dup_exquo(g,",
"\"\"\"Helper function for `dmp_inner_gcd()`. \"\"\" if K.has_Field or not K.is_Exact: if USE_DMP_HEU_GCD: if",
"-B-r, 2*B+r, 2*B+r roots, stack = [], [] F1 = _dup_inner_sturm(f, K.one, K.zero,",
"a` in `K[X]` using Horner scheme. \"\"\" if j < 0 or j",
"return dmp_zero(v) else: s = (-1)**((d*(d-1)) // 2) c = dmp_LC(f, K) r",
"F def dup_sturm(f, K): \"\"\"Computes the Sturm sequence of `f` in `F[x]`. Given",
"K) G = dmp_ground_trunc(g, p, u, K) try: R = dmp_zz_modular_resultant(F, G, p,",
"return result df = dup_degree(f) dg = dup_degree(g) gcd, f, g = dup_extract(f,",
"i, (u, v, k) in enumerate(I_neg): for j, (s, t, m) in enumerate(I_neg[i+1:]):",
"K) return h, cff_, cfg_ cff = _dup_zz_gcd_interpolate(cff, x, K) h, r =",
"cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K): \"\"\"Computes",
"in xrange(0, n): if f[i] >= 0: continue a, Q = K.log(-f[i], 2),",
"y1, dx1, dy1, F1 = dup_inner_refine_complex_root(f1, x1, y1, dx1, dy1, F1, K) x2,",
"DomainError('computation can be done only in a field') a, b = [K.one], []",
"coeff, result else: (g, i), rest = result[0], result[1:] g = dup_mul_ground(g, coeff,",
"dmp_rr_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a ring in `K[X]`. \"\"\"",
"u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K): \"\"\"Computes",
"dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h, u): k = dmp_degree(h, u)",
"@cythonized(\"u\") def dmp_inner_gcd(f, g, u, K): \"\"\"Computes polynomial GCD and cofactors of `f`",
"else: f, s = dmp_compose(f, F, u, K), s+1 return s, f, r",
"else: coeff, f = dup_primitive(f, K) if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K)",
"return deriv @cythonized(\"m,v,w,i,j\") def _rec_diff_in(g, m, v, i, j, K): \"\"\"XXX\"\"\" if i",
"m, u, K), a, u, K) return _rec_diff_eval(f, m, a, u, 0, j,",
"\"\"\" if K.has_Field or not K.is_Exact: if USE_DUP_HEU_GCD: if K.is_QQ: try: return dup_qq_heu_gcd(f,",
"m, v, K), a, v, K) v, i = v-1, i+1 return dmp_strip([",
"= dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h = dup_add(h, q,",
"1: stack.append((cx, cy, hx, hy, k1, F11, F12, F13, F14)) # Quadrant #2:",
"F4 = stack.pop() hx, hy = dx/2, dy/2 cx, cy = x +",
"K.invert(dup_eval(D, a, K), p) d = dup_mul_ground(D, d, K) d = dmp_raise(d, v,",
"= t + a - K.log(f[j], 2) Q.append(q // (j - i)) t",
"`f(g)` in `K[X]`. \"\"\" if not u: return dup_compose(f, g, K) if dmp_zero_p(f,",
"dmp_exquo(cf, h, v, K) for cf in f ] cfg = [ dmp_exquo(cg,",
"def dmp_rr_prs_gcd(f, g, u, K): \"\"\"Computes polynomial GCD using subresultants over a ring.",
"polynomial GCD is recovered from the integer image by interpolation. The final step",
"in `K[X]`, useful over algebraic domains. \"\"\" if not u: return dup_sqf_norm(f, K)",
"K.is_Exact: return dup_ff_content(f, K) else: return dup_rr_content(f, K) @cythonized(\"u,v\") def dmp_content(f, u, K):",
"v) or dmp_zero_p(gg, v)): h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h",
"f: return [] h, Q = [f[0]], [[K.one]] for i in xrange(0, dup_degree(f)):",
"enumerate(roots): x1, y1, dx1, dy1, F1 = r1 for j, (f2, r2, k2)",
"not None: f, h = result F = [h] + F else: break",
"Sturm sequence `f_0(x), ..., f_n(x)` defined by:: f_0(x), f_1(x) = f(x), f'(x) f_n",
"u, K), u), dmp_zero(u)) elif USE_DMP_SIMPLIFY_GCD: return _dmp_simplify_gcd(f, g, u, K) else: return",
"dmp_zero(v) while dup_degree(D) <= B: while True: a += K.one if a ==",
"dup_diff(f, m, K): \"\"\"m-th order derivative of a polynomial in `K[x]`. \"\"\" if",
"if s < 0: p = -p i = dup_degree(R[-2]) res = dup_LC(R[-1],",
"`x_0 = a` in `K[X]` using Horner scheme. \"\"\" if not u: return",
"f: return K.zero else: return K.one def dup_content(f, K): \"\"\"Returns GCD of coefficients",
"else: return K.one @cythonized(\"u\") def dmp_ground_content(f, u, K): \"\"\"Returns GCD of coefficients in",
"if not K1.is_one(common): f = dup_mul_ground(f, common, K0) if not args.get('convert'): return common,",
"cff, cfg_ cfg = _dup_zz_gcd_interpolate(cfg, x, K) h, r = dup_div(g, cfg, K)",
"F_pos, F_neg = {}, {} for f, k in factors: for u, v",
"return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K) def dup_refine_real_root(f, s, t,",
"dup_eval(f, K.zero, K) for f in F4 ], K), ] return sum(v1 -",
"for b, d in zip(B, D)[:-1]: du = dup_degree(R[i-1]) dv = dup_degree(R[i ])",
"] if i < u - len(A) + 1: return h else: return",
"def dup_discriminant(f, K): \"\"\"Computes discriminant of a polynomial in `K[x]`. \"\"\" d =",
"2: g -= x f.insert(0, g) h = (h-g) // x return f",
"dup_exquo(g, h, K) return h, cff, cfg @cythonized(\"u\") def dmp_rr_prs_gcd(f, g, u, K):",
"g: common = K1.lcm(common, _rec_ground_to_ring(c, w, K0, K1)) return common @cythonized(\"u\") def dmp_ground_to_ring(f,",
"1, 1, u-1 p = dmp_one(v, K) q = dmp_one(v, K) for b,",
"h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck')",
"root isolation intervals. \"\"\" a, b, c, d = K.one, K.zero, K.zero, K.one",
"c, c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1, d1), F(b1, d1))) f1,",
"k1 == 1: roots.append((cx, cy, hx, hy, (F11, F12, F13, F14))) elif k1",
"not f or not g: return (K.zero, []) R, B, D = dup_inner_subresultants(f,",
"= T_m o T_n` where `T_n` and `T_m` are Chebyshev polynomials. References ==========",
"content and a primitive polynomial over a field. \"\"\" return K.one, f def",
"@cythonized(\"u,v,n,m\") def dmp_zz_collins_resultant(f, g, u, K): \"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\"",
"result else: (g, i), rest = result[0], result[1:] g = dup_mul_ground(g, coeff, K)",
"dup_ff_primitive(f, K): \"\"\"Returns content and a primitive polynomial over a field. \"\"\" return",
"polynomials in `K[X]`. \"\"\" fc = dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u,",
"h, cff, cfg USE_DUP_HEU_GCD = 1 USE_DMP_HEU_GCD = 1 def dup_inner_gcd(f, g, K):",
"K), dmp_inflate(cfg, J, u, K)) def dup_gcd(f, g, K): \"\"\"Computes polynomial GCD of",
"dup_div(f, h, K) if not r: h = dup_mul_ground(h, gcd, K) return h,",
"dup_convert(f, K0, K) else: raise DomainError(\"isolation of complex roots not supported over %s\"",
"1 if coeff: prev = coeff return k def dup_root_upper_bound(f, K): \"\"\"Compute LMQ",
"T_m = T_m o T_n` where `T_n` and `T_m` are Chebyshev polynomials. References",
"b, A*c + d if not dup_eval(f, K.zero, K): roots.append((F(b, d), F(b, d)))",
"f, g = dup_extract(f, g, K) if df == 0 or dg ==",
"algorithms, Journal of Symbolic Computation 7 (1989), pp. 445-456 \"\"\" F = []",
"return gcd, f, g def dup_mirror(f, K): \"\"\"Evaluate efficiently composition `f(-x)` in `K[x]`.",
"sturm[-1]: s = dup_rem(sturm[-2], sturm[-1], K) sturm.append(dup_neg(s, K)) return sturm[:-1] @cythonized(\"u\") def dmp_lift(f,",
"h = dup_mul(h, p, K) q = dup_mul_ground(q, c, K) h = dup_add(h,",
"dup_sign_variations([ dup_eval(f, hy, K) for f in F2 ], K), dup_sign_variations([ dup_eval(f, hx,",
"K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r",
"dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1) g = dup_convert(g, K0, K1)",
"continue fc, gc = f[n+j-i], g[s-j] coeff += (i - r*j)*fc*gc g[s-i] =",
"u, K) b = dmp_ground_LC(g, u, K) v = u - 1 B",
"f ]) v = dup_strip([ C.imag(c) for c in f ]) seq =",
"= dup_exquo_ground(h, b, K) return R, B, D def dup_subresultants(f, g, K): \"\"\"Computes",
"= dmp_degree(f, u), u-1 if d <= 0: return dmp_zero(v) else: s =",
"dmp_pow(dmp_ground(-K.one, v), d+1, v, K) c = dmp_ground(-K.one, v) B, D = [b],",
"d2), cond, fast, K)) else: stack.append((a2, b2, c2, d2, f2, k2)) return sorted(roots)",
"I_neg ] + \\ [ (( u, v), k) for (u, v, k)",
"u) if n < 0 or m < 0: return dmp_zero(u-1) A =",
"raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD from",
"= _dup_sturm_shift(F4, hy, K) k3 = _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K)",
"73794*x * K.sqrt(K.sqrt(x)) // 27011 raise HeuristicGCDFailed('no luck') def dup_qq_heu_gcd(f, g, K0): \"\"\"Heuristic",
"u, j)) if not j: return dmp_eval(dmp_diff(f, m, u, K), a, u, K)",
"of `f` in `K[x]`. \"\"\" if m <= 0 or not f: return",
"[dup_inner_refine_real_root( f, (a, b, c, d), cond, fast, K)] else: roots, stack =",
"(%s, %s) rectangle\" % (x, y, x+dx, y+dy)) def dup_outer_refine_complex_root(f, x, y, dx,",
"K), u, K) return dmp_ground_monic(h, u, K) @cythonized(\"u\") def dmp_lcm(f, g, u, K):",
"h, cff, cfg = dmp_zz_heu_gcd(ff, gg, v, K) h = _dmp_zz_gcd_interpolate(h, x, v,",
"dup_isolate_complex_roots(f, K, **args): \"\"\"Isolate complex roots using Wilf's global bisection algorithm. \"\"\" if",
"h = dmp_mul_term(h, b, 0, u, K) while not dmp_zero_p(h, u): k =",
"= dup_exquo(g, h, K) return h, cff, cfg def dup_ff_prs_gcd(f, g, K): \"\"\"Computes",
"g, h return None def dup_decompose(f, K): \"\"\"Computes functional decomposition of `f` in",
"in the given rectangle. \"\"\" V1 = [ dup_sign_variations([ dup_eval(f, hx, K) for",
"i, r in enumerate(upper): upper[i] = (r, multiplicity[r]) for i, r in enumerate(lower):",
"dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate, dmp_inflate,",
"== 0: continue if k == 1: roots.append(dup_inner_refine_real_root( f, (a, b, c, d),",
"such that:: h = gcd(f, g), cff = quo(f, h) and cfg =",
"\"\"\" cont = K.zero for c in f: cont = K.gcd(cont, c) if",
"_dup_inner_sturm(f,-K.one, K.zero, x+dx, y+dy, K) F4 = _dup_inner_sturm(f, K.zero,-K.one, x, y+dy, K) k",
"for r in group ]) for i, (x, y, dx, dy) in enumerate(group):",
"a real root on (%s, %s)\" % (s, t)) fast = args.get('fast') if",
"- r*j)*fc*gc g[s-i] = K.exquo(coeff, i*r*lc) return dup_from_raw_dict(g, K) @cythonized(\"i\") def _dup_left_decompose(f, h,",
"result F = [h] + F else: break return [f] + F def",
"= a, a+b, c, c+d if not dup_eval(f, K.zero, K): return F(b1, d1),",
"K): \"\"\"Resultant algorithm in `K[x]` using subresultant PRS. \"\"\" if not f or",
"t)) return dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K) def dup_refine_real_root(f, s,",
"complex roots using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F",
"], u) dw = dmp_degree(R[i+1], u) if du % 2 and dv %",
"(a2, b2, c2, d2), cond, fast, K)) else: stack.append((a2, b2, c2, d2, f2,",
"F41 = _dup_sturm_shift(F1, hx, K) F42 = F2 F43 = _dup_sturm_mirror(_dup_sturm_shift(Fx, hx, K),",
"in `K[x]`. \"\"\" n = dup_degree(f) m = dup_degree(g) if n < m:",
"Press, Montreal, Quebec, Canada, 1995, pp. 240--247 \"\"\" if not u: return dup_zz_heu_gcd(f,",
"dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F, G, p, v, K) e",
"g ], v) @cythonized(\"m,j,u\") def dmp_integrate_in(f, m, j, u, K): \"\"\"Computes indefinite integral",
"polynomial LCM over a field in `K[X]`. \"\"\" h = dmp_exquo(dmp_mul(f, g, u,",
"\"\"\"Collins's modular resultant algorithm in `Z[X]`. \"\"\" n = dmp_degree(f, u) m =",
"F(b1, d1), F(b1, d1) k = dup_sign_variations(f, K) if k == 1: a,",
"dup_mul_ground(h, gcd, K) return h, cff, cfg x = 73794*x * K.sqrt(K.sqrt(x)) //",
"b, c, d, f, k = stack.pop() A = dup_root_lower_bound(f, K) if A",
"d1), F(b1, d1))) f1, r = dup_rshift(f1, 1, K), 1 k1 = dup_sign_variations(f1,",
"_rec_eval_tail(g, i, A, u, K): \"\"\"XXX\"\"\" if i == u: return dup_eval(g, A[-1],",
"roots.append((x, y, dx, dy, (F1, F2, F3, F4))) elif k > 1: stack.append((x,",
"for i, (u, v, k) in enumerate(I_neg): for j, (s, t, m) in",
"27011 raise HeuristicGCDFailed('no luck') @cythonized(\"v\") def _dmp_zz_gcd_interpolate(h, x, v, K): \"\"\"Interpolate polynomial GCD",
"2) for i in xrange(0, HEU_GCD_MAX): ff = dup_eval(f, x, K) gg =",
"dmp_one(v, K) q = dmp_one(v, K) for b, d in zip(B, D)[:-1]: du",
"= K(nextprime(p)) while not (a % p) or not (b % p): p",
"USE_COLLINS_RESULTANT and K.is_QQ: return dmp_qq_collins_resultant(f, g, u, K) else: if USE_COLLINS_RESULTANT and K.is_ZZ:",
"r = a, a+b, c, c+d, 0 if not dup_eval(f1, K.zero, K): roots.append((F(b1,",
"algorithm computes the polynomial GCD by evaluating polynomials f and g at certain",
"a, c, A = A*a, A*c, K.one if A >= K.one: f =",
"(-K.one)**(d+1) c = -K.one B, D = [b], [d] if not f or",
"== 1: roots.append((x, y, hx, hy, (F31, F32, F33, F34))) elif k3 >",
"return dmp_zero(u - len(A)) e = _rec_eval_tail(f, 0, A, u, K) if u",
"`T_m` are Chebyshev polynomials. References ========== .. [Kozen89] <NAME>, <NAME>, Polynomial decomposition algorithms,",
"= K.log(-f[i], 2), [] for j in xrange(i+1, n): if f[j] <= 0:",
"K.one, K.zero, x, y, K) F2 = _dup_inner_sturm(f, K.zero, K.one, x+dx, y, K)",
"g, u, K1) r = dmp_convert(r, u-1, K1, K0) c = K0.convert(cf**m *",
"dup_inner_isolate_complex_roots(dup_convert(f, K, F), F, **args) else: roots = [] _, factors = dup_sqf_list(f,",
"return None def dup_inner_refine_real_root(f, (a, b, c, d), cond, fast, K): \"\"\"Refine a",
"K): \"\"\"Computes indefinite integral of `f` in `K[x]`. \"\"\" if m <= 0",
"def dmp_subresultants(f, g, u, K): \"\"\"Computes subresultant PRS of two polynomials in `K[X]`.",
"99*K.sqrt(B)), 2*min(f_norm // abs(dmp_ground_LC(f, u, K)), g_norm // abs(dmp_ground_LC(g, u, K))) + 2)",
"1995, pp. 240--247 \"\"\" result = _dup_rr_trivial_gcd(f, g, K) if result is not",
"p), 1, u, K) if dmp_degree(G, v) == m: break R = dmp_zz_modular_resultant(F,",
"_dup_zz_gcd_interpolate(h, x, K): \"\"\"Interpolate polynomial GCD from integer GCD. \"\"\" f = []",
"K) F = dup_sub_mul(h, s, f, K) t = dup_exquo(F, g, K) return",
"x, y, dx, dy, F, eps, K) return x, y, dx, dy def",
"common, dup_convert(f, K0, K1) @cythonized(\"v,w\") def _rec_ground_to_ring(g, v, K0, K1): \"\"\"XXX\"\"\" common =",
"!= 1: raise RefinementFailed(\"there should be exactly one root on (%s, %s)\" %",
"GCD of `f` and `g` in `K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\")",
"need to switch to another GCD method. The algorithm computes the polynomial GCD",
"= dup_degree(h) R.append(h) lc = dup_LC(g, K) if not d: q = c",
"return f lc = dmp_ground_LC(f, u, K) if K.is_one(lc): return f else: return",
"K), dup_sign_variations([ dup_eval(f, K.zero, K) for f in F3 ], K), dup_sign_variations([ dup_eval(f,",
"`K[x]`. \"\"\" if m <= 0: return f n = dup_degree(f) if n",
"return [(g, i)] + rest def dup_extract(f, g, K): \"\"\"Extracts common content from",
"= n*M + m*N D, a = [K.one], -K.one r = dmp_zero(v) while",
"k) for i, (u, v, k) in enumerate(I_neg): for j, (s, t, m)",
"= dmp_degree(R[i ], u) dw = dmp_degree(R[i+1], u) if du % 2 and",
"F3 ], K), dup_sign_variations([ dup_eval(f, hy, K) for f in F4 ], K),",
"in `K[x]`. \"\"\" if m <= 0 or not f: return f g",
"if K.is_negative(dmp_ground_LC(cont, v, K)): return dmp_neg(cont, v, K) else: return cont @cythonized(\"u,v\") def",
"s, t = F(a, c), F(b, d) if s <= t: return (s,",
"F33, F34, hx, hy, K) if k3 == 1: return (x, y, hx,",
"gcd, f, g = dmp_ground_extract(f, g, u, K) f_norm = dmp_max_norm(f, u, K)",
"return result h = dup_subresultants(f, g, K)[-1] h = dup_monic(h, K) cff =",
"and cfg = quo(g, h) The algorithm is purely heuristic which means it",
"= v-1, i+1 return dmp_strip([ _rec_integrate_in(c, m, w, i, j, K) for c",
"u, K)[-1] c, _, _ = dmp_ff_prs_gcd(fc, gc, u-1, K) _, h =",
"eps, K): \"\"\"Refine a complex root using Wilf's global bisection algorithm. \"\"\" if",
"dx, dy, F, eps, K) return roots else: return dup_inner_isolate_complex_roots(f, K) def dup_isolate_complex_roots(f,",
"K) @cythonized(\"u\") def dmp_ff_lcm(f, g, u, K): \"\"\"Computes polynomial LCM over a field",
"1: return (cx, cy, hx, hy, (F11, F12, F13, F14)) # Quadrant #2:",
"c, d, i, F: abs(F(a, c) - F(b, d)) < n else: cond",
"= _dup_inner_zeros(F31, F32, F33, F34, hx, hy, K) if k3 == 1: roots.append((x,",
"g, u, K) def dup_trunc(f, p, K): \"\"\"Reduce `K[x]` polynomial modulo a constant",
"dw = dmp_degree(R[i+1], u) if du % 2 and dv % 2: s",
"where:: f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n)) and",
"= dmp_mul_ground(h, gcd, u, K) return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x,",
"or (k1 > 0 and k2 == 1): f2 = dup_taylor(dup_reverse(f), K.one, K)",
"interpolated polynomial is the correct GCD. This gives cofactors of the input polynomials",
"n < m: f, g = g, f n, m = m, n",
"= dmp_ground_content(f, u, K) gc = dmp_ground_content(g, u, K) gcd = K.gcd(fc, gc)",
"j < %s expected, got %s\" % (u, u, j)) if not j:",
"= dmp_content(g, u, K) else: F = dmp_content(f, u, K) G = dmp_LC(g,",
"K) for cf in f ] cfg = [ dmp_exquo(cg, h, v, K)",
"g: common = K1.lcm(common, K0.denom(c)) else: w = v-1 for c in g:",
"if K.is_negative(dmp_ground_LC(h, u, K)): h = dmp_neg(h, u, K) _, h = dmp_primitive(h,",
"df = dmp_degree(f, u) dg = dmp_degree(g, u) if df > 0 and",
"= dmp_max_norm(f, u, K) B = dmp_max_norm(g, u, K) a = dmp_ground_LC(f, u,",
"dmp_convert(dmp_expand(polys, u, K), u, K, K.dom) def dup_sign_variations(f, K): \"\"\"Compute the number of",
"a+b, c, c+d if not dup_eval(f, K.zero, K): return F(b1, d1), F(b1, d1)",
"F14, hx, hy, K) if k1 == 1: return (cx, cy, hx, hy,",
"g = [K.zero]*m for i, c in enumerate(reversed(f)): n = i+1 for j",
"cy = x + hx, y + hy F1, F2, F3, F4 =",
"`K[x]`. \"\"\" return dup_inner_gcd(f, g, K)[0] @cythonized(\"u\") def dmp_gcd(f, g, u, K): \"\"\"Computes",
"roots using Wilf's global bisection algorithm. \"\"\" if K.is_ZZ or K.is_QQ: F =",
"G = dmp_eval_in(g, gf_int(a, p), 1, u, K) if dmp_degree(G, v) == m:",
"`g` modulo a prime `p`. \"\"\" if not u: return gf_int(dup_prs_resultant(f, g, K)[0]",
"\"\"\"Divides all coefficients by `LC(f)` in `K[X]`. \"\"\" if not u: return dup_monic(f,",
"return h, cff_, cfg_ cff = _dmp_zz_gcd_interpolate(cff, x, v, K) h, r =",
"K, **args): \"\"\"Compute disjoint complex root isolating rectangles for all quadrants. \"\"\" n,",
"m, j, u, K): \"\"\"Computes indefinite integral of `f` in `x_j` in `K[X]`.",
"p *= b**dv * lc**(du-dw) q *= lc**(dv*(1+d)) if s < 0: p",
"a ring. \"\"\" zero_f = dmp_zero_p(f, u) zero_g = dmp_zero_p(g, u) if zero_f",
"u, K) return h, cff_, cfg x = 73794*x * K.sqrt(K.sqrt(x)) // 27011",
"K1) cg, g = dup_ground_to_ring(g, K0, K1) f = dup_convert(f, K0, K1) g",
"or K.is_QQ: K0, K = K, K.float_domain() f = dup_convert(f, K0, K) else:",
"F11, F12, F13, F14)) # Quadrant #2: -+ F21 = _dup_sturm_shift(Fx,-hx, K) F22",
"= K.get_field() a, c = F.numer(s), F.denom(s) b, d = F.numer(t), F.denom(t) f",
"dmp_degree_in(f, 1, u) M = dmp_degree_in(g, 1, u) B = n*M + m*N",
"using subresultant PRS. \"\"\" if not u: return dup_prs_resultant(f, g, K) if dmp_zero_p(f,",
"if dmp_degree(R[-1], u) > 0: return (dmp_zero(u-1), R) if dmp_one_p(R[-2], u, K): return",
"= dup_zz_heu_gcd(f, g, K1) h = dup_convert(h, K1, K0) c = dup_LC(h, K0)",
"result K1 = K0.get_ring() cf, f = dup_ground_to_ring(f, K0, K1) cg, g =",
"cont, f else: return cont, dup_exquo_ground(f, cont, K) def dup_ff_primitive(f, K): \"\"\"Returns content",
"1, u-1 p = dmp_one(v, K) q = dmp_one(v, K) for b, d",
"dmp_mul_ground(f, common, u, K0) if not args.get('convert'): return common, f else: return common,",
"`K[x]`. \"\"\" f, n, a = list(f), dup_degree(f), -K.one for i in xrange(n-1,",
"1): f2 = dup_taylor(dup_reverse(f), K.one, K) if not dup_eval(f2, K.zero, K): f2 =",
"f if K.is_negative(dup_LC(f, K)): f = dup_neg(f, K) gcd = dup_gcd(f, dup_diff(f, 1,",
"if K.has_Field or not K.is_Exact: return dmp_ff_lcm(f, g, u, K) else: return dmp_rr_lcm(f,",
"if all or dup_degree(g) > 0: result.append((g, i)) i += 1 if not",
"final step is to verify if the interpolated polynomial is the correct GCD.",
"for i, (x, y, dx, dy, F) in enumerate(roots): roots[i] = dup_outer_refine_complex_root(f, x,",
"not K.is_Exact: coeff = dmp_ground_LC(f, u, K) f = dmp_ground_monic(f, u, K) else:",
"dx, dy, k, F1, F2, F3, F4 = stack.pop() hx, hy = dx/2,",
"efficiently Taylor shift `f(x + a)` in `K[x]`. \"\"\" f, n = list(f),",
"from sympy.polys.galoistools import ( gf_int, gf_crt ) from sympy.polys.polyerrors import ( HeuristicGCDFailed, HomomorphismFailed,",
"dmp_from_dict, dup_LC, dmp_LC, dmp_ground_LC, dup_TC, dmp_TC, dmp_ground_TC, dmp_zero, dmp_one, dmp_ground, dmp_zero_p, dmp_one_p, dmp_multi_deflate,",
"[gcd], f, g f_norm = dup_max_norm(f, K) g_norm = dup_max_norm(g, K) B =",
"return result @cythonized(\"v,i,j\") def _rec_eval_in(g, a, v, i, j, K): \"\"\"XXX\"\"\" if i",
"return dup_rr_primitive(f, K) @cythonized(\"u,v\") def dmp_primitive(f, u, K): \"\"\"Returns multivariate content and a",
"d, u, K) if dmp_zero_p(h, u): result.append((p, i)) break g, p, q ="
] |
[
"data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape)",
"''' d = (l.dX != dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel())",
"data.reshape() l = L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X > 0]",
"dX[X > 0] = l.scale dX[X <= 0] = l.scale * l.alpha *",
"= l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX =",
"assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1",
"L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0]",
"l.eval() p = np.exp(X) n = np.exp(-X) ty = (p - n) /",
"- 5000) / 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l",
"X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b =",
"assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1,",
"= l.dY[b] ''' d = (l.dX != dX) print (l.dX[d], dX[d]) ''' assert",
"assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx =",
"*= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000) /",
"b = (X > 0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b] =",
"/ 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data)",
"numpy as np def test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1,",
"l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1,",
"L.Tanh(data) y = l.eval() p = np.exp(X) n = np.exp(-X) ty = (p",
"= np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX *= l.dY print (dX,",
"1)) data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y = l.eval() p",
"np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX != dX) print (l.dX[d], dX[d])",
"data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape",
"1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.SELU(data) y =",
"np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) -",
"n) / (p + n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX",
"L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha",
"ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y,",
"np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY",
"X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward()",
"np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX *= l.dY print (dX, l.dX)",
"np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p - n)",
"(p - n) / (p + n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape)",
"+ enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel()) def test_relu():",
"= (l.dX != dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(),",
"= L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] =",
"/ 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.SELU(data)",
"l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape)",
"assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1,",
"np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1,",
"X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(),",
"np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX *=",
"(l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X =",
"= np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0] = l.scale dX[X <=",
"(p + n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0",
"l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1))",
"l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert",
"1)) data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape ==",
"enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel()) def test_relu(): X",
"data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape)",
"ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY =",
"10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert",
"l.backward() dX = 1.0 - np.square(p - n) / np.square(p + n) dX",
"Y = np.zeros(X.shape) b = (X > 0) Y[b] = X[b] dX =",
"assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y =",
"l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p - n) / np.square(p",
"= l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def",
"Y[b] = X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX",
"L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X > 0] = l.scale *",
"= ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\")",
"- l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X",
"test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data =",
"l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X)",
"(l.dX != dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel())",
"*= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000)",
"* 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel())",
"enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1,",
"!= dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def",
"l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha",
"/ 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data)",
"* l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1,",
"0] = l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) -",
"1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape",
"dX = 1.0 - np.square(p - n) / np.square(p + n) dX *=",
"1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert",
"1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape()",
"print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) - 5000)",
"dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX != dX) print",
"+ n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 -",
"l = L.Tanh(data) y = l.eval() p = np.exp(X) n = np.exp(-X) ty",
"np def test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1))",
"assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 +",
"l = L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X > 0] =",
"* np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000)",
"> 0] = l.scale dX[X <= 0] = l.scale * l.alpha * np.exp(X[X<=0])",
"= np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b = (X > 0)",
"l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape)",
"l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1,",
"ty = np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0] ty[X<=0] = l.scale",
"import mobula.layers as L import numpy as np def test_sigmoid(): X = ((np.arange(10000)",
"l.backward() Y = np.zeros(X.shape) b = (X > 0) Y[b] = X[b] dX",
"0] = l.scale dX[X <= 0] = l.scale * l.alpha * np.exp(X[X<=0]) dX",
"1 dX[X<=0] = l.alpha dX *= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX)",
"L import numpy as np def test_sigmoid(): X = ((np.arange(10000) - 5000) /",
"L.Data(X, \"data\") data.reshape() l = L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X",
"== X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b",
"dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu():",
"test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data =",
"np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0]",
"l.alpha dX *= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X",
"l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0",
"def test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data",
"dX[X<=0] = l.alpha dX *= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def",
"= np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0",
"l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx",
"np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1",
"as np def test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1,",
"10 l.backward() Y = np.zeros(X.shape) b = (X > 0) Y[b] = X[b]",
"l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) -",
"> 0] = l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0])",
"* 10 l.backward() Y = np.zeros(X.shape) b = (X > 0) Y[b] =",
"l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X =",
"\"data\") data.reshape() l = L.Tanh(data) y = l.eval() p = np.exp(X) n =",
"= L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward()",
"(dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) - 5000) /",
"1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape()",
"data.reshape() l = L.Tanh(data) y = l.eval() p = np.exp(X) n = np.exp(-X)",
"= np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p - n) / np.square(p +",
"= l.eval() ty = np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0] ty[X<=0]",
"1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y = l.eval()",
"np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p - n) / np.square(p + n)",
"= (X > 0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b]",
"1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.SELU(data) y",
"l.eval() ty = np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0] ty[X<=0] =",
"np.allclose(dX, l.dX) def test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1,",
"= l.eval() p = np.exp(X) n = np.exp(-X) ty = (p - n)",
"L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward()",
"assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel()) def test_relu(): X =",
"l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape)",
"np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b = (X > 0) Y[b]",
"\"data\") data.reshape() l = L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X >",
"np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1,",
"/ (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel())",
"X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX != dX)",
"test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data =",
"= L.Tanh(data) y = l.eval() p = np.exp(X) n = np.exp(-X) ty =",
"np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx)",
"def test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data",
"l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X >",
"y = l.eval() p = np.exp(X) n = np.exp(-X) ty = (p -",
"data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y = l.eval() ty =",
"X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X,",
"(enx / np.square(1 + enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000) -",
"l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1))",
"l.dY[b] ''' d = (l.dX != dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(),",
"= l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY =",
"l.backward() dX = np.zeros(X.shape) dX[X > 0] = l.scale dX[X <= 0] =",
"1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape",
"1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y = l.eval()",
"dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1))",
"* X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0]",
"> 0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d",
"X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] =",
"(1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) *",
"= np.exp(X) n = np.exp(-X) ty = (p - n) / (p +",
"np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 +",
"import numpy as np def test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1,",
"l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0] = l.scale dX[X",
"l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX *= l.dY",
"data.reshape() l = L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0]",
"\"data\") data.reshape() l = L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0] =",
"assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1,",
"/ 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data)",
"def test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data",
"= np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx /",
"* X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y,",
"= np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty)",
"np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape)",
"data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y = l.eval() p =",
"1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y =",
"mobula.layers as L import numpy as np def test_sigmoid(): X = ((np.arange(10000) -",
"p = np.exp(X) n = np.exp(-X) ty = (p - n) / (p",
"dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX *= l.dY print",
"L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY",
"5000) / 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l =",
"= np.zeros(X.shape) b = (X > 0) Y[b] = X[b] dX = np.zeros(X.shape)",
"ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0] = l.scale",
"0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d =",
"1)) data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y = l.eval() ty",
"= L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward()",
"* l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X",
"L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y = l.eval() p = np.exp(X) n",
"= np.exp(-X) ty = (p - n) / (p + n) assert np.allclose(y,",
"= 1.0 - np.square(p - n) / np.square(p + n) dX *= l.dY",
"= np.zeros(X.shape) dX[X > 0] = l.scale dX[X <= 0] = l.scale *",
"- np.square(p - n) / np.square(p + n) dX *= l.dY assert np.allclose(dX,",
"- n) / (p + n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward()",
"data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape",
"* np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX =",
"l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) *",
"1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.SELU(data) y = l.eval()",
"1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y",
"dX = np.zeros(X.shape) dX[X > 0] = l.scale dX[X <= 0] = l.scale",
"= l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha)",
"L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward()",
"np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000) /",
"Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1,",
"d = (l.dX != dX) print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert",
"test_selu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data =",
"test_sigmoid(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data =",
"data = L.Data(X, \"data\") data.reshape() l = L.SELU(data) y = l.eval() ty =",
"= L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10",
"y = l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha *",
"assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p -",
"l.dX) def test_tanh(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1))",
"= X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX !=",
"l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y",
"* (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward()",
"= l.alpha dX *= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh():",
"((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape()",
"dX[b] = l.dY[b] ''' d = (l.dX != dX) print (l.dX[d], dX[d]) '''",
"X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty)",
"n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p",
"l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 /",
"= L.Data(X, \"data\") data.reshape() l = L.SELU(data) y = l.eval() ty = np.zeros(X.shape)",
"= np.zeros(X.shape) dX[b] = l.dY[b] ''' d = (l.dX != dX) print (l.dX[d],",
"assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0]",
"dX[X <= 0] = l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY assert",
"np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000)",
"l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b = (X",
"= np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0] ty[X<=0] = l.scale *",
"assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) - 5000)",
"l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert",
"dX[X>0] = 1 dX[X<=0] = l.alpha dX *= l.dY print (dX, l.dX) assert",
"enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx",
"+ enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1,",
"/ np.square(1 + enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000)",
"ty = (p - n) / (p + n) assert np.allclose(y, ty) l.dY",
"dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU(): X = ((np.arange(10000) - 5000)",
"dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000)",
"np.exp(-X) ty = (p - n) / (p + n) assert np.allclose(y, ty)",
"ty[X<=0] = l.scale * (l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY",
"print (l.dX[d], dX[d]) ''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X",
"1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.ReLU(data) l.reshape() assert",
"1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y =",
"= 1 dX[X<=0] = l.alpha dX *= l.dY print (dX, l.dX) assert np.allclose(dX,",
"= l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0] = l.alpha * X[X<=0]",
"n = np.exp(-X) ty = (p - n) / (p + n) assert",
"y = l.eval() ty = np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0]",
"np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0] =",
"ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = 1.0 - np.square(p - n) /",
"(l.alpha * np.exp(X[X<=0]) - l.alpha) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX",
"== X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10 l.backward() enx = np.exp(-X) assert",
"np.square(1 + enx) * l.dY).ravel()) def test_relu(): X = ((np.arange(10000) - 5000) /",
"l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) *",
"\"data\") data.reshape() l = L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY =",
"as L import numpy as np def test_sigmoid(): X = ((np.arange(10000) - 5000)",
"np.zeros(X.shape) dX[X > 0] = l.scale dX[X <= 0] = l.scale * l.alpha",
"l.dY = np.random.random(l.Y.shape) * 10 l.backward() Y = np.zeros(X.shape) b = (X >",
"np.exp(X) n = np.exp(-X) ty = (p - n) / (p + n)",
"= l.scale dX[X <= 0] = l.scale * l.alpha * np.exp(X[X<=0]) dX *=",
"ty[X > 0] = l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha *",
"ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX",
"''' assert np.allclose(l.Y.ravel(), Y.ravel()) assert np.allclose(l.dX.ravel(), dX.ravel()) def test_selu(): X = ((np.arange(10000) -",
"/ 1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data)",
"l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX) def test_PReLU():",
"(X > 0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b] = l.dY[b] '''",
"/ (p + n) assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape) l.backward() dX =",
"ty) l.dY = np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] =",
"= np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X>0] = 1 dX[X<=0] = l.alpha dX",
"dX *= l.dY print (dX, l.dX) assert np.allclose(dX, l.dX) def test_tanh(): X =",
"np.zeros(X.shape) b = (X > 0) Y[b] = X[b] dX = np.zeros(X.shape) dX[b]",
"1)) data = L.Data(X, \"data\") data.reshape() l = L.SELU(data) y = l.eval() ty",
"l.scale dX[X <= 0] = l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY",
"def test_relu(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data",
"0] = l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX, l.dX)",
"def test_PReLU(): X = ((np.arange(10000) - 5000) / 1000.0).reshape((-1, 1, 1, 1)) data",
"<= 0] = l.scale * l.alpha * np.exp(X[X<=0]) dX *= l.dY assert np.allclose(dX,",
"= (p - n) / (p + n) assert np.allclose(y, ty) l.dY =",
"l.backward() enx = np.exp(-X) assert np.allclose(l.Y.ravel(), (1.0 / (1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(),",
"= X[X>0] ty[X<=0] = l.alpha * X[X<=0] assert np.allclose(y, ty) l.dY = np.random.random(l.Y.shape)",
"1.0 - np.square(p - n) / np.square(p + n) dX *= l.dY assert",
"1000.0).reshape((-1, 1, 1, 1)) data = L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y",
"np.zeros(X.shape) ty[X > 0] = l.scale * X[X>0] ty[X<=0] = l.scale * (l.alpha",
"l = L.PReLU(data) y = l.eval() ty = np.zeros(X.shape) ty[X>0] = X[X>0] ty[X<=0]",
"L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY",
"np.random.random(l.Y.shape) l.backward() dX = np.zeros(X.shape) dX[X > 0] = l.scale dX[X <= 0]",
"1)) data = L.Data(X, \"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape ==",
"= L.Data(X, \"data\") data.reshape() l = L.PReLU(data) y = l.eval() ty = np.zeros(X.shape)",
"= L.Data(X, \"data\") data.reshape() l = L.Tanh(data) y = l.eval() p = np.exp(X)",
"np.square(p - n) / np.square(p + n) dX *= l.dY assert np.allclose(dX, l.dX)",
"= L.ReLU(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY = np.random.random(l.Y.shape) * 10",
"= L.SELU(data) y = l.eval() ty = np.zeros(X.shape) ty[X > 0] = l.scale",
"\"data\") data.reshape() l = L.Sigmoid(data) l.reshape() assert l.Y.shape == X.shape l.forward() l.dY =",
"(1.0 + enx)).ravel()) assert np.allclose(l.dX.ravel(), (enx / np.square(1 + enx) * l.dY).ravel()) def"
] |
[
"config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except",
"if tracks: tries = 10 while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth)",
"input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"]",
"dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\",",
"%(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help message for",
"\"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\"",
"config file\\n\" ) spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print(",
"config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\")",
") spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after (default: %(default)s)\",",
"(Note: the URI doesn't need to be accessible. By default we use http://localhost)\"",
"27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm",
"Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information (available on the app",
"starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds)",
"configparser import ConfigParser from datetime import datetime from getpass import getpass from hashlib",
"the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \")",
"spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"],",
"hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while tries:",
"pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks = [] for",
"file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show",
"spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 - On the app page, click",
"a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings",
"import os import pickle import sys from argparse import ArgumentParser from configparser import",
"import md5 from math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from",
"following command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser()",
"scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date and",
"file to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't",
"Redirect URIs field and save. (Note: the URI doesn't need to be accessible.",
"libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script parameters",
"url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\") session_key =",
"the instructions and enter the requested information to create the config file\\n\" )",
"config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"],",
"LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries remaining\")",
"app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information",
"open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file:",
"main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config",
"\"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\")",
"librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries =",
"print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\")",
"write to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save",
"print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file)",
"to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file)",
"\") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf",
"save. (Note: the URI doesn't need to be accessible. By default we use",
"to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\",",
"config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"],",
"try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"],",
"f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args = vars(args) if dict_args: args.func(**dict_args) else:",
"parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks to libre.fm\",",
"at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in",
"Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\")",
"tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\")",
"not found and no arguments passed\") print(\"Run the following command to generate a",
"played after this date and time will be scrobbled. Must follow search-after-fmt format\",",
"help=\"Scrobble your Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\",",
"= kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] )",
"1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as",
"\") print( \"3 - On the app page, click on Edit Settings, enter",
"to be accessible. By default we use http://localhost)\" ) print(\"4 - Input the",
"ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 - On the app",
"page, click on Edit Settings, enter a URI on the Redirect URIs field",
"sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp",
"config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"]",
"accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify",
"and time will be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\",",
"help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate",
"spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect",
"date and time you listened the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\",",
"2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and no arguments",
"\"--config\", default=\"config.ini\", help=\"Config file to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\",",
") help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args =",
"KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify =",
"need to be accessible. By default we use http://localhost)\" ) print(\"4 - Input",
"def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions and",
"wizard to generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file",
"skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when",
"spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"),",
"if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"]",
"from argparse import ArgumentParser from configparser import ConfigParser from datetime import datetime from",
") spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token before starting the",
"dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or",
"\"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\":",
"auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime(",
"open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if",
"try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\":",
";)\") if __name__ == \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser =",
"spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument(",
"with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"]",
"librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries",
"found and no arguments passed\") print(\"Run the following command to generate a config",
"kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"]",
"reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1)",
"value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if",
") librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard",
"time will be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime",
"def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs):",
"pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return",
"tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key, value",
"track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date and time will",
"1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session!",
"config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default:",
"for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args",
"spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" *",
"spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after (default: %(default)s)\", )",
"create the config file\\n\" ) spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify",
"kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to",
"On the app page, click on Edit Settings, enter a URI on the",
"to save non-scrobbled tracks in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\",",
"else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or",
"settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help",
"spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"]",
"= spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] =",
"add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args",
"to scrobble!\") print(\"Organizing tracks...\") tracks = [] for track in spotify_tracks: try: track_info",
"help=\"Force refresh your Spotify Client Token before starting the routine\", ) last_played =",
"kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int(",
"help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\",",
"import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config",
"import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth",
"tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new",
"API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") )",
"= 10 while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try:",
"no arguments passed\") print(\"Run the following command to generate a config file:\") print(f\"\\t{sys.argv[0]}",
"and no arguments passed\") print(\"Run the following command to generate a config file:\")",
"config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else",
"in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"]",
"except WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new session...\") skg =",
"= skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else:",
"print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create an app on",
"<reponame>yyyyyyyan/spotify-libre-scrobbler import os import pickle import sys from argparse import ArgumentParser from configparser",
"if __name__ == \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser(",
"print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password:",
"type=int, help=\"UNIX timestamp (milliseconds) representing the date and time you listened the last",
"from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename =",
"username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config",
"librefm_auth = {key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or",
"non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as",
"sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] =",
"URI doesn't need to be accessible. By default we use http://localhost)\" ) print(\"4",
"\"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as err: print(\"Error reading track metadata\")",
"getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config to",
"print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict()",
"config.write(config_file) print(\"Saved config file! ;)\") if __name__ == \"__main__\": parser = ArgumentParser() subparsers",
"ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def",
"= scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's",
"tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify",
"librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries}",
") scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case of any",
"the config file\\n\" ) spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\")",
"scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser",
"config = ConfigParser() print( \"Follow the instructions and enter the requested information to",
"print( \"3 - On the app page, click on Edit Settings, enter a",
"(default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client",
"will be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format",
"last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date",
"Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config =",
"Secret: \") print( \"3 - On the app page, click on Edit Settings,",
"last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date and time will be scrobbled.",
") print(\"2 - Input the following information (available on the app page):\") spotify_conf[\"client_id\"]",
"librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username:",
"\") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 - On the app page,",
"* 27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def",
"requested information to create the config file\\n\" ) spotify_conf = dict() print(\"-\" *",
"\"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks,",
"config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config file",
"passed\") print(\"Run the following command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1)",
"or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"]",
"\"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case of any error\", )",
"session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving",
"kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError",
"27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create an app on Spotify for",
"case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble",
"help=\"Show the complete help message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs:",
"{len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks = [] for track in spotify_tracks:",
"md5 from math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy",
"unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with",
"help message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" )",
"librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"]",
"= kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions and enter the requested",
"if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while tries: tries",
"enter the requested information to create the config file\\n\" ) spotify_conf = dict()",
"kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\",",
"while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except",
"\"Follow the instructions and enter the requested information to create the config file\\n\"",
"tracks: tries = 10 while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling",
"username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\"",
"to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file):",
"= ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try:",
"cursors[\"after\"] if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file =",
"\") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with",
"= recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"]",
"/ 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception",
") last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date",
"Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax)",
"API:\\n\") print( \"1 - Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" )",
"tracks.append(track_info) except Exception as err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled",
"help=\"Only tracks played after this date and time will be scrobbled. Must follow",
"value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] =",
"remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app:",
"= scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\")",
"= input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" * 27)",
"librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27)",
"print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]:",
"to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled",
"and save. (Note: the URI doesn't need to be accessible. By default we",
") last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date and time will be",
"datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get(",
"= input(\"Client Secret: \") print( \"3 - On the app page, click on",
"LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def",
"set on your Spotify Developer's page - doesn't need to be accessible (default:",
"dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved on tracks-file\", ) spotify_group",
"information to create the config file\\n\" ) spotify_conf = dict() print(\"-\" * 27)",
"format (in strftime syntax) for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\",",
"help=\"Config file to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\",",
"help=\"Datetime format (in strftime syntax) for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group(",
"\"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv)",
"auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"]",
"generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file)",
"Developer's page - doesn't need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your",
"= kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as",
"init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config file\" ) init_parser.add_argument(",
"ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"]",
") init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help message for all",
"tracks = [] for track in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"],",
"Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\"",
"} tracks.append(track_info) except Exception as err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving",
"tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError:",
"WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename",
"break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1)",
"the Redirect URIs field and save. (Note: the URI doesn't need to be",
"help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI",
"print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\")",
"= skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url)",
"on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret:",
"strftime syntax) for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related",
"the date and time you listened the last scrobbled Spotify track\", ) last_played.add_argument(",
"\"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser",
"spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks = [] for track",
"action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved on tracks-file\", ) spotify_group =",
"file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] =",
"{key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"]",
"* 27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create an app on Spotify",
"ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh",
"librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"]",
"page - doesn't need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify",
"\"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after (default: %(default)s)\", ) librefm_group",
"= input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] =",
"format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after (default:",
"as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks = []",
"(default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help message",
"save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete",
"file\\n\" ) spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1",
"), } tracks.append(track_info) except Exception as err: print(\"Error reading track metadata\") print(err) print(track)",
"recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] =",
"to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key, value in",
"be accessible. By default we use http://localhost)\" ) print(\"4 - Input the following",
"save non-scrobbled tracks in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\",",
"help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args = vars(args)",
"subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument(",
"scrobble!\") print(\"Organizing tracks...\") tracks = [] for track in spotify_tracks: try: track_info =",
"\"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date and time you listened the",
"\"--search-after\", help=\"Only tracks played after this date and time will be scrobbled. Must",
"remaining tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\"",
"sys from argparse import ArgumentParser from configparser import ConfigParser from datetime import datetime",
"[http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf",
"a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else:",
"instructions and enter the requested information to create the config file\\n\" ) spotify_conf",
"print(\"Saved config file! ;)\") if __name__ == \"__main__\": parser = ArgumentParser() subparsers =",
":(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file,",
"config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def",
"(available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client",
"config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks",
"except KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify",
"Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token before starting",
"config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL)",
") spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify",
"config file! ;)\") if __name__ == \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers()",
"skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"]",
"or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as",
"Input the following information (available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID:",
"track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int(",
"config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if",
"librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config file\"",
"for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information (available on the",
"session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break",
"import ConfigParser from datetime import datetime from getpass import getpass from hashlib import",
"print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() *",
"commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args()",
"print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower():",
"init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help message for all commands\",",
"default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser(",
"to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script",
"<= 2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and no",
"\"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token before starting the routine\", )",
"the URI doesn't need to be accessible. By default we use http://localhost)\" )",
"os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and no arguments passed\") print(\"Run the",
"doesn't need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\")",
"%(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm",
"\"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors",
"= librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as",
"hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow",
"all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args =",
"= dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \")",
"== \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble",
"last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp =",
"(default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your",
"import datetime from getpass import getpass from hashlib import md5 from math import",
"librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as config_file:",
"librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful",
"ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played",
"Spotify Client Token before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\",",
"save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"]",
"your Spotify Developer's page - doesn't need to be accessible (default: %(default)s)\", )",
"int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or",
"played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to",
"spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\",",
"kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not",
"from configparser import ConfigParser from datetime import datetime from getpass import getpass from",
"help=\"CLI wizard to generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config",
"config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify config/parameter",
"= dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create an",
"config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file):",
"{ \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000),",
"err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching",
"file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\",",
"ConfigParser from datetime import datetime from getpass import getpass from hashlib import md5",
"err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file,",
"parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI",
"as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <=",
"kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" )",
"done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"]",
"\"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__ == \"__main__\": parser",
"scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks to libre.fm\", )",
"Spotify API:\\n\") print( \"1 - Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\"",
"print(\"Configuring Spotify API:\\n\") print( \"1 - Create an app on Spotify for Developers",
"URI set on your Spotify Developer's page - doesn't need to be accessible",
"scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime",
"the following command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config =",
"non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key,",
"any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks",
"or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", )",
"os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth(",
"app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print(",
"config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"]",
"help_parser = subparsers.add_parser( \"help\", help=\"Show the complete help message for all commands\", add_help=False,",
"pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and",
"a URI on the Redirect URIs field and save. (Note: the URI doesn't",
"\"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as err:",
"WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm)",
"information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] =",
"except Exception as err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks",
"= spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date and time",
"message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) )",
"search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\",",
"related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\",",
"username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on",
"to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write",
"or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf =",
"= [] for track in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\":",
"and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and no arguments passed\")",
"date and time will be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\",",
"spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file))",
"when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] =",
"recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)}",
"\"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info)",
"Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the",
"subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\",",
"print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] =",
"to generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to",
"hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config",
"on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your",
"spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify Developer's page -",
"arguments passed\") print(\"Run the following command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\")",
"doesn't need to be accessible. By default we use http://localhost)\" ) print(\"4 -",
"input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\")",
"kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions and enter the requested information",
"tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error:",
"config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"],",
"and time you listened the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only",
"(default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the",
") ) args = parser.parse_args() dict_args = vars(args) if dict_args: args.func(**dict_args) else: parser.print_help()",
"spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 -",
"follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for",
"Client Token before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int,",
"track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp()",
"{url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling",
"datetime from getpass import getpass from hashlib import md5 from math import ceil",
"page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3",
"md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions",
"Edit Settings, enter a URI on the Redirect URIs field and save. (Note:",
"tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 )",
"spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your",
"action=\"store_true\", help=\"Force refresh your Spotify Client Token before starting the routine\", ) last_played",
"open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks",
"if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks",
"print( \"Follow the instructions and enter the requested information to create the config",
"config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if",
"- Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or",
"librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks)",
"SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\") session_key",
"from datetime import datetime from getpass import getpass from hashlib import md5 from",
"or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or",
") scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the end\", )",
"__name__ == \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\",",
"click on Edit Settings, enter a URI on the Redirect URIs field and",
"= last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with",
"field and save. (Note: the URI doesn't need to be accessible. By default",
"if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\") if",
"kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp",
"= recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found",
"print(\"Run the following command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config",
"if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else:",
"print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for",
"= {key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"]",
"spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date and time you",
"following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"]",
"last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date and time you listened",
"scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script parameters (default: %(default)s)\",",
"complete help message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\"",
"command to generate a config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if",
"\"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser =",
"print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks):",
"track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth",
"track in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"],",
"scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the end\", ) scrobble_parser.add_argument(",
"- On the app page, click on Edit Settings, enter a URI on",
"and enter the requested information to create the config file\\n\" ) spotify_conf =",
"print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \")",
"if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth =",
"search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after",
"file! ;)\") if __name__ == \"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser",
"URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] =",
"\"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify",
"dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or",
"- Input the following information (available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client",
"last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the date and",
"as err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\")",
"None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if",
"time you listened the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks",
"for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = (",
"ArgumentParser from configparser import ConfigParser from datetime import datetime from getpass import getpass",
"cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks",
"key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"])",
"[] for track in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"],",
") spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" )",
"app page, click on Edit Settings, enter a URI on the Redirect URIs",
"recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not",
"we use http://localhost)\" ) print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] = (",
"int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as err: print(\"Error",
"or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify",
"the following information (available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \")",
"= dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"]",
"{tries} tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize",
"= librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file,",
"the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case",
"kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file:",
"an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following",
") spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\")",
"be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your",
"def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default",
"else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"]",
"default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in strftime syntax) for search-after (default: %(default)s)\", ) librefm_group =",
"input(\"Client Secret: \") print( \"3 - On the app page, click on Edit",
"session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER",
"your Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\",",
"refresh your Spotify Client Token before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group()",
"\"help\", help=\"Show the complete help message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda",
"on the Redirect URIs field and save. (Note: the URI doesn't need to",
"recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file",
"ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except",
"default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify Developer's page - doesn't need",
"%(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\"",
"as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth)",
"with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__ ==",
"parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's",
"skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling",
"in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to",
"tracks to scrobble!\") print(\"Organizing tracks...\") tracks = [] for track in spotify_tracks: try:",
"\"3 - On the app page, click on Edit Settings, enter a URI",
"spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create",
"import ArgumentParser from configparser import ConfigParser from datetime import datetime from getpass import",
"math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify,",
"default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case of any error\", ) scrobble_parser.add_argument(",
"try to scrobble remaining tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\",",
"for track in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\":",
"= ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries = 10",
"URI on the Redirect URIs field and save. (Note: the URI doesn't need",
"Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after this date and time",
"script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config",
"1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp)",
"following information (available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"]",
"kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__",
"help=\"Spotify redirect URI set on your Spotify Developer's page - doesn't need to",
"- Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input",
"from math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import",
"subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks",
"this date and time will be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument(",
"import getpass from hashlib import md5 from math import ceil from pylast import",
"- doesn't need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client",
"= kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp",
"input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 - On the",
"ConfigParser() print( \"Follow the instructions and enter the requested information to create the",
"\"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime(",
"new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press",
"end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case of",
"spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file!",
"print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent",
"successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to",
"before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp",
"scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache",
"help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config file\" )",
"not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"]",
") config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\") with open(config_filename,",
"scrobble remaining tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related",
"config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if",
"on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information (available",
"error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved",
"{tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key, value in config[\"libre.fm\"].items()}",
"syntax) for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\"",
"return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the",
"description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser(",
"= spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not None",
"save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config",
"track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), }",
"\"1 - Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 -",
"= ConfigParser() print( \"Follow the instructions and enter the requested information to create",
"(https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information (available on the app page):\")",
"SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"],",
"scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]:",
"* 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks =",
"10 while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks)",
"tracks played after this date and time will be scrobbled. Must follow search-after-fmt",
"init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config)",
"**kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args = vars(args) if dict_args:",
"= kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file})",
"dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1 - Create an app",
"pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2",
") recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is",
"help=\"Don't try to scrobble remaining tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group(",
"password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving config to {config_filename}\")",
"tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" )",
"config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions and enter the",
"\"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict()",
"to scrobble remaining tracks saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify",
"for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" )",
") librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\")",
"default=\"config.ini\", help=\"Config file to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\",",
"Token before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX",
"routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing the",
"read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to",
"track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"],",
"the app: {url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key",
"SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs):",
"input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf",
"spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your",
"from hashlib import md5 from math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator,",
"= Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"]",
"(milliseconds) representing the date and time you listened the last scrobbled Spotify track\",",
"\"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script parameters (default: %(default)s)\", ) scrobble_parser.add_argument(",
"SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser()",
"import pickle import sys from argparse import ArgumentParser from configparser import ConfigParser from",
"* 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password(",
"of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining",
"Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \")",
"not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and no arguments passed\") print(\"Run",
"help=\"File to save non-scrobbled tracks in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\",",
"from getpass import getpass from hashlib import md5 from math import ceil from",
"config file:\") print(f\"\\t{sys.argv[0]} init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"]",
") init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\", )",
"sys.exit(1) librefm_auth = {key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] = kwargs[\"librefm_user\"]",
"print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks",
"help=\"UNIX timestamp (milliseconds) representing the date and time you listened the last scrobbled",
"http://localhost)\" ) print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI",
"last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"]",
"to create the config file\\n\" ) spotify_conf = dict() print(\"-\" * 27) print(\"Configuring",
"cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify Developer's",
"last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and",
"\") librefm_conf[\"password_hash\"] = hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" *",
"try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new session...\")",
"print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url",
") except KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"])",
"as config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__ == \"__main__\": parser =",
"Exception as err: print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to",
"\"__main__\": parser = ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your",
"listened the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after",
"= LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries",
"pickle import sys from argparse import ArgumentParser from configparser import ConfigParser from datetime",
"enter a URI on the Redirect URIs field and save. (Note: the URI",
"path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify Developer's page",
"len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found and",
"in spotify_tracks: try: track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\":",
"need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\", help=\"Your Spotify Client ID\") spotify_group.add_argument(",
"= dict() config[\"libre.fm\"] = dict() try: auth = SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"]",
"print(f\"Default config file ({config_file}) not found and no arguments passed\") print(\"Run the following",
"else librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while tries: tries -= 1",
"print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting",
"the requested information to create the config file\\n\" ) spotify_conf = dict() print(\"-\"",
"tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read",
"%(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the end\",",
"print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"] =",
"or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify config/parameter {err}\") sys.exit(1)",
"= parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks to",
"information (available on the app page):\") spotify_conf[\"client_id\"] = input(\"Client ID: \") spotify_conf[\"client_secret\"] =",
"hashlib import md5 from math import ceil from pylast import LibreFMNetwork, SessionKeyGenerator, WSError",
"= subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main)",
"librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm related parameters\" ) librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\",",
"if len(sys.argv) <= 2 and not os.path.isfile(config_file): print(f\"Default config file ({config_file}) not found",
"= session_key else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\")",
"last_timestamp = cursors[\"after\"] if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp",
"(in strftime syntax) for search-after (default: %(default)s)\", ) librefm_group = scrobble_parser.add_argument_group( \"Libre.fm\", description=\"Libre.fm",
"your Spotify Client Token before starting the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument(",
"= hash_librefm_password( getpass(\"Libre.fm password: \") ) config[\"libre.fm\"] = librefm_conf print(\"-\" * 27) print(f\"Saving",
"Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2 - Input the following information (available on",
"as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file,",
"spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify",
"cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing Spotify config/parameter {err}\")",
"\"scrobble\", help=\"Scrobble your Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\",",
"= { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] /",
"print(\"Organizing tracks...\") tracks = [] for track in spotify_tracks: try: track_info = {",
"Settings, enter a URI on the Redirect URIs field and save. (Note: the",
"init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print( \"Follow the instructions and enter",
"\") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\")",
"description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument(",
") spotify_conf = dict() print(\"-\" * 27) print(\"Configuring Spotify API:\\n\") print( \"1 -",
"nargs=\"?\", default=\"config.ini\", help=\"Config file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser =",
"datetime import datetime from getpass import getpass from hashlib import md5 from math",
"cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not None else last_timestamp",
"\"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks =",
"app: {url}\") input(\"Press ENTER when done\") session_key = skg.get_web_auth_session_key(url) librefm_auth[\"session_key\"] = session_key else:",
"Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token",
"{err}\") sys.exit(1) if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]:",
") print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]:",
"os import pickle import sys from argparse import ArgumentParser from configparser import ConfigParser",
"to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename,",
") scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script parameters (default:",
"help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client",
"{tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved",
").timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks",
"librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while tries: tries -= 1 librefm",
") scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved on",
"sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\")",
"related parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\",",
"else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if",
"save_tracks(filename, tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file",
"Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp()",
"import sys from argparse import ArgumentParser from configparser import ConfigParser from datetime import",
"tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the",
"config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled tracks to {tracks_file}\")",
"= SessionKeyGenerator(librefm) url = skg.get_web_auth_url() print(f\"Authorize the app: {url}\") input(\"Press ENTER when done\")",
"file ({config_file}) not found and no arguments passed\") print(\"Run the following command to",
"librefm_group.add_argument(\"--librefm-user\", help=\"Your Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to",
"( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username: \")",
"help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify",
"Libre.fm username\") librefm_group.add_argument(\"--librefm-password\", help=\"<PASSWORD>\") init_parser = subparsers.add_parser( \"init\", help=\"CLI wizard to generate a",
"spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm",
"= cursors[\"after\"] if cursors is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file",
"= subparsers.add_parser( \"help\", help=\"Show the complete help message for all commands\", add_help=False, )",
"import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest()",
"or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks:",
"\"init\", help=\"CLI wizard to generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\",",
"print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value",
"on Edit Settings, enter a URI on the Redirect URIs field and save.",
"Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token before",
"kwargs[\"librefm_user\"] or librefm_auth[\"username\"] librefm_auth[\"password_hash\"] = ( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if",
"last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks = recent_tracks[\"items\"] if kwargs[\"scrobble_remaining\"] and os.path.isfile(tracks_file): with open(tracks_file,",
"Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set",
"input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring",
"init\") sys.exit(1) config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"]",
"the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" )",
"-= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\") try: librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid",
"= SpotifyOAuth( kwargs[\"spotify_client_id\"] or config[\"spotify\"][\"CLIENT_ID\"], kwargs[\"spotify_client_secret\"] or config[\"spotify\"][\"CLIENT_SECRET\"], kwargs[\"spotify_redirect_uri\"] or config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or",
"metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) librefm_auth =",
"the app page, click on Edit Settings, enter a URI on the Redirect",
"print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args = vars(args) if dict_args: args.func(**dict_args)",
"username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err: print(f\"Missing",
"= subparsers.add_parser( \"init\", help=\"CLI wizard to generate a config file\" ) init_parser.add_argument( \"config_file\",",
"non-scrobbled tracks in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't",
"= ArgumentParser() subparsers = parser.add_subparsers() scrobble_parser = subparsers.add_parser( \"scrobble\", help=\"Scrobble your Spotify's recently",
"after this date and time will be scrobbled. Must follow search-after-fmt format\", )",
") else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors",
"parameters (default: %(default)s)\", ) scrobble_parser.add_argument( \"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at",
"action=\"store_false\", help=\"Don't write to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File",
"is not None else last_timestamp config[\"spotify\"][\"LAST_TIMESTAMP\"] = last_timestamp tracks_file = kwargs[\"tracks_file\"] spotify_tracks =",
"session! {tries} tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url = skg.get_web_auth_url()",
"config = ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict()",
"else: print(\"Scrobbling successful!\") config[\"libre.fm\"][\"SESSION_KEY\"] = librefm_auth[\"session_key\"] break else: print(\"Scrobbling unsuccessful :(\") print(f\"Saving non-scrobbled",
"with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\")",
"\"--no-write-config\", dest=\"write_config\", action=\"store_false\", help=\"Don't write to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\",",
"27) print(f\"Saving config to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename,",
"on your Spotify Developer's page - doesn't need to be accessible (default: %(default)s)\",",
"func=lambda **kwargs: print( f\"{scrobble_parser.format_help()}\\n{'-'*27}\\n{init_parser.format_help()}\" ) ) args = parser.parse_args() dict_args = vars(args) if",
"config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__ == \"__main__\": parser = ArgumentParser()",
"\"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved on tracks-file\", )",
"Spotify Developer's page - doesn't need to be accessible (default: %(default)s)\", ) spotify_group.add_argument(\"--spotify-client-id\",",
"help=\"Config file to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\",",
"kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\"",
"open(config_file, \"w\") as config_file: config.write(config_file) print(\"Saved config file! ;)\") if __name__ == \"__main__\":",
"to save settings (default: %(default)s)\", ) init_parser.set_defaults(func=init_config) help_parser = subparsers.add_parser( \"help\", help=\"Show the",
"= input(\"Client ID: \") spotify_conf[\"client_secret\"] = input(\"Client Secret: \") print( \"3 - On",
"\"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"] / 1000), \"timestamp\": int( datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ),",
"dict() print(\"-\" * 27) print(\"Configuring Libre.fm API:\\n\") librefm_conf[\"username\"] = input(\"Libre.fm username: \") librefm_conf[\"password_hash\"]",
").timestamp() ), } tracks.append(track_info) except Exception as err: print(\"Error reading track metadata\") print(err)",
"from pylast import LibreFMNetwork, SessionKeyGenerator, WSError from spotipy import Spotify, SpotifyOAuth def hash_librefm_password(password):",
"scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try to scrobble remaining tracks saved on tracks-file\",",
"Spotify Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\",",
"Invalid session! {tries} tries remaining\") print(\"Getting new session...\") skg = SessionKeyGenerator(librefm) url =",
"kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp =",
"track_info = { \"artist\": track[\"track\"][\"artists\"][0][\"name\"], \"title\": track[\"track\"][\"name\"], \"album\": track[\"track\"][\"album\"][\"name\"], \"track_number\": track[\"track\"].get(\"track_number\"), \"duration\": ceil(track[\"track\"][\"duration_ms\"]",
"datetime.strptime( track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as err: print(\"Error reading",
"By default we use http://localhost)\" ) print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"]",
"{config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\")",
"librefm.scrobble_many(tracks) except WSError: print(f\"Error: Invalid session! {tries} tries remaining\") print(\"Getting new session...\") skg",
"getpass from hashlib import md5 from math import ceil from pylast import LibreFMNetwork,",
"print(\"2 - Input the following information (available on the app page):\") spotify_conf[\"client_id\"] =",
"saved on tracks-file\", ) spotify_group = scrobble_parser.add_argument_group( \"Spotify\", description=\"Spotify related parameters\" ) spotify_group.add_argument(\"--spotify-user\",",
"ConfigParser() if os.path.isfile(config_file): config.read(config_file) else: config[\"spotify\"] = dict() config[\"libre.fm\"] = dict() try: auth",
"print(\"Error reading track metadata\") print(err) print(track) print(f\"Saving non-scrobbled tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks)",
"be scrobbled. Must follow search-after-fmt format\", ) spotify_group.add_argument( \"--search-after-fmt\", default=\"%Y-%m-%dT%H:%M:%S.%f%z\", help=\"Datetime format (in",
"config file ({config_file}) not found and no arguments passed\") print(\"Run the following command",
"print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing tracks...\") tracks = [] for track in",
"help=\"Don't write to config at the end\", ) scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to",
"parameters\" ) spotify_group.add_argument(\"--spotify-user\", help=\"Your Spotify username\") spotify_group.add_argument(\"--cache-path\", help=\"Spotify's cache path\") spotify_group.add_argument( \"--spotify-redirect-uri\", default=\"http://localhost\",",
"redirect URI set on your Spotify Developer's page - doesn't need to be",
"tracks): with open(filename, \"wb\") as pickle_file: pickle.dump(tracks, pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file =",
"config to {config_filename}\") with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with",
"= ( input(\"Redirect URI [http://localhost]: \") or \"http://localhost\" ) spotify_conf[\"username\"] = input(\"Spotify username:",
"accessible. By default we use http://localhost)\" ) print(\"4 - Input the following information:\")",
"def hash_librefm_password(password): return md5(password.encode(\"utf8\")).hexdigest() def init_config(**kwargs): config_filename = kwargs[\"config_file\"] config = ConfigParser() print(",
"username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\" * 27) print(\"Configuring Libre.fm",
"( hash_librefm_password(kwargs[\"librefm_password\"]) if kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while",
"else: last_timestamp = kwargs[\"last_timestamp\"] or config[\"spotify\"].get( \"LAST_TIMESTAMP\" ) recent_tracks = spotify.current_user_recently_played(after=last_timestamp) cursors =",
"spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force refresh your Spotify Client Token before starting the routine\",",
"representing the date and time you listened the last scrobbled Spotify track\", )",
"os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\") print(\"Organizing",
"Spotify's recently played tracks to libre.fm\", ) scrobble_parser.set_defaults(func=main) scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config",
"pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and not os.path.isfile(config_file):",
"print( \"1 - Create an app on Spotify for Developers (https://developer.spotify.com/dashboard/applications)\" ) print(\"2",
"and os.path.isfile(tracks_file): with open(tracks_file, \"rb\") as pickle_file: spotify_tracks.extend(pickle.load(pickle_file)) print(f\"Found {len(spotify_tracks)} tracks to scrobble!\")",
"\"--spotify-redirect-uri\", default=\"http://localhost\", help=\"Spotify redirect URI set on your Spotify Developer's page - doesn't",
"scrobble_parser.add_argument( \"--tracks-file\", default=\".tracks.pickle\", help=\"File to save non-scrobbled tracks in case of any error\",",
"= int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000 ) else: last_timestamp = kwargs[\"last_timestamp\"]",
"generate a config file\" ) init_parser.add_argument( \"config_file\", nargs=\"?\", default=\"config.ini\", help=\"Config file to save",
"config[\"spotify\"][\"REDIRECT_URI\"], username=kwargs[\"spotify_user\"] or config[\"spotify\"][\"USERNAME\"], cache_path=kwargs[\"cache_path\"] or config[\"spotify\"][\"CACHE_PATH\"], scope=\"user-read-recently-played\", ) except KeyError as err:",
"the routine\", ) last_played = spotify_group.add_mutually_exclusive_group() last_played.add_argument( \"--last-timestamp\", type=int, help=\"UNIX timestamp (milliseconds) representing",
"subparsers.add_parser( \"help\", help=\"Show the complete help message for all commands\", add_help=False, ) help_parser.set_defaults(",
"pickle_file, pickle.HIGHEST_PROTOCOL) def main(**kwargs): config_file = kwargs[\"config\"] if len(sys.argv) <= 2 and not",
"with open(config_filename, \"w\") as config_file: config.write(config_file) def save_tracks(filename, tracks): with open(filename, \"wb\") as",
"URIs field and save. (Note: the URI doesn't need to be accessible. By",
"({config_file}) not found and no arguments passed\") print(\"Run the following command to generate",
"scrobble_parser.add_argument( \"-c\", \"--config\", default=\"config.ini\", help=\"Config file to read script parameters (default: %(default)s)\", )",
"spotify_tracks) sys.exit(1) librefm_auth = {key.lower(): value for key, value in config[\"libre.fm\"].items()} librefm_auth[\"username\"] =",
"track[\"played_at\"], \"%Y-%m-%dT%H:%M:%S.%f%z\" ).timestamp() ), } tracks.append(track_info) except Exception as err: print(\"Error reading track",
"argparse import ArgumentParser from configparser import ConfigParser from datetime import datetime from getpass",
"tries = 10 while tries: tries -= 1 librefm = LibreFMNetwork(**librefm_auth) print(\"Scrobbling tracks...\")",
"kwargs[\"librefm_password\"] else librefm_auth[\"password_hash\"] ) if tracks: tries = 10 while tries: tries -=",
"recent tracks\") if kwargs[\"search_after\"]: last_timestamp = int( datetime.strptime( kwargs[\"search_after\"], kwargs[\"search_after_fmt\"] ).timestamp() * 1000",
"use http://localhost)\" ) print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] = ( input(\"Redirect",
") spotify_conf[\"username\"] = input(\"Spotify username: \") config[\"spotify\"] = spotify_conf librefm_conf = dict() print(\"-\"",
"Client ID\") spotify_group.add_argument( \"--spotify-client-secret\", help=\"Your Spotify Client Secret\" ) spotify_group.add_argument( \"--force-refresh-token\", action=\"store_true\", help=\"Force",
"you listened the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played",
"the complete help message for all commands\", add_help=False, ) help_parser.set_defaults( func=lambda **kwargs: print(",
"timestamp (milliseconds) representing the date and time you listened the last scrobbled Spotify",
"default we use http://localhost)\" ) print(\"4 - Input the following information:\") spotify_conf[\"redirect_uri\"] =",
"if kwargs[\"force_refresh_token\"]: auth.refresh_access_token(auth.get_cached_token()[\"refresh_token\"]) spotify = Spotify(auth_manager=auth) print(\"Searching recent tracks\") if kwargs[\"search_after\"]: last_timestamp =",
"tracks...\") tracks = [] for track in spotify_tracks: try: track_info = { \"artist\":",
"the last scrobbled Spotify track\", ) last_played.add_argument( \"--search-after\", help=\"Only tracks played after this",
"getpass import getpass from hashlib import md5 from math import ceil from pylast",
") if tracks: tries = 10 while tries: tries -= 1 librefm =",
"tracks to {tracks_file}\") save_tracks(tracks_file, spotify_tracks) sys.exit(1) if kwargs[\"write_config\"]: with open(config_file, \"w\") as config_file:",
"spotify.current_user_recently_played(after=last_timestamp) cursors = recent_tracks[\"cursors\"] last_timestamp = cursors[\"after\"] if cursors is not None else",
"tracks in case of any error\", ) scrobble_parser.add_argument( \"--ignore-tracks-file\", dest=\"scrobble_remaining\", action=\"store_false\", help=\"Don't try"
] |
[
"under the License. from __future__ import absolute_import from elasticsearch import Elasticsearch from flask",
"cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component): DFG_db =",
"Unless required by applicable law or agreed to in writing, software # distributed",
"Apache License, Version 2.0 (the \"License\"); you may # not use this file",
"the License. You may obtain # a copy of the License at #",
"may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"return components @classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for",
"import re import yaml from rhoci.database import Database class DFG(object): def __init__(self, name,",
"@classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based on job model",
"components: return squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components",
"with the License. You may obtain # a copy of the License at",
"get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items():",
"squads self.components = components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to the",
"squad, components in DFG_db['squad_to_components'].items(): for comp in components: if comp == component: return",
"from rhoci.database import Database class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name",
"return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query = {}",
"@classmethod def get_all_components(cls): components = [] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components'])",
"= cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query = {}",
"DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count",
"result.\"\"\" query = {} if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query)",
"documents.\"\"\" query = {} if squads: return len(cls.get_all_squads()) else: DFGs = Database.find(collection='DFGs', query=query)",
"in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components = []",
"rhoci.database import Database class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name =",
"squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}):",
"use this file except in compliance with the License. You may obtain #",
"DFGs documents.\"\"\" query = {} if squads: return len(cls.get_all_squads()) else: DFGs = Database.find(collection='DFGs',",
"given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\"",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"\"\"Returns one query result.\"\"\" query = {} if name: query['name'] = name DFGs",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"implied. See the # License for the specific language governing permissions and limitations",
"of all DFGs based on job model where it cuts the DFG name",
"current_app as app import re import yaml from rhoci.database import Database class DFG(object):",
"# Copyright 2019 <NAME> # # Licensed under the Apache License, Version 2.0",
"unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0,",
"if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def",
"count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query = {} if squads:",
"self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs",
"DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\",",
"4000 } } } } result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']:",
"it cuts the DFG name from the job name and makes sure the",
"you may # not use this file except in compliance with the License.",
"DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name self.squads = squads",
"for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name,",
"all the components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod",
"limitations # under the License. from __future__ import absolute_import from elasticsearch import Elasticsearch",
"} } } } result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key'])",
"[] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls,",
"@classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of a given squad.\"\"\"",
"DFG name from the job name and makes sure the set is unique.",
"KIND, either express or implied. See the # License for the specific language",
"import current_app as app import re import yaml from rhoci.database import Database class",
"if component == components: return squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns",
"find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def",
"components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls):",
"= name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns",
"file except in compliance with the License. You may obtain # a copy",
"based on job model where it cuts the DFG name from the job",
"[] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls):",
"= Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" : { \"jobs\" : {",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"== component: return squad if component == components: return squad return @classmethod def",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"job model where it cuts the DFG name from the job name and",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"squads = [] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod",
"the set is unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body =",
"squad if component == components: return squad return @classmethod def get_squad_components(cls, DFG_name, squad):",
"bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads = [] for",
"return { 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def",
"def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in",
"permissions and limitations # under the License. from __future__ import absolute_import from elasticsearch",
"the # License for the specific language governing permissions and limitations # under",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"governing permissions and limitations # under the License. from __future__ import absolute_import from",
"and makes sure the set is unique. \"\"\" DFGs = [] es =",
"set is unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = {",
"DFGs based on job model where it cuts the DFG name from the",
"You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name,",
"from __future__ import absolute_import from elasticsearch import Elasticsearch from flask import current_app as",
"components=[], squad_to_components={}): self.name = name self.squads = squads self.components = components self.squad_to_components =",
"required by applicable law or agreed to in writing, software # distributed under",
"applicable law or agreed to in writing, software # distributed under the License",
"in compliance with the License. You may obtain # a copy of the",
"def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query = {} if name: query['name']",
"or agreed to in writing, software # distributed under the License is distributed",
"from the job name and makes sure the set is unique. \"\"\" DFGs",
"Elasticsearch from flask import current_app as app import re import yaml from rhoci.database",
"result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def",
"License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"\"jobs\" : { \"terms\" : { \"field\" : \"DFG.keyword\", \"size\" : 4000 }",
"def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name self.squads = squads self.components",
"component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp",
"0, \"aggs\" : { \"jobs\" : { \"terms\" : { \"field\" : \"DFG.keyword\",",
"re import yaml from rhoci.database import Database class DFG(object): def __init__(self, name, squads=[],",
"query = {} if squads: return len(cls.get_all_squads()) else: DFGs = Database.find(collection='DFGs', query=query) return",
"\"\"\"Returns find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod",
"@classmethod def find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query)",
"= cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp in components:",
"= Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\"",
"DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp in",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"as app import re import yaml from rhoci.database import Database class DFG(object): def",
"def insert(self): \"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs',",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may # not",
"for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components",
"Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" : { \"jobs\" : { \"terms\"",
"} result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod",
"for squad, components in DFG_db['squad_to_components'].items(): for comp in components: if comp == component:",
"query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls,",
"2.0 (the \"License\"); you may # not use this file except in compliance",
"components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\" if not",
"language governing permissions and limitations # under the License. from __future__ import absolute_import",
"# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"model where it cuts the DFG name from the job name and makes",
"name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls,",
"License, Version 2.0 (the \"License\"); you may # not use this file except",
"find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs",
"Copyright 2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the",
"where it cuts the DFG name from the job name and makes sure",
"DFGs @classmethod def get_all_squads(cls): squads = [] for DFG_db in cls.find(): if DFG_db['squads']:",
"import Database class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name",
"= [] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def",
"if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components = [] for DFG_db",
"DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components = [] for DFG_db in",
"DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp in components: if comp ==",
"agreed to in writing, software # distributed under the License is distributed on",
"squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of a",
"__init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name self.squads = squads self.components =",
"{ \"field\" : \"DFG.keyword\", \"size\" : 4000 } } } } result =",
"list of all DFGs based on job model where it cuts the DFG",
"components: if comp == component: return squad if component == components: return squad",
"class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name self.squads =",
"# Unless required by applicable law or agreed to in writing, software #",
"from flask import current_app as app import re import yaml from rhoci.database import",
"by applicable law or agreed to in writing, software # distributed under the",
"get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based on job model where it",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\"",
"def count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query = {} if",
"== components: return squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the",
"query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name):",
"get_all_squads(cls): squads = [] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads",
"{} if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod",
"components @classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad,",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"name from the job name and makes sure the set is unique. \"\"\"",
"squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query",
"result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads = [] for DFG_db in",
"except in compliance with the License. You may obtain # a copy of",
"DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query",
"= Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count of",
"'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list",
"insert(self): \"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json())",
"to in writing, software # distributed under the License is distributed on an",
"all DFGs based on job model where it cuts the DFG name from",
"from elasticsearch import Elasticsearch from flask import current_app as app import re import",
"for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads = []",
"name self.squads = squads self.components = components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts",
"in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads = [] for DFG_db",
"flask import current_app as app import re import yaml from rhoci.database import Database",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"= {} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns",
"# not use this file except in compliance with the License. You may",
"self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name, 'squads': self.squads, 'components': self.components,",
"# License for the specific language governing permissions and limitations # under the",
"def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of a given squad.\"\"\" DFG_db",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components = [] for",
"\"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\"",
"Version 2.0 (the \"License\"); you may # not use this file except in",
"app import re import yaml from rhoci.database import Database class DFG(object): def __init__(self,",
"squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components = [] for DFG_db in cls.find():",
"cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs",
"{\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name, 'squads': self.squads, 'components':",
"self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\",",
"find_one(cls, name): \"\"\"Returns one query result.\"\"\" query = {} if name: query['name'] =",
"\"License\"); you may # not use this file except in compliance with the",
"name and makes sure the set is unique. \"\"\" DFGs = [] es",
"{ 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls):",
"the Apache License, Version 2.0 (the \"License\"); you may # not use this",
"components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']:",
"name): \"\"\"Returns one query result.\"\"\" query = {} if name: query['name'] = name",
"__future__ import absolute_import from elasticsearch import Elasticsearch from flask import current_app as app",
"in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component): DFG_db",
"of DFGs documents.\"\"\" query = {} if squads: return len(cls.get_all_squads()) else: DFGs =",
"if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name)",
"Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components':",
"not use this file except in compliance with the License. You may obtain",
"\"\"\"Returns a list of all DFGs based on job model where it cuts",
"is unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\":",
"data=self.json()) def json(self): return { 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components,",
"# under the License. from __future__ import absolute_import from elasticsearch import Elasticsearch from",
"'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns",
"2019 <NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp in components: if comp",
"License for the specific language governing permissions and limitations # under the License.",
"get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of a given squad.\"\"\" DFG_db =",
"Database class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}): self.name = name self.squads",
"elasticsearch import Elasticsearch from flask import current_app as app import re import yaml",
"= name self.squads = squads self.components = components self.squad_to_components = squad_to_components def insert(self):",
"components in DFG_db['squad_to_components'].items(): for comp in components: if comp == component: return squad",
"\"DFG.keyword\", \"size\" : 4000 } } } } result = es.search(index=\"logstash\", body=body) for",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #",
"= squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\":",
"to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return",
"comp in components: if comp == component: return squad if component == components:",
"squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query = {} if squads: return",
"OF ANY KIND, either express or implied. See the # License for the",
"squads=[], components=[], squad_to_components={}): self.name = name self.squads = squads self.components = components self.squad_to_components",
"absolute_import from elasticsearch import Elasticsearch from flask import current_app as app import re",
": { \"jobs\" : { \"terms\" : { \"field\" : \"DFG.keyword\", \"size\" :",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"def get_all_components(cls): components = [] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return",
"DFG_db['squad_to_components'].items(): for comp in components: if comp == component: return squad if component",
"object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self):",
"\"\"\"Inserts object to the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def",
"DFG_name, squad): \"\"\"Returns all the components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name)",
"return squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of",
"for comp in components: if comp == component: return squad if component ==",
"DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query = {} if",
"self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of",
"in components: if comp == component: return squad if component == components: return",
"(the \"License\"); you may # not use this file except in compliance with",
"Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query",
"\"aggs\" : { \"jobs\" : { \"terms\" : { \"field\" : \"DFG.keyword\", \"size\"",
"# # Unless required by applicable law or agreed to in writing, software",
"{} DFGs = Database.find(collection=\"DFGs\", query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one",
"Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count of DFGs",
"@classmethod def count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query = {}",
"return squads @classmethod def get_all_components(cls): components = [] for DFG_db in cls.find(): if",
"database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name':",
"body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads =",
"= { \"size\": 0, \"aggs\" : { \"jobs\" : { \"terms\" : {",
"one query result.\"\"\" query = {} if name: query['name'] = name DFGs =",
"License. You may obtain # a copy of the License at # #",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"} @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based on job",
"@classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query = {} if name:",
": \"DFG.keyword\", \"size\" : 4000 } } } } result = es.search(index=\"logstash\", body=body)",
"DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for",
"import Elasticsearch from flask import current_app as app import re import yaml from",
"components = [] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod",
"ANY KIND, either express or implied. See the # License for the specific",
"import yaml from rhoci.database import Database class DFG(object): def __init__(self, name, squads=[], components=[],",
"return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all the components of a given",
"\"field\" : \"DFG.keyword\", \"size\" : 4000 } } } } result = es.search(index=\"logstash\",",
"'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based",
": { \"field\" : \"DFG.keyword\", \"size\" : 4000 } } } } result",
"yaml from rhoci.database import Database class DFG(object): def __init__(self, name, squads=[], components=[], squad_to_components={}):",
"\"size\": 0, \"aggs\" : { \"jobs\" : { \"terms\" : { \"field\" :",
": { \"terms\" : { \"field\" : \"DFG.keyword\", \"size\" : 4000 } }",
"squad): \"\"\"Returns all the components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return",
"'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all",
"comp == component: return squad if component == components: return squad return @classmethod",
"= [] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def",
"def find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs = Database.find(collection=\"DFGs\", query=query) return",
"body = { \"size\": 0, \"aggs\" : { \"jobs\" : { \"terms\" :",
"return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query = {} DFGs =",
"License. from __future__ import absolute_import from elasticsearch import Elasticsearch from flask import current_app",
"count of DFGs documents.\"\"\" query = {} if squads: return len(cls.get_all_squads()) else: DFGs",
"under the Apache License, Version 2.0 (the \"License\"); you may # not use",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"the DFG name from the job name and makes sure the set is",
"in DFG_db['squad_to_components'].items(): for comp in components: if comp == component: return squad if",
": 4000 } } } } result = es.search(index=\"logstash\", body=body) for bucket in",
"self.squads = squads self.components = components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object",
"specific language governing permissions and limitations # under the License. from __future__ import",
"} } result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs",
"return DFGs @classmethod def get_all_squads(cls): squads = [] for DFG_db in cls.find(): if",
"See the # License for the specific language governing permissions and limitations #",
"query = {} if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return",
"sure the set is unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body",
"law or agreed to in writing, software # distributed under the License is",
"{ \"terms\" : { \"field\" : \"DFG.keyword\", \"size\" : 4000 } } }",
"express or implied. See the # License for the specific language governing permissions",
"on job model where it cuts the DFG name from the job name",
"{ \"jobs\" : { \"terms\" : { \"field\" : \"DFG.keyword\", \"size\" : 4000",
"DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"CONDITIONS OF ANY KIND, either express or implied. See the # License for",
"if comp == component: return squad if component == components: return squad return",
"the job name and makes sure the set is unique. \"\"\" DFGs =",
"component == components: return squad return @classmethod def get_squad_components(cls, DFG_name, squad): \"\"\"Returns all",
"\"terms\" : { \"field\" : \"DFG.keyword\", \"size\" : 4000 } } } }",
"} } } result = es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"makes sure the set is unique. \"\"\" DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url'])",
"es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads",
"and limitations # under the License. from __future__ import absolute_import from elasticsearch import",
"self.name = name self.squads = squads self.components = components self.squad_to_components = squad_to_components def",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"a list of all DFGs based on job model where it cuts the",
"the count of DFGs documents.\"\"\" query = {} if squads: return len(cls.get_all_squads()) else:",
"compliance with the License. You may obtain # a copy of the License",
"def json(self): return { 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, }",
"DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return squads @classmethod def get_all_components(cls): components =",
"Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name, 'squads': self.squads,",
"DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find query.\"\"\" query =",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\" if",
"self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False):",
"name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the",
"{ \"size\": 0, \"aggs\" : { \"jobs\" : { \"terms\" : { \"field\"",
"DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components @classmethod def get_squad(cls, DFG_name, component):",
"import absolute_import from elasticsearch import Elasticsearch from flask import current_app as app import",
"get_all_components(cls): components = [] for DFG_db in cls.find(): if DFG_db['components']: components.extend(DFG_db['components']) return components",
"\"size\" : 4000 } } } } result = es.search(index=\"logstash\", body=body) for bucket",
"\"\"\"Returns all the components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad]",
"= {} if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\", query=query) return DFGs",
"the components of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def",
"DFGs = [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" :",
"@classmethod def get_squad(cls, DFG_name, component): DFG_db = cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components",
"may # not use this file except in compliance with the License. You",
"job name and makes sure the set is unique. \"\"\" DFGs = []",
"squad_to_components={}): self.name = name self.squads = squads self.components = components self.squad_to_components = squad_to_components",
"either express or implied. See the # License for the specific language governing",
"es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" : { \"jobs\" :",
"component: return squad if component == components: return squad return @classmethod def get_squad_components(cls,",
"this file except in compliance with the License. You may obtain # a",
"squads @classmethod def get_all_components(cls): components = [] for DFG_db in cls.find(): if DFG_db['components']:",
"DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query =",
"query=query) return DFGs @classmethod def find_one(cls, name): \"\"\"Returns one query result.\"\"\" query =",
"or implied. See the # License for the specific language governing permissions and",
"a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns find",
"the specific language governing permissions and limitations # under the License. from __future__",
"= {} if squads: return len(cls.get_all_squads()) else: DFGs = Database.find(collection='DFGs', query=query) return DFGs.count()",
"cls.find_one(name=DFG_name) if DFG_db['squad_to_components']: for squad, components in DFG_db['squad_to_components'].items(): for comp in components: if",
"of a given squad.\"\"\" DFG_db = cls.find_one(name=DFG_name) return DFG_db['squad_to_components'][squad] @classmethod def find(cls): \"\"\"Returns",
"= [] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" : {",
"\"\"\"Returns the count of DFGs documents.\"\"\" query = {} if squads: return len(cls.get_all_squads())",
"for the specific language governing permissions and limitations # under the License. from",
"return DFGs @classmethod def count(cls, squads=False): \"\"\"Returns the count of DFGs documents.\"\"\" query",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"self.squad_to_components, } @classmethod def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based on",
"return squad if component == components: return squad return @classmethod def get_squad_components(cls, DFG_name,",
"@classmethod def get_all_squads(cls): squads = [] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads'])",
"def get_all_DFGs_based_on_jobs(cls): \"\"\"Returns a list of all DFGs based on job model where",
"= es.search(index=\"logstash\", body=body) for bucket in result[\"aggregations\"]['jobs']['buckets']: DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls):",
"self.components = components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to the database.\"\"\"",
"json(self): return { 'name': self.name, 'squads': self.squads, 'components': self.components, 'squad_to_components': self.squad_to_components, } @classmethod",
"the database.\"\"\" if not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return {",
"OR CONDITIONS OF ANY KIND, either express or implied. See the # License",
"not Database.find_one(\"DFGs\", {\"name\": self.name}): Database.insert(collection='DFGs', data=self.json()) def json(self): return { 'name': self.name, 'squads':",
"obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may #",
"name, squads=[], components=[], squad_to_components={}): self.name = name self.squads = squads self.components = components",
"<NAME> # # Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"[] es = Elasticsearch(app.config['custom']['elk']['es']['url']) body = { \"size\": 0, \"aggs\" : { \"jobs\"",
"def get_all_squads(cls): squads = [] for DFG_db in cls.find(): if DFG_db['squads']: squads.extend(DFG_db['squads']) return",
"= squads self.components = components self.squad_to_components = squad_to_components def insert(self): \"\"\"Inserts object to",
"DFGs.append(bucket['key']) return DFGs @classmethod def get_all_squads(cls): squads = [] for DFG_db in cls.find():",
"query result.\"\"\" query = {} if name: query['name'] = name DFGs = Database.find_one(collection=\"DFGs\",",
"the License. from __future__ import absolute_import from elasticsearch import Elasticsearch from flask import",
"cuts the DFG name from the job name and makes sure the set"
] |
[
"== '__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state =",
"print(str(iter) + '/' + str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts,",
"1.1*n - 1, 0, K) vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100)",
"up: if state[idx] != n - 1: state[idx] = state[idx] + 1 else:",
"'#477890' line_color = '#990D35' text_color = '#153243' if __name__ == '__main__': K =",
"1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) +",
"dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K) + r', '",
"as np import matplotlib.pyplot as plt from random import randint import sys plt.style.use('ja')",
"1, 0.9*K, r'$K = {} \\,$'.format(K) + r', ' + '$n = {}",
"sys plt.style.use('ja') def update_configuration(state, n): K = len(state) - 1 idx = randint(0,",
"- 1 else: state[idx] = n - 1 return state bar_color = '#477890'",
"<filename>GifGen/complexity.py<gh_stars>0 ''' Idea based on Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's",
"bool(randint(0, 1)) if up: if state[idx] != n - 1: state[idx] = state[idx]",
"K = len(state) - 1 idx = randint(0, K) up = bool(randint(0, 1))",
"= randint(0, K) up = bool(randint(0, 1)) if up: if state[idx] != n",
"numpy as np import matplotlib.pyplot as plt from random import randint import sys",
"- 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter)",
"plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state = update_configuration(state, n) iter +=",
"int(sys.argv[3]) state = np.zeros(K) + randint(0, n - 1) iter = 0 plt.ion()",
"It then randomly updates the configuration to illustrate the long term behaviour. '''",
"len(state) - 1 idx = randint(0, K) up = bool(randint(0, 1)) if up:",
"+ 1 else: state[idx] = 0 else: if state[idx] != 0: state[idx] =",
"- 1 return state bar_color = '#477890' line_color = '#990D35' text_color = '#153243'",
"randint(0, K) up = bool(randint(0, 1)) if up: if state[idx] != n -",
"0 else: if state[idx] != 0: state[idx] = state[idx] - 1 else: state[idx]",
"to illustrate the long term behaviour. ''' import numpy as np import matplotlib.pyplot",
"term behaviour. ''' import numpy as np import matplotlib.pyplot as plt from random",
"{} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True)",
"state[idx] = state[idx] - 1 else: state[idx] = n - 1 return state",
"configuration. It then randomly updates the configuration to illustrate the long term behaviour.",
"r', ' + r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3'))",
"(x1 x2 ... xK) in an \"all-i\" configuration. It then randomly updates the",
"- 1 idx = randint(0, K) up = bool(randint(0, 1)) if up: if",
"K) up = bool(randint(0, 1)) if up: if state[idx] != n - 1:",
"= np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha = 0.8)",
"= state[idx] + 1 else: state[idx] = 0 else: if state[idx] != 0:",
"bar_color = '#477890' line_color = '#990D35' text_color = '#153243' if __name__ == '__main__':",
"alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n - 1, 0, K)",
"[http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to entropy. This script considers a",
"randint(0, n - 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter <",
"alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K",
"0, K) vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals,",
"r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_'",
"= 0 else: if state[idx] != 0: state[idx] = state[idx] - 1 else:",
"\\,$'.format(n) + r', ' + r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white',",
"plt.axis() axis = (-0.1*n, 1.1*n - 1, 0, K) vals = np.linspace(-n, 2*n,",
"1 else: state[idx] = 0 else: if state[idx] != 0: state[idx] = state[idx]",
"K = int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) +",
"- 1, 0.9*K, r'$K = {} \\,$'.format(K) + r', ' + '$n =",
"iters = int(sys.argv[3]) state = np.zeros(K) + randint(0, n - 1) iter =",
"configuration to illustrate the long term behaviour. ''' import numpy as np import",
"regarding classical complexity and it's relation to entropy. This script considers a string",
"the long term behaviour. ''' import numpy as np import matplotlib.pyplot as plt",
"align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n - 1, 0,",
"= int(sys.argv[3]) state = np.zeros(K) + randint(0, n - 1) iter = 0",
"Idea based on Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to",
"iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) + '/'",
"+ r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw()",
"classical complexity and it's relation to entropy. This script considers a string of",
"\\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001)",
"end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis",
"n = int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) + randint(0, n -",
"iter < iters: print(str(iter) + '/' + str(iters), end='\\r') unique, counts = np.unique(state,",
"= int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) + randint(0, n - 1)",
"random import randint import sys plt.style.use('ja') def update_configuration(state, n): K = len(state) -",
"+ '/' + str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5,",
"width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n - 1,",
"\\,$'.format(K) + r', ' + '$n = {} \\,$'.format(n) + r', ' +",
"complexity and it's relation to entropy. This script considers a string of K",
"1 return state bar_color = '#477890' line_color = '#990D35' text_color = '#153243' if",
"= '#153243' if __name__ == '__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters",
"import sys plt.style.use('ja') def update_configuration(state, n): K = len(state) - 1 idx =",
"plt.style.use('ja') def update_configuration(state, n): K = len(state) - 1 idx = randint(0, K)",
"state[idx] = 0 else: if state[idx] != 0: state[idx] = state[idx] - 1",
"else: if state[idx] != 0: state[idx] = state[idx] - 1 else: state[idx] =",
"n - 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters:",
"' + r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([])",
"''' import numpy as np import matplotlib.pyplot as plt from random import randint",
"color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K,",
"!= n - 1: state[idx] = state[idx] + 1 else: state[idx] = 0",
"= {} \\,$'.format(K) + r', ' + '$n = {} \\,$'.format(n) + r',",
"(-0.1*n, 1.1*n - 1, 0, K) vals = np.linspace(-n, 2*n, 100) avg =",
"updates the configuration to illustrate the long term behaviour. ''' import numpy as",
"plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K)",
"!= 0: state[idx] = state[idx] - 1 else: state[idx] = n - 1",
"return state bar_color = '#477890' line_color = '#990D35' text_color = '#153243' if __name__",
"style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K) +",
"= '#477890' line_color = '#990D35' text_color = '#153243' if __name__ == '__main__': K",
"idx = randint(0, K) up = bool(randint(0, 1)) if up: if state[idx] !=",
"= state[idx] - 1 else: state[idx] = n - 1 return state bar_color",
"state[idx] + 1 else: state[idx] = 0 else: if state[idx] != 0: state[idx]",
"- 1: state[idx] = state[idx] + 1 else: state[idx] = 0 else: if",
"+ r', ' + r'Iteration: ${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black',",
"2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4, color=line_color,",
"+ str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0,",
"plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n",
"+ (K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha = 0.8) plt.axis(axis) style",
"Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to entropy. This script",
"import randint import sys plt.style.use('ja') def update_configuration(state, n): K = len(state) - 1",
"**style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state",
"np.zeros(K) + randint(0, n - 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while",
"counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis()",
"state bar_color = '#477890' line_color = '#990D35' text_color = '#153243' if __name__ ==",
"+ randint(0, n - 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7)) while iter",
"long term behaviour. ''' import numpy as np import matplotlib.pyplot as plt from",
"< iters: print(str(iter) + '/' + str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True)",
"np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis =",
"else: state[idx] = n - 1 return state bar_color = '#477890' line_color =",
"= 0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) + '/' +",
"plt.plot(vals, avg, lw = 4, color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15,",
"if state[idx] != 0: state[idx] = state[idx] - 1 else: state[idx] = n",
"color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K) + r', ' +",
"line_color = '#990D35' text_color = '#153243' if __name__ == '__main__': K = int(sys.argv[1])",
"+ '$n = {} \\,$'.format(n) + r', ' + r'Iteration: ${} / {}",
"... xK) in an \"all-i\" configuration. It then randomly updates the configuration to",
"in an \"all-i\" configuration. It then randomly updates the configuration to illustrate the",
"iters: print(str(iter) + '/' + str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique,",
"n-bits (x1 x2 ... xK) in an \"all-i\" configuration. It then randomly updates",
"while iter < iters: print(str(iter) + '/' + str(iters), end='\\r') unique, counts =",
"This script considers a string of K n-bits (x1 x2 ... xK) in",
"a string of K n-bits (x1 x2 ... xK) in an \"all-i\" configuration.",
"def update_configuration(state, n): K = len(state) - 1 idx = randint(0, K) up",
"axis = (-0.1*n, 1.1*n - 1, 0, K) vals = np.linspace(-n, 2*n, 100)",
"= plt.axis() axis = (-0.1*n, 1.1*n - 1, 0, K) vals = np.linspace(-n,",
"= 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K =",
"if up: if state[idx] != n - 1: state[idx] = state[idx] + 1",
"1)) if up: if state[idx] != n - 1: state[idx] = state[idx] +",
"n - 1 return state bar_color = '#477890' line_color = '#990D35' text_color =",
"from random import randint import sys plt.style.use('ja') def update_configuration(state, n): K = len(state)",
"__name__ == '__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state",
"to entropy. This script considers a string of K n-bits (x1 x2 ...",
"n - 1: state[idx] = state[idx] + 1 else: state[idx] = 0 else:",
"state = np.zeros(K) + randint(0, n - 1) iter = 0 plt.ion() plt.figure(figsize=(7,",
"' + '$n = {} \\,$'.format(n) + r', ' + r'Iteration: ${} /",
"state[idx] = n - 1 return state bar_color = '#477890' line_color = '#990D35'",
"= bool(randint(0, 1)) if up: if state[idx] != n - 1: state[idx] =",
"unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis =",
"= n - 1 return state bar_color = '#477890' line_color = '#990D35' text_color",
"else: state[idx] = 0 else: if state[idx] != 0: state[idx] = state[idx] -",
"= len(state) - 1 idx = randint(0, K) up = bool(randint(0, 1)) if",
"#plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state = update_configuration(state, n) iter += 1",
"on Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to entropy. This",
"(K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha = 0.8) plt.axis(axis) style =",
"plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) + '/' + str(iters), end='\\r') unique,",
"0: state[idx] = state[idx] - 1 else: state[idx] = n - 1 return",
"the configuration to illustrate the long term behaviour. ''' import numpy as np",
"if __name__ == '__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3])",
"script considers a string of K n-bits (x1 x2 ... xK) in an",
"= dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K) + r',",
"avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha =",
"edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state = update_configuration(state,",
"plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) + '/' + str(iters), end='\\r')",
"1: state[idx] = state[idx] + 1 else: state[idx] = 0 else: if state[idx]",
"'#990D35' text_color = '#153243' if __name__ == '__main__': K = int(sys.argv[1]) n =",
"import numpy as np import matplotlib.pyplot as plt from random import randint import",
"illustrate the long term behaviour. ''' import numpy as np import matplotlib.pyplot as",
"{} \\,$'.format(K) + r', ' + '$n = {} \\,$'.format(n) + r', '",
"avg, lw = 4, color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color)",
"state[idx] != 0: state[idx] = state[idx] - 1 else: state[idx] = n -",
"as plt from random import randint import sys plt.style.use('ja') def update_configuration(state, n): K",
"- 1, 0, K) vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100) +",
"100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha",
"{} \\,$'.format(n) + r', ' + r'Iteration: ${} / {} \\,$'.format(iter, iters), **style,",
"int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) + randint(0, n",
"= int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) + randint(0,",
"1 else: state[idx] = n - 1 return state bar_color = '#477890' line_color",
"'#153243' if __name__ == '__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters =",
"counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n -",
"= 4, color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n -",
"lw = 4, color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n",
"r', ' + '$n = {} \\,$'.format(n) + r', ' + r'Iteration: ${}",
"return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis = (-0.1*n,",
"behaviour. ''' import numpy as np import matplotlib.pyplot as plt from random import",
"x2 ... xK) in an \"all-i\" configuration. It then randomly updates the configuration",
"int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K) + randint(0, n - 1) iter",
"matplotlib.pyplot as plt from random import randint import sys plt.style.use('ja') def update_configuration(state, n):",
"1, 0, K) vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n)",
"vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw",
"0.9*K, r'$K = {} \\,$'.format(K) + r', ' + '$n = {} \\,$'.format(n)",
"= np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color) axis = plt.axis() axis",
"state[idx] = state[idx] + 1 else: state[idx] = 0 else: if state[idx] !=",
"plt.text(0.3*n - 1, 0.9*K, r'$K = {} \\,$'.format(K) + r', ' + '$n",
"boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state = update_configuration(state, n)",
"randomly updates the configuration to illustrate the long term behaviour. ''' import numpy",
"state[idx] - 1 else: state[idx] = n - 1 return state bar_color =",
"'$n = {} \\,$'.format(n) + r', ' + r'Iteration: ${} / {} \\,$'.format(iter,",
"plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state = update_configuration(state, n) iter",
"n): K = len(state) - 1 idx = randint(0, K) up = bool(randint(0,",
"up = bool(randint(0, 1)) if up: if state[idx] != n - 1: state[idx]",
"xK) in an \"all-i\" configuration. It then randomly updates the configuration to illustrate",
"= {} \\,$'.format(n) + r', ' + r'Iteration: ${} / {} \\,$'.format(iter, iters),",
"text_color = '#153243' if __name__ == '__main__': K = int(sys.argv[1]) n = int(sys.argv[2])",
"np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4,",
"if state[idx] != n - 1: state[idx] = state[idx] + 1 else: state[idx]",
"= '#990D35' text_color = '#153243' if __name__ == '__main__': K = int(sys.argv[1]) n",
"axis = plt.axis() axis = (-0.1*n, 1.1*n - 1, 0, K) vals =",
"= np.zeros(K) + randint(0, n - 1) iter = 0 plt.ion() plt.figure(figsize=(7, 7))",
"0 plt.ion() plt.figure(figsize=(7, 7)) while iter < iters: print(str(iter) + '/' + str(iters),",
"'__main__': K = int(sys.argv[1]) n = int(sys.argv[2]) iters = int(sys.argv[3]) state = np.zeros(K)",
"4, color=line_color, alpha = 0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1,",
"+ r', ' + '$n = {} \\,$'.format(n) + r', ' + r'Iteration:",
"then randomly updates the configuration to illustrate the long term behaviour. ''' import",
"np import matplotlib.pyplot as plt from random import randint import sys plt.style.use('ja') def",
"r'$K = {} \\,$'.format(K) + r', ' + '$n = {} \\,$'.format(n) +",
"bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf() state =",
"and it's relation to entropy. This script considers a string of K n-bits",
"based on Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to entropy.",
"K n-bits (x1 x2 ... xK) in an \"all-i\" configuration. It then randomly",
"plt from random import randint import sys plt.style.use('ja') def update_configuration(state, n): K =",
"string of K n-bits (x1 x2 ... xK) in an \"all-i\" configuration. It",
"str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center', alpha=1.0, color=bar_color)",
"0.8) plt.axis(axis) style = dict(size=15, color=text_color) plt.text(0.3*n - 1, 0.9*K, r'$K = {}",
"entropy. This script considers a string of K n-bits (x1 x2 ... xK)",
"np.zeros(100) + (K/n) plt.plot(vals, avg, lw = 4, color=line_color, alpha = 0.8) plt.axis(axis)",
"K) vals = np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg,",
"'/' + str(iters), end='\\r') unique, counts = np.unique(state, return_counts=True) plt.bar(unique, counts, width=0.5, align='center',",
"/ {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter),",
"(2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation to entropy. This script considers",
"= (-0.1*n, 1.1*n - 1, 0, K) vals = np.linspace(-n, 2*n, 100) avg",
"1 idx = randint(0, K) up = bool(randint(0, 1)) if up: if state[idx]",
"state[idx] != n - 1: state[idx] = state[idx] + 1 else: state[idx] =",
"iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' + '{0:04d}'.format(iter), transparent=True) plt.pause(0.0001) plt.clf()",
"relation to entropy. This script considers a string of K n-bits (x1 x2",
"an \"all-i\" configuration. It then randomly updates the configuration to illustrate the long",
"import matplotlib.pyplot as plt from random import randint import sys plt.style.use('ja') def update_configuration(state,",
"''' Idea based on Shangnan (2019) [http://inspirehep.net/record/1722270] regarding classical complexity and it's relation",
"update_configuration(state, n): K = len(state) - 1 idx = randint(0, K) up =",
"color=bar_color) axis = plt.axis() axis = (-0.1*n, 1.1*n - 1, 0, K) vals",
"${} / {} \\,$'.format(iter, iters), **style, bbox=dict(facecolor='white', edgecolor='black', boxstyle='round,pad=0.3')) plt.xticks([]) plt.draw() #plt.savefig('frames/fig_' +",
"considers a string of K n-bits (x1 x2 ... xK) in an \"all-i\"",
"\"all-i\" configuration. It then randomly updates the configuration to illustrate the long term",
"= np.linspace(-n, 2*n, 100) avg = np.zeros(100) + (K/n) plt.plot(vals, avg, lw =",
"it's relation to entropy. This script considers a string of K n-bits (x1",
"randint import sys plt.style.use('ja') def update_configuration(state, n): K = len(state) - 1 idx",
"of K n-bits (x1 x2 ... xK) in an \"all-i\" configuration. It then",
"7)) while iter < iters: print(str(iter) + '/' + str(iters), end='\\r') unique, counts"
] |
[
"if pred in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue",
"if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue if",
"= line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1]",
"continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if 'topic_server' in pred:",
"'topic_server' in pred: continue result.write(line) filtercount += 1 print filtercount, linecount result.close() types.close()",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"continue result.write(line) filtercount += 1 print filtercount, linecount result.close() types.close() labels.close() print \"saved\"",
"'<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>',",
"2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0",
"'<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ]",
"+= 1 if linecount % 1000000 == 0 : print filtercount, linecount /",
"in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if 'topic_server'",
"'<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0 result = open(sys.argv[2], 'w')",
"'<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>',",
"CONDITIONS OF ANY KIND, either express or implied. See the License for the",
"dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>':",
"or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] +",
"'<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>',",
"Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"); you may",
"OR CONDITIONS OF ANY KIND, either express or implied. See the License for",
"limitations under the License. \"\"\" import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>',",
"] linecount = 0 filtercount = 0 result = open(sys.argv[2], 'w') types =",
"OF ANY KIND, either express or implied. See the License for the specific",
"to in writing, software distributed under the License is distributed on an \"AS",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"continue if 'topic_server' in pred: continue result.write(line) filtercount += 1 print filtercount, linecount",
"not use this file except in compliance with the License. You may obtain",
"License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000",
"specific language governing permissions and limitations under the License. \"\"\" import gzip import",
"\"\"\" import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>',",
"obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred ==",
"except in compliance with the License. You may obtain a copy of the",
"+ \"\\t\" + obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] +",
"License. \"\"\" import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>',",
"may not use this file except in compliance with the License. You may",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the",
"obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj",
"'<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount =",
"under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"== '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue if pred in",
"(sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1]",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"'<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>',",
"'<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>',",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"'<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>',",
"linecount / 1000000 sub, pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or",
"import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>',",
"print filtercount, linecount / 1000000 sub, pred, obj, dot = line.split(\"\\t\") if not",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue",
"pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue if pred",
"the License for the specific language governing permissions and limitations under the License.",
"'<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>':",
"'w') labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount += 1 if",
"language governing permissions and limitations under the License. \"\"\" import gzip import sys",
"ANY KIND, either express or implied. See the License for the specific language",
"linecount % 1000000 == 0 : print filtercount, linecount / 1000000 sub, pred,",
"'<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>'",
"pred: continue result.write(line) filtercount += 1 print filtercount, linecount result.close() types.close() labels.close() print",
"file except in compliance with the License. You may obtain a copy of",
"License for the specific language governing permissions and limitations under the License. \"\"\"",
"'<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>',",
"Unless required by applicable law or agreed to in writing, software distributed under",
"1000000 sub, pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,",
"'w') for line in gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000 ==",
"2.0 (the \"License\"); you may not use this file except in compliance with",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"/ 1000000 sub, pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')):",
"sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\")",
"+ obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" +",
"if 'topic_server' in pred: continue result.write(line) filtercount += 1 print filtercount, linecount result.close()",
"pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue if pred",
"See the License for the specific language governing permissions and limitations under the",
"'<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>',",
"\"\\n\") continue if pred in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"\"\\t\" + obj + \"\\n\") continue if pred in filters: continue if pred.startswith('/fictional_universe'):",
"0 : print filtercount, linecount / 1000000 sub, pred, obj, dot = line.split(\"\\t\")",
"if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue if",
"'<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0",
"0 filtercount = 0 result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels",
"continue if pred in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred:",
"+ \"\\t\" + obj + \"\\n\") continue if pred in filters: continue if",
"if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if 'topic_server' in pred: continue",
"Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not",
"'<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>',",
": print filtercount, linecount / 1000000 sub, pred, obj, dot = line.split(\"\\t\") if",
"the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"continue if 'wikipedia' in pred: continue if 'topic_server' in pred: continue result.write(line) filtercount",
"'<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>',",
"'<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue if pred in filters:",
"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",
"= 0 result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4],",
"(the \"License\"); you may not use this file except in compliance with the",
"= 0 filtercount = 0 result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w')",
"this file except in compliance with the License. You may obtain a copy",
"gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>',",
"== '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue if pred ==",
"pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred",
"== 0 : print filtercount, linecount / 1000000 sub, pred, obj, dot =",
"\"License\"); you may not use this file except in compliance with the License.",
"express or implied. See the License for the specific language governing permissions and",
"pred in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"you may not use this file except in compliance with the License. You",
"if linecount % 1000000 == 0 : print filtercount, linecount / 1000000 sub,",
"for the specific language governing permissions and limitations under the License. \"\"\" import",
"agreed to in writing, software distributed under the License is distributed on an",
"'<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>',",
"\"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\")",
"'<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0 result =",
"pred: continue if 'topic_server' in pred: continue result.write(line) filtercount += 1 print filtercount,",
"for line in gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000 == 0",
"distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"'<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>',",
"open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line in",
"the License. \"\"\" import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>',",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"permissions and limitations under the License. \"\"\" import gzip import sys filters =",
"'<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0 result = open(sys.argv[2],",
"labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount += 1 if linecount",
"in gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000 == 0 : print",
"sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>',",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"\"\\t\" + obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\"",
"Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the",
"All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"by applicable law or agreed to in writing, software distributed under the License",
"applicable law or agreed to in writing, software distributed under the License is",
"implied. See the License for the specific language governing permissions and limitations under",
"[ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>',",
"in pred: continue if 'topic_server' in pred: continue result.write(line) filtercount += 1 print",
"import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>',",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License",
"1000000 == 0 : print filtercount, linecount / 1000000 sub, pred, obj, dot",
"line in gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000 == 0 :",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version",
"= open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line",
"<reponame>google/freebase-wikidata-converter \"\"\" Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache",
"'<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount",
"continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue",
"'<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount =",
"if 'wikipedia' in pred: continue if 'topic_server' in pred: continue result.write(line) filtercount +=",
"linecount = 0 filtercount = 0 result = open(sys.argv[2], 'w') types = open(sys.argv[3],",
"law or agreed to in writing, software distributed under the License is distributed",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See",
"+ \"\\n\") continue if pred in filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia'",
"'<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0 result = open(sys.argv[2], 'w') types",
"'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]):",
"Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the \"License\");",
"Version 2.0 (the \"License\"); you may not use this file except in compliance",
"types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount",
"line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] +",
"in compliance with the License. You may obtain a copy of the License",
"1 if linecount % 1000000 == 0 : print filtercount, linecount / 1000000",
"the Apache License, Version 2.0 (the \"License\"); you may not use this file",
"use this file except in compliance with the License. You may obtain a",
"pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if 'topic_server' in pred: continue result.write(line)",
"open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount += 1",
"KIND, either express or implied. See the License for the specific language governing",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"sub, pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use",
"linecount += 1 if linecount % 1000000 == 0 : print filtercount, linecount",
"in writing, software distributed under the License is distributed on an \"AS IS\"",
"under the License. \"\"\" import gzip import sys filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>',",
"under the Apache License, Version 2.0 (the \"License\"); you may not use this",
"filters = [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>',",
"filters: continue if pred.startswith('/fictional_universe'): continue if 'wikipedia' in pred: continue if 'topic_server' in",
"+ \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1] + \"\\t\" + obj +",
"not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\" +",
"writing, software distributed under the License is distributed on an \"AS IS\" BASIS,",
"labels.write(sub[28:-1] + \"\\t\" + obj + \"\\n\") continue if pred in filters: continue",
"= [ '<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>',",
"'wikipedia' in pred: continue if 'topic_server' in pred: continue result.write(line) filtercount += 1",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"'<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>', '<http://rdf.freebase.com/ns/common.topic.description>', '<http://rdf.freebase.com/key/dataworld.freeq>', '<http://rdf.freebase.com/ns/type.permission.controls>', '<http://rdf.freebase.com/ns/type.object.permission>', '<http://rdf.freebase.com/key/en>', '<http://rdf.freebase.com/ns/common.document.text>', '<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>',",
"either express or implied. See the License for the specific language governing permissions",
"governing permissions and limitations under the License. \"\"\" import gzip import sys filters",
"filtercount, linecount / 1000000 sub, pred, obj, dot = line.split(\"\\t\") if not (sub.startswith('<http://rdf.freebase.com/ns/m.')",
"0 result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w')",
"'<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0 result",
"'<http://rdf.freebase.com/ns/common.notable_for.display_name>', '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>', '<http://rdf.freebase.com/ns/type.object.type>', '<http://rdf.freebase.com/ns/type.type.instance>', '<http://rdf.freebase.com/ns/type.object.key>', '<http://www.w3.org/2000/01/rdf-schema#label>', '<http://rdf.freebase.com/ns/type.object.name>', '<http://rdf.freebase.com/ns/common.topic.topic_equivalent_webpage>', '<http://rdf.freebase.com/ns/common.topic.notable_for>', '<http://rdf.freebase.com/ns/common.notable_for.predicate>', '<http://rdf.freebase.com/ns/common.notable_for.notable_object>', '<http://rdf.freebase.com/ns/common.notable_for.object>', '<http://rdf.freebase.com/ns/common.topic.notable_types>',",
"= open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount += 1 if linecount %",
"% 1000000 == 0 : print filtercount, linecount / 1000000 sub, pred, obj,",
"or agreed to in writing, software distributed under the License is distributed on",
"\"\"\" Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License,",
"if not (sub.startswith('<http://rdf.freebase.com/ns/m.') or sub.startswith('<http://rdf.freebase.com/ns/g.')): continue if pred == '<http://rdf.freebase.com/ns/type.object.type>': types.write(sub[28:-1] + \"\\t\"",
"+ obj + \"\\n\") continue if pred in filters: continue if pred.startswith('/fictional_universe'): continue",
"= open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for line in gzip.open(sys.argv[1]): linecount +=",
"filtercount = 0 result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels =",
"obj + \"\\n\") continue if pred in filters: continue if pred.startswith('/fictional_universe'): continue if",
"types.write(sub[28:-1] + \"\\t\" + obj[24:-1] + \"\\n\") continue if pred == '<http://rdf.freebase.com/ns/type.object.name>': labels.write(sub[28:-1]",
"result = open(sys.argv[2], 'w') types = open(sys.argv[3], 'w') labels = open(sys.argv[4], 'w') for",
"'<http://rdf.freebase.com/ns/common.topic.article>', '<http://rdf.freebase.com/ns/common.topic.image>', '<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount",
"Apache License, Version 2.0 (the \"License\"); you may not use this file except",
"or implied. See the License for the specific language governing permissions and limitations",
"with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"gzip.open(sys.argv[1]): linecount += 1 if linecount % 1000000 == 0 : print filtercount,",
"required by applicable law or agreed to in writing, software distributed under the",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software",
"the specific language governing permissions and limitations under the License. \"\"\" import gzip",
"and limitations under the License. \"\"\" import gzip import sys filters = [",
"in pred: continue result.write(line) filtercount += 1 print filtercount, linecount result.close() types.close() labels.close()",
"'<http://rdf.freebase.com/ns/common.topic.alias>', '<http://rdf.freebase.com/ns/common.document.source_uri>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.last_referenced_by>', '<http://rdf.freebase.com/ns/type.object.id>', '<http://rdf.freebase.com/ns/dataworld.gardening_hint.replaced_by>', '<http://rdf.freebase.com/ns/freebase.object_hints.best_hrid>' ] linecount = 0 filtercount = 0"
] |
[
"used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/'",
"'Campus' : \"\", 'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course",
"Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self,",
"a single course page. It is not used currently. class CourseInfoSpider(scrapy.Spider): name =",
"'Course Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom'",
"course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items(): value =",
"Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course",
"'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course Title'",
": \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\"",
"'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] #",
"response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()'",
"= 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')]",
"base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course Title' :",
"'[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items():",
"parse(self, response): course_dict = { 'Course Title' : \"\", 'Instructor' : \"\", 'Schedule':",
"is None else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first()",
"= ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design",
"[('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common",
"II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response):",
"\"\", 'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first()",
"classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items(): value = value.replace(u'\\xa0', u'",
"It is not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus']",
": \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\" } course_title =",
"used to scrape a single course page. It is not used currently. class",
"course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath +",
"# -*- coding: utf-8 -*- import scrapy # This file is used to",
"response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title is",
"course_dict['Course Title'] = course_title if course_sub_title is None else course_title + course_sub_title course_dict['Instructor']",
"= course_title if course_sub_title is None else course_title + course_sub_title course_dict['Instructor'] = response.xpath((",
"else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] =",
"\"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath((",
"= [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath =",
"+ course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath",
"response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus",
"course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()'",
"self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value",
"allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info",
"course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if",
"'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title",
"-*- import scrapy # This file is used to scrape a single course",
"start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath",
"self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first()",
"is used to scrape a single course page. It is not used currently.",
"course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath +",
")).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title",
"This file is used to scrape a single course page. It is not",
"\"\", 'Campus' : \"\", 'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath +",
"file is used to scrape a single course page. It is not used",
"= response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title",
")).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items(): value",
"def parse(self, response): course_dict = { 'Course Title' : \"\", 'Instructor' : \"\",",
"self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus =",
"\"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\" }",
"= response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for",
"scrapy # This file is used to scrape a single course page. It",
"currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')]",
"= '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course Title' : \"\",",
"to scrape a single course page. It is not used currently. class CourseInfoSpider(scrapy.Spider):",
"import scrapy # This file is used to scrape a single course page.",
"} course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath",
"name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II",
"response): course_dict = { 'Course Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\",",
"response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key,",
"= response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course",
"classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0]",
"# This file is used to scrape a single course page. It is",
"'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr'",
"course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath((",
"'[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title']",
"response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus']",
"= response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first()",
"is not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls",
"Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title is None else course_title +",
"{ 'Course Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\",",
"= response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract()",
"coding: utf-8 -*- import scrapy # This file is used to scrape a",
"+ '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1]",
"course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items(): value = value.replace(u'\\xa0', u' ')",
"if course_sub_title is None else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath +",
"single course page. It is not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info'",
"class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] #",
"= classroom_campus[0] for key, value in course_dict.items(): value = value.replace(u'\\xa0', u' ') yield",
"scrape a single course page. It is not used currently. class CourseInfoSpider(scrapy.Spider): name",
"'[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title is None else course_title",
"Title'] = course_title if course_sub_title is None else course_title + course_sub_title course_dict['Instructor'] =",
")).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] =",
"+ '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in",
"Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] =",
"'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\" } course_title",
")).extract_first() course_dict['Course Title'] = course_title if course_sub_title is None else course_title + course_sub_title",
"utf-8 -*- import scrapy # This file is used to scrape a single",
"'[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath",
"'[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] = classroom_campus[1] course_dict['Classroom']",
"['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')]",
"ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course Title' : \"\", 'Instructor' :",
"\"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\" } course_title = response.xpath((",
"= classroom_campus[1] course_dict['Classroom'] = classroom_campus[0] for key, value in course_dict.items(): value = value.replace(u'\\xa0',",
"# Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict =",
"course page. It is not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains",
"+ '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath((",
"course_dict = { 'Course Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus'",
"'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict",
": \"\", 'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()'",
"course_sub_title is None else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()'",
": \"\" } course_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title =",
"Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = {",
"course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()'",
"not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls =",
"None else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Instructor\")]/td/text()' )).extract_first() course_dict['Schedule']",
"self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath + '[contains(th/text(),\"Classroom\")]/td/text()' )).extract() course_dict['Campus'] =",
"Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' : \"\", 'Classroom' :",
"course_title if course_sub_title is None else course_title + course_sub_title course_dict['Instructor'] = response.xpath(( self.base_xpath",
"CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains = ['wsl.waseda.jp/syllabus'] start_urls = [('https://www.wsl.waseda.jp/syllabus/' 'JAA104.php?pKey=1200000007012017120000000712&pLng=jp')] # Spanish",
"page. It is not used currently. class CourseInfoSpider(scrapy.Spider): name = 'course_info' allowed_domains =",
"'Schedule': \"\", 'Campus' : \"\", 'Classroom' : \"\" } course_title = response.xpath(( self.base_xpath",
"-*- coding: utf-8 -*- import scrapy # This file is used to scrape",
"= { 'Course Title' : \"\", 'Instructor' : \"\", 'Schedule': \"\", 'Campus' :",
")).extract_first() course_dict['Schedule'] = response.xpath(( self.base_xpath + '[contains(th/text(),\"Term/Day/Period\")]/td/text()' )).extract_first() classroom_campus = response.xpath(( self.base_xpath +",
"self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title is None",
"'//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def parse(self, response): course_dict = { 'Course Title' : \"\", 'Instructor'",
"+ '[contains(th/text(),\"Course Title\")]/td/div/text()' )).extract_first() course_sub_title = response.xpath(( self.base_xpath + '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course",
"classroom_campus[0] for key, value in course_dict.items(): value = value.replace(u'\\xa0', u' ') yield course_dict",
"# Spanish II 'JAA104.php?pKey=210CO14300032017210CO1430021&pLng=en')] # Info Design 'JAA104.php?pKey=26GF02200201201726GF02200226&pLng=en')] base_xpath = '//*[@class=\"ct-common ct-sirabasu\"]/tbody/tr' def",
"+ '[contains(th/text(),\"Course Title\")]/td/p/text()' )).extract_first() course_dict['Course Title'] = course_title if course_sub_title is None else",
"<reponame>waseda-room-finder/waseda-syllabus-scraper<filename>wsl_spider/wsl_spider/spiders/course_info.py # -*- coding: utf-8 -*- import scrapy # This file is used"
] |
[
"in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric(",
"[] # Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in",
"of an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item",
"item in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id",
"list_metrics.append(metric) # Duration of an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration",
"seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id in list_items: item =",
"in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue in",
"= queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name], value=queue.get_in_queue_duration(item_id) )",
"Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric( labels=[],",
") list_metrics.append(metric) # Duration of an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration',",
"Queue in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id in list_items:",
"item_id in list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric(",
"Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None",
"item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name], value=queue.get_in_queue_duration(item_id) ) list_metrics.append(metric) return",
"'Total items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration",
"from prometheus_client.core import GaugeMetricFamily def make_metrics(queue): list_metrics = [] # Total items in",
"value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item in Queue metric = GaugeMetricFamily(",
"= queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id",
"make_metrics(queue): list_metrics = [] # Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total',",
"def make_metrics(queue): list_metrics = [] # Total items in Queue metric = GaugeMetricFamily(",
"GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric)",
") metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item in Queue",
"in list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id,",
"Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item",
"'Duration of a item in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items =",
"items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of",
"for item_id in list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id)",
"# Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue',",
"item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue",
"in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an",
"in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id in list_items: item",
"metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item in Queue metric",
"queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name], value=queue.get_in_queue_duration(item_id) ) list_metrics.append(metric)",
"# Duration of an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of",
"an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in",
"labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item in",
"items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None )",
"GaugeMetricFamily def make_metrics(queue): list_metrics = [] # Total items in Queue metric =",
"prometheus_client.core import GaugeMetricFamily def make_metrics(queue): list_metrics = [] # Total items in Queue",
"'jenkins_queue_item_duration', 'Duration of a item in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items",
"list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name],",
"GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue in seconds', labels=['queue_id', 'item_name'] )",
"list_metrics = [] # Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total",
"= [] # Total items in Queue metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items",
"Duration of an item in Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a",
"of a item in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items()",
"item = queue.get_item(item_id) item_name = item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name], value=queue.get_in_queue_duration(item_id)",
"labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id)",
"metric = GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items()",
"metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue in seconds', labels=['queue_id',",
") list_items = queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id) item_name =",
"'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() ) list_metrics.append(metric) #",
"= GaugeMetricFamily( 'jenkins_queue_total', 'Total items in Queue', labels=None ) metric.add_metric( labels=[], value=queue.get_total_items() )",
"Queue metric = GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue in seconds',",
"'item_name'] ) list_items = queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id) item_name",
"queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id) item_name = item['name'] queue_id =",
"labels=[], value=queue.get_total_items() ) list_metrics.append(metric) # Duration of an item in Queue metric =",
"import GaugeMetricFamily def make_metrics(queue): list_metrics = [] # Total items in Queue metric",
"in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for item_id in",
"= item['name'] queue_id = str(item_id) metric.add_metric( labels=[queue_id, item_name], value=queue.get_in_queue_duration(item_id) ) list_metrics.append(metric) return list_metrics",
"a item in Queue in seconds', labels=['queue_id', 'item_name'] ) list_items = queue.get_list_items() for",
"= GaugeMetricFamily( 'jenkins_queue_item_duration', 'Duration of a item in Queue in seconds', labels=['queue_id', 'item_name']",
"list_items = queue.get_list_items() for item_id in list_items: item = queue.get_item(item_id) item_name = item['name']"
] |
[
"import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import",
"db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1]",
"aLock.created_at).total_seconds() / 60 >= 15: # 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username,",
"select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked",
"or marked as false positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me =",
"= filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in artifact_txt_list:",
"positive by me, or marked as false positive by at least 2 people",
"== who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for row",
"distinct from src import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData",
"return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive by me,",
"manually_uploaded: bool = False) -> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list)",
"return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text)",
"artifact_txt_list) inserted_ids = [] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator,",
"from typing import List from sqlalchemy import insert, func, select, distinct from src",
"insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]:",
"import List from sqlalchemy import insert, func, select, distinct from src import db",
"string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier,",
"db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit()",
"typing import List from sqlalchemy import insert, func, select, distinct from src import",
"if my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username:",
"if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15: # 15min # print(\"Unlocking Artifact:",
"artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def",
"as false positive by me, or marked as false positive by at least",
"datetime import datetime from typing import List from sqlalchemy import insert, func, select,",
"inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return",
"inserted_ids = [] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded)",
"art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids",
"LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in result} return all_locks def update_api_locks():",
"marked as false positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter(",
"= select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts",
"def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for",
"== art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool = False)",
"q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for row in q_artifacts_marked_fp_by_me.union(q_artifacts_marked_fp_by_2).all()}",
"artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if",
"LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return",
"all_locks = {row[0]: row[1] for row in result} return all_locks def update_api_locks(): all_locks",
"[] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit()",
"as false positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by",
"15: # 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit()",
"select, distinct from src import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact,",
"least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query(",
"who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str,",
"label_text) return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return",
"not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit()",
"unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None:",
"if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result =",
"False) -> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = []",
"datetime.utcnow() for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15:",
"\"\"\" Return artifacts marked as false positive by me, or marked as false",
"get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row",
"positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in())",
"str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s),",
"-> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for",
"import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id:",
"def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact",
"\"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1)",
"for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return",
"identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry",
"from datetime import datetime from typing import List from sqlalchemy import insert, func,",
"created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry =",
"db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks =",
"in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def",
"return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all()",
"= db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in result} return",
"at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 =",
"func, select, distinct from src import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation,",
"int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded:",
"creator: str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list = filter(lambda s: not",
"me, or marked as false positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me",
"stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str)",
"str, creator: str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list = filter(lambda s:",
"import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str],",
"ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id",
"lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks()",
"people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() >",
"db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty,",
"result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock",
"all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks:",
"def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks: if",
"db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query =",
"int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) >",
"= LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds()",
"for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first()",
"artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]:",
"aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15: # 15min",
"get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str,",
"in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock",
"row[1] for row in result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime",
"string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier:",
"def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all())",
"db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def",
"my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id):",
"List[str], artifact_identifier: str, creator: str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list =",
"in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15: # 15min #",
"false positive by me, or marked as false positive by at least 2",
"username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by(",
"return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1))",
"-> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact, in",
"def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator:",
"LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar()",
"def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive by me, or marked",
"marked as false positive by me, or marked as false positive by at",
"artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result",
"db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in result} return all_locks",
"artifacts marked as false positive by me, or marked as false positive by",
"{} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all())",
"src import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common",
"return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in",
"update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks: if (now_datetime",
">= 15: # 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock)",
"uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where(",
"unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks",
"{}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count()",
"get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for",
"qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact, in db.session.execute(qry).all()] def",
"= {row[0]: row[1] for row in result} return all_locks def update_api_locks(): all_locks =",
"len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return",
"for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15: #",
"not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art,",
"= False) -> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids =",
"query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return",
"FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for",
"in result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for",
"def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_(",
"LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() /",
"aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int:",
"filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in artifact_txt_list: stmt",
"-> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def",
"/ 60 >= 15: # 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId,",
"datetime from typing import List from sqlalchemy import insert, func, select, distinct from",
"# 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def",
"all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow() for aLock in all_locks: if (now_datetime -",
"LabelingData.labeling == label_text) return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not",
"false positive by at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by ==",
"= [] for art in artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0])",
"from sqlalchemy import insert, func, select, distinct from src import db from src.database.models",
"1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive by",
"60 >= 15: # 15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id))",
"select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as",
"q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result",
"- aLock.created_at).total_seconds() / 60 >= 15: # 15min # print(\"Unlocking Artifact: {} ->",
"db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0]",
"= select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username):",
"def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts():",
"by me, or marked as false positive by at least 2 people \"\"\"",
"-> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by)",
"15min # print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count()",
"List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact, in db.session.execute(qry).all()]",
"(now_datetime - aLock.created_at).total_seconds() / 60 >= 15: # 15min # print(\"Unlocking Artifact: {}",
"is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username)",
"username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit() def",
"total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having(",
"def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool = False) -> List[int]:",
"s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in artifact_txt_list: stmt =",
"{row[0]: row[1] for row in result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all()",
"Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return",
"now_datetime = datetime.utcnow() for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60",
"all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >= 15: # 15min # print(\"Unlocking",
"[artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock =",
"result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in result}",
"return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool",
"db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is",
"# print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() ->",
"== label_text) return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username:",
"def unlock_artifacts_by(username): if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not",
"func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false",
"who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for row in",
"from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in",
"None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id))",
"bool = False) -> List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids",
"db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool =",
"src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def",
"row in result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime = datetime.utcnow()",
"import insert, func, select, distinct from src import db from src.database.models import Artifact,",
"str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact,",
"= LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if",
"update_api_locks() result = db.session.query(LockedArtifact.artifact_id, func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in",
"aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() ->",
"by at least 2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2",
"add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list",
"import datetime from typing import List from sqlalchemy import insert, func, select, distinct",
"artifact_txt_list: stmt = insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text:",
"not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username, artifact_id=artifact_id)) db.session.commit() def get_locked_artifacts(): update_api_locks() result = db.session.query(LockedArtifact.artifact_id,",
"2 people \"\"\" q_artifacts_marked_fp_by_me = db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count()",
"print(\"Unlocking Artifact: {} -> {}:{}\".format(aLock.username, aLock.sourceId, aLock.artifact_post_id)) db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int:",
"len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive by me, or",
"Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int):",
"db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling ==",
"List from sqlalchemy import insert, func, select, distinct from src import db from",
"= datetime.utcnow() for aLock in all_locks: if (now_datetime - aLock.created_at).total_seconds() / 60 >=",
"insert, func, select, distinct from src import db from src.database.models import Artifact, LockedArtifact,",
"db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for row in q_artifacts_marked_fp_by_me.union(q_artifacts_marked_fp_by_2).all()} return result",
"-> int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts():",
"List[int]: artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art",
"get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive by me, or marked as",
"return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if not username: return my_lock",
"select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling == label_text) return [artifact for artifact, in db.session.execute(qry).all()] def unlock_artifacts_by(username): if",
"artifact_txt_list = filter(lambda s: not string_none_or_empty(s), artifact_txt_list) inserted_ids = [] for art in",
"if not username: return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock)",
"= db.session.query(distinct(FlaggedArtifact.artifact_id)).filter( FlaggedArtifact.created_by == who_is_signed_in()) q_artifacts_marked_fp_by_2 = db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result =",
"art_id)).scalar() def add_artifacts(artifact_txt_list: List[str], artifact_identifier: str, creator: str, manually_uploaded: bool = False) ->",
"LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not",
"= db.session.query( distinct(FlaggedArtifact.artifact_id)).group_by(FlaggedArtifact.artifact_id).having(func.count() > 1) result = {row[0] for row in q_artifacts_marked_fp_by_me.union(q_artifacts_marked_fp_by_2).all()} return",
"FlaggedArtifact, LabelingData from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id ==",
"Return artifacts marked as false positive by me, or marked as false positive",
"src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def add_artifacts(artifact_txt_list:",
"not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return unlock_artifacts_by(username) db.session.add(LockedArtifact(created_by=username,",
"my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username, artifact_id): if not username: return",
"int: query = select(Artifact.id).except_( select(ArtifactLabelRelation.artifact_id).group_by(ArtifactLabelRelation.artifact_id).having( func.count(ArtifactLabelRelation.created_by) > 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\"",
"> 1)) return len(db.session.execute(query).all()) def get_false_positive_artifacts(): \"\"\" Return artifacts marked as false positive",
"from src import db from src.database.models import Artifact, LockedArtifact, ArtifactLabelRelation, FlaggedArtifact, LabelingData from",
"artifact_identifier: str, creator: str, manually_uploaded: bool = False) -> List[int]: artifact_txt_list = filter(lambda",
"from src.helper.tools_common import string_none_or_empty, who_is_signed_in def get_artifact_by_id(art_id: int): return db.session.execute(select(Artifact).where(Artifact.id == art_id)).scalar() def",
"sqlalchemy import insert, func, select, distinct from src import db from src.database.models import",
"inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) -> List[Artifact]: qry = select(Artifact).join(ArtifactLabelRelation.artifact).join(ArtifactLabelRelation.label).where( LabelingData.labeling",
"return my_lock = LockedArtifact.query.filter_by(created_by=username).first() if my_lock is not None: db.session.delete(my_lock) db.session.commit() def lock_artifact_by(username,",
"func.count(LockedArtifact.created_by)).group_by( LockedArtifact.artifact_id).all() all_locks = {row[0]: row[1] for row in result} return all_locks def",
"for row in result} return all_locks def update_api_locks(): all_locks = LockedArtifact.query.all() now_datetime =",
"= insert(Artifact).values(text=art, identifier=artifact_identifier, created_by=creator, uploaded_manually=manually_uploaded) inserted_ids.append(db.session.execute(stmt).inserted_primary_key[0]) db.session.commit() return inserted_ids def get_artifacts_with_label(label_text: str) ->",
"db.session.delete(aLock) db.session.commit() def total_artifact_count() -> int: return len(db.session.execute(select(Artifact.id)).all()) def artifact_needs_labeling_count() -> int: query"
] |
[
"= E_name + '\\n\\n' + E_description champ_info['E'] = combined_E # Add R R_name",
"re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return",
"self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*'",
"autocompleteList self.var = self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"] = tk.StringVar()",
"Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master",
"ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label",
"= json.load(f) global champ_info champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description",
"self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def",
"R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label",
"self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index)",
"to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4,",
"'-1' else: index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index) ==",
"matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def",
"in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern =",
"width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp =",
"to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20)",
"combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add Q",
"__init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent = args[0] # Custom matches",
"tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel,",
"passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add Q Q_name =",
"'': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\",",
"self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value)",
"AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda:",
"declared Use either with root window or Toplevel Bind Return key to selection",
"E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations",
"= data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description champ_info['W']",
"index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END,",
"if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp:",
"or toplevel as the second argument to use as entry's parent widget entry",
"self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False",
"event=None): if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False",
"for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken",
"# Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name +",
"from champion json files def get_PQWER(champion): \"\"\" Consumes a champion name in string",
"else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus()",
"else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index) ==",
"widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button =",
"files def get_PQWER(champion): \"\"\" Consumes a champion name in string form and returns",
"self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown)",
"self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode):",
"labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20)",
"champ_info['W'] = combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E",
"use as entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0,",
"\"\"\" Consumes a champion name in string form and returns a dictionary containing",
"= kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args,",
"features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon",
"self.comparison() if words: if not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"],",
"self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp =",
"Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted",
"self.listboxLength = 0 self.parent = args[0] # Custom matches function if 'matchesFunction' in",
"\"\"\" changes made: make widgets parent explicitly declared Use either with root window",
"widgets parent explicitly declared Use either with root window or Toplevel Bind Return",
"self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength)",
"R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text = tk.Label(topLevel, textvariable= P) #",
"json from tkinter import ttk # Helper function extracting ability descriptions from champion",
"E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description champ_info['E'] = combined_E",
"Image import json from tkinter import ttk # Helper function extracting ability descriptions",
"locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20)",
"Custom return function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else:",
"False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None):",
"else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END)",
"\"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\",
"# Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600,",
"column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit",
"boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20)",
"if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry):",
"= selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var =",
"if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index",
"R_name + '\\n\\n' + R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info",
"self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var",
"# tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon",
"\"\"\" #from tkinter import * import tkinter as tk import re from PIL",
"if self.listbox.curselection() == (): index = '-1' else: index = self.listbox.curselection()[0] if index",
"second argument to use as entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel,",
"name, index, mode): if self.var.get() == '': self.deleteListbox() else: words = self.comparison() if",
"= len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(),",
"= ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label = tk.Label(topLevel,",
"in string form and returns a dictionary containing the champion's passive, Q, W,",
"Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) #",
"# tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) #",
"self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w in self.autocompleteList",
"Consumes a champion name in string form and returns a dictionary containing the",
"tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or toplevel as the second argument",
"Bind Return key to selection method \"\"\" #from tkinter import * import tkinter",
"= data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description champ_info['E'] = combined_E #",
"R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' +",
"\"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern =",
"data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description champ_info['R'] =",
"Champions Dex') #pass either root or toplevel as the second argument to use",
"+ '\\n\\n' + W_description champ_info['W'] = combined_W # Add E E_name = data['data'][champion]['spells'][2]['name']",
"= tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label =",
"re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches",
"+ '\\n\\n' + E_description champ_info['E'] = combined_E # Add R R_name = data['data'][champion]['spells'][3]['name']",
"W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' +",
"data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description champ_info['R'] = combined_R return champ_info",
"*args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var",
"if not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection)",
"= data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description champ_info['R']",
"self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index) == -1: index =",
"w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken from",
"E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args,",
"E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label =",
"and R ability names and descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\")",
"= data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive #",
"__name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\",
"champ_info champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive",
"kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs)",
"self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var == '': self.var =",
"+ self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for",
"wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text",
"Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern,",
"else: index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1:",
"== '': self.deleteListbox() else: words = self.comparison() if words: if not self.listboxUp: self.listboxLength",
"y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END)",
"champ_info['Q'] = combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W",
"dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f)",
"== -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event):",
"W_name + '\\n\\n' + W_description champ_info['W'] = combined_W # Add E E_name =",
"class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent = args[0]",
"self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event):",
"if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0]",
"re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return function if 'returnFunction'",
"\"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\",
"column=0,pady=20) # Add text boxes # Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive'])",
"tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New",
"not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\",",
"search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P =",
"dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel,",
"as tk import re from PIL import ImageTk, Image import json from tkinter",
"Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\",",
"https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\",
"mode): if self.var.get() == '': self.deleteListbox() else: words = self.comparison() if words: if",
"-> dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data =",
"and returns a dictionary containing the champion's passive, Q, W, E, and R",
"pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit =",
"self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy()",
"descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read",
"Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n'",
"args[0] # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del",
"'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern",
"else: words = self.comparison() if words: if not self.listboxUp: self.listboxLength = len(words) self.listbox",
"w) else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False",
"del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args,",
"!= tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\" else: index =",
"topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or toplevel as the",
"= combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E =",
"data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add",
"(): index = '-1' else: index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index)",
"selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"]",
"tk.Label(topLevel, image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3,",
"selection method \"\"\" #from tkinter import * import tkinter as tk import re",
"PIL import ImageTk, Image import json from tkinter import ttk # Helper function",
"as entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0,",
"str(int(index) - 1) if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll!",
"= AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10,",
"+ '\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name']",
"= str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w",
"= data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description champ_info['W'] = combined_W #",
"text='Check code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon",
"= tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations to image labels",
"self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)]",
"Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific",
"kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) + '.*',",
"self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '-1'",
"= False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index",
"pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel",
"Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else:",
"if self.var.get() == '': self.deleteListbox() else: words = self.comparison() if words: if not",
"def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent = args[0] # Custom",
"#from tkinter import * import tkinter as tk import re from PIL import",
"= combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E'])",
"self.var.get() == '': self.deleteListbox() else: words = self.comparison() if words: if not self.listboxUp:",
"the second argument to use as entry's parent widget entry = AutocompleteEntry( autocompleteList,",
"image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0, pady=20)",
"ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel,",
"wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") #",
"= combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q =",
"= tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign",
"= matches # Custom return function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction']",
"= self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index) == -1: index",
"= tk.Label(topLevel, image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20)",
"# Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon",
"deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None): if self.listboxUp:",
"moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '-1' else: index",
"combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R'])",
"= passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add Q Q_name",
"\"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry)",
"parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button",
"pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20)",
"W, E, and R ability names and descriptions Parameters: ----------- champion string Example:",
"self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp",
"= tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\",",
"changes made: make widgets parent explicitly declared Use either with root window or",
"E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations to image",
"if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0,",
"del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) +",
"False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode): if self.var.get()",
"# Helper function extracting ability descriptions from champion json files def get_PQWER(champion): \"\"\"",
"locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0,",
"index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index) == -1:",
"if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList =",
"Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add W W_name =",
"self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode): if self.var.get() ==",
"W_description champ_info['W'] = combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description']",
"+ '\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name']",
"#super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var == '':",
"# Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name +",
"self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\",",
"= self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self,",
"width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) #",
"self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w",
"<reponame>jsleslie/PQWER<gh_stars>0 \"\"\" changes made: make widgets parent explicitly declared Use either with root",
"= Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add W W_name",
"re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return function if 'returnFunction' in kwargs:",
"E_name + '\\n\\n' + E_description champ_info['E'] = combined_E # Add R R_name =",
"Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n'",
"acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either root",
"Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q",
"wraplength=600, justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1,",
"combined_W = W_name + '\\n\\n' + W_description champ_info['W'] = combined_W # Add E",
"self.returnFunction(value) def changed(self, name, index, mode): if self.var.get() == '': self.deleteListbox() else: words",
"return re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass",
"samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent =",
"import tkinter as tk import re from PIL import ImageTk, Image import json",
"columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P",
"def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else:",
"index = \"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def",
"height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True",
"tkinter import * import tkinter as tk import re from PIL import ImageTk,",
"= combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W =",
"self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w) else:",
"= tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or toplevel as the second",
"self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self,",
"to selection method \"\"\" #from tkinter import * import tkinter as tk import",
"pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add",
"either root or toplevel as the second argument to use as entry's parent",
"'\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description",
"self.matchesFunction = matches # Custom return function if 'returnFunction' in kwargs: self.returnFunction =",
"bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images",
"tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp",
"self.parent = args[0] # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction =",
"----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f:",
"print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList",
"= 0 self.parent = args[0] # Custom matches function if 'matchesFunction' in kwargs:",
"# Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20)",
"== '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp)",
"**kwargs): self.listboxLength = 0 self.parent = args[0] # Custom matches function if 'matchesFunction'",
"= tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20)",
"- 1) if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index)",
"Dex') #pass either root or toplevel as the second argument to use as",
"self.listbox.activate(index) def comparison(self): return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if",
"# Custom return function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction']",
"Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info champ_info",
"= False def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE)",
"# Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name +",
"Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text =",
"import json from tkinter import ttk # Helper function extracting ability descriptions from",
"column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit = tk.Button(topLevel, text=\"Exit",
"re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either",
"select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp =",
"tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text",
"column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1,",
"champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info champ_info =dict()",
"W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList,",
"len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def",
"comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\"))",
"matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root =",
"code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon =",
"champ_info['E'] = combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R",
"self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength",
"# Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0)",
"from PIL import ImageTk, Image import json from tkinter import ttk # Helper",
"self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None):",
"\"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return",
"text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\"))",
"=dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name",
"= ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label =",
"self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp =",
"\"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*',",
"-1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if",
"self.listboxUp: if self.listbox.curselection() == (): index = '-1' else: index = self.listbox.curselection()[0] if",
"Add text boxes # Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text =",
"champion name in string form and returns a dictionary containing the champion's passive,",
"tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0)",
"= autocompleteList self.var = self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"] =",
"import ImageTk, Image import json from tkinter import ttk # Helper function extracting",
"str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w in",
"== '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\",
"Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) #",
"import * import tkinter as tk import re from PIL import ImageTk, Image",
"R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs):",
"E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit = tk.Button(topLevel,",
"justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign",
"passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label",
"function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value):",
"data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive'] =",
"= kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*' +",
"self.listboxUp = False def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value =",
"or Toplevel Bind Return key to selection method \"\"\" #from tkinter import *",
"*args, **kwargs): self.listboxLength = 0 self.parent = args[0] # Custom matches function if",
"R_label = tk.Label(topLevel, image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0,",
"self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False",
"topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3)",
"words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp",
"# tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon =",
"matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern,",
"in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction =",
"from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss",
"self.listbox.curselection() == (): index = '-1' else: index = self.listbox.curselection()[0] if index !=",
"image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations to",
"# Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w in self.autocompleteList if",
"self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def",
"1) if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index)",
"Q_description champ_info['Q'] = combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description']",
"update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) #",
"True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END,",
"E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text = tk.Label(topLevel,",
"acListEntry) self.matchesFunction = matches # Custom return function if 'returnFunction' in kwargs: self.returnFunction",
"them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label =",
"self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"]",
"tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\")",
"#pass either root or toplevel as the second argument to use as entry's",
"self.var = self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w',",
"= data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q #",
"w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE))",
"text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check",
"autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get()))",
"returns a dictionary containing the champion's passive, Q, W, E, and R ability",
"autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu",
"* import tkinter as tk import re from PIL import ImageTk, Image import",
"root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or",
"\"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global",
"Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength =",
"get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data",
"text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\")",
"justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text =",
"string form and returns a dictionary containing the champion's passive, Q, W, E,",
"root window or Toplevel Bind Return key to selection method \"\"\" #from tkinter",
"made: make widgets parent explicitly declared Use either with root window or Toplevel",
"combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name",
"# Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction']",
"= self[\"textvariable\"] if self.var == '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed)",
"len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y()",
"column=1, pady=20) # Add exit button button_quit = tk.Button(topLevel, text=\"Exit Program\", command=root.quit) button_quit.grid(row=10,",
"self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else:",
"self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() ==",
"champion's passive, Q, W, E, and R ability names and descriptions Parameters: -----------",
"+ Q_description champ_info['Q'] = combined_Q # Add W W_name = data['data'][champion]['spells'][1]['name'] W_description =",
"self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index =",
"def matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return",
"tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon =",
"tk import re from PIL import ImageTk, Image import json from tkinter import",
"extracting ability descriptions from champion json files def get_PQWER(champion): \"\"\" Consumes a champion",
"kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue",
"json.load(f) global champ_info champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description =",
"padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel,",
"in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy()",
"pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text =",
"+ '\\n\\n' + R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info =",
"autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent = args[0] # Custom matches function",
"Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n'",
"\"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return",
"Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) +",
"ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them",
"'.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches #",
"as f: data = json.load(f) global champ_info champ_info =dict() # Add passive passive_name",
"column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text = tk.Label(topLevel, textvariable=",
"= tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text",
"self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name,",
"text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) # Load",
"Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text",
"else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w",
"+ W_description champ_info['W'] = combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description =",
"tkinter as tk import re from PIL import ImageTk, Image import json from",
"event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index =",
"def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList",
"W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes #",
"= len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox()",
"acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk()",
"self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion",
"False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index =",
"+ passive_description champ_info['passive'] = combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description =",
"self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == ():",
"Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry):",
"champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W'])",
"def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp",
"Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern",
"Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon =",
"passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' +",
"string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\")",
"= '-1' else: index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index)",
"passive_description champ_info['passive'] = combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description']",
"# Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength",
"= tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label =",
"False def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy()",
"kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue)",
"self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index =",
"entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic",
"= re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel =",
"combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name",
"entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2)",
"W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description champ_info['W'] = combined_W",
"tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel,",
"= combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R =",
"index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1)",
"boxes # Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\",",
"parent explicitly declared Use either with root window or Toplevel Bind Return key",
"import re from PIL import ImageTk, Image import json from tkinter import ttk",
"= tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) #",
"+ re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom",
"= self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\",",
"if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None): if self.listboxUp: index =",
"changed(self, name, index, mode): if self.var.get() == '': self.deleteListbox() else: words = self.comparison()",
"'': self.deleteListbox() else: words = self.comparison() if words: if not self.listboxUp: self.listboxLength =",
"for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if self.listboxUp:",
"tk.Button(topLevel, text='Check code comments').grid(column=0) # Load images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\"))",
"'0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index)",
"tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\")",
"= tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to",
"E_description champ_info['E'] = combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description']",
"self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words)",
"Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) #",
"= ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon =",
"Toplevel Bind Return key to selection method \"\"\" #from tkinter import * import",
"pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes",
"passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description",
"def get_PQWER(champion): \"\"\" Consumes a champion name in string form and returns a",
"pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit = tk.Button(topLevel, text=\"Exit Program\",",
"= data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description champ_info['E']",
"== (): index = '-1' else: index = self.listbox.curselection()[0] if index != tk.END:",
"column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text",
"justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text =",
"Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index",
"self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength =",
"search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel,",
"if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def",
"descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular",
"wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text",
"function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue,",
"a dictionary containing the champion's passive, Q, W, E, and R ability names",
"self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection)",
"self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place(",
"passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive'] = combined_passive",
"return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) #",
"combined_R = R_name + '\\n\\n' + R_description champ_info['R'] = combined_R return champ_info def",
"index, mode): if self.var.get() == '': self.deleteListbox() else: words = self.comparison() if words:",
"as the second argument to use as entry's parent widget entry = AutocompleteEntry(",
"kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile(",
"inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel,",
"a champion name in string form and returns a dictionary containing the champion's",
"# Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon)",
"tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel,",
"words: if not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\",",
"return function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def",
"self.deleteListbox() else: words = self.comparison() if words: if not self.listboxUp: self.listboxLength = len(words)",
"+ R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive'])",
"tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0,",
"re from PIL import ImageTk, Image import json from tkinter import ttk #",
"entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\",",
"data = json.load(f) global champ_info champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name']",
"self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode): if self.var.get() == '': self.deleteListbox()",
"command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0)",
"[w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': #",
"pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit",
"# Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3,",
"dictionary containing the champion's passive, Q, W, E, and R ability names and",
"Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as",
"image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon)",
"= W_name + '\\n\\n' + W_description champ_info['W'] = combined_W # Add E E_name",
"= data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q']",
"json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info champ_info =dict() #",
"\"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def",
"# tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0)",
"= ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place",
"Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(),",
"if int(index) == self.listboxLength-1: index = \"0\" else: index = str(int(index)+1) self.listbox.see(index) #",
"data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description champ_info['E'] = combined_E # Add",
"in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/",
"images passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\"))",
"Return key to selection method \"\"\" #from tkinter import * import tkinter as",
"x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0,",
"update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from",
"self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self,",
"re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex')",
"self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self,",
"Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5,",
"column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add",
"Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code",
"self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection)",
"# Add exit button button_quit = tk.Button(topLevel, text=\"Exit Program\", command=root.quit) button_quit.grid(row=10, column=3) root.mainloop()",
"self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def",
"== (): index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index)",
"= tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\",",
"Helper function extracting ability descriptions from champion json files def get_PQWER(champion): \"\"\" Consumes",
"def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self,",
"'__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\",
"P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text",
"tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) # Assign locations",
"index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\" else: index",
"and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue)",
"AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent = args[0] #",
"W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description",
"Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description",
"W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside",
"ImageTk, Image import json from tkinter import ttk # Helper function extracting ability",
"tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if",
"# tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed",
"event): if self.listboxUp: if self.listbox.curselection() == (): index = '-1' else: index =",
"tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600,",
"tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or toplevel as",
"self.var == '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\",",
"event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None): if self.listboxUp: index",
"tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0) # tk.Button(topLevel, text='Check code comments').grid(column=0) #",
"P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600,",
"index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp:",
"'.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions",
"moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index",
"= self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value)",
"\"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue,",
"image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5,",
"# tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel,",
"containing the champion's passive, Q, W, E, and R ability names and descriptions",
"E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' +",
"self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\" else: index = str(int(index)+1) self.listbox.see(index)",
"return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return function if 'returnFunction' in",
"def changed(self, name, index, mode): if self.var.get() == '': self.deleteListbox() else: words =",
"# Read champ-specific json with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info",
"self.listboxUp: index = self.listbox.curselection()[0] value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END)",
"name in string form and returns a dictionary containing the champion's passive, Q,",
"Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\")",
"data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description champ_info['E'] =",
"\"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\ \"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"]",
"self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection()",
"Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def",
"passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4, column=0, pady=20) R_label.grid(row=5, column=0,pady=20) #",
"R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q'])",
"int(index) == self.listboxLength-1: index = \"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll!",
"text boxes # Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel,",
"and descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" #",
"if self.var == '': self.var = self[\"textvariable\"] = tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection)",
"index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index",
"int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self,",
"= False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode): if",
"R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description champ_info['R'] = combined_R",
"names and descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\"",
"champ_info['passive'] = combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q",
"W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1, pady=20) R_text.grid(row=5, column=1, pady=20) # Add exit button",
"get_PQWER(champion): \"\"\" Consumes a champion name in string form and returns a dictionary",
"= False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self,",
"from tkinter import ttk # Helper function extracting ability descriptions from champion json",
"the champion's passive, Q, W, E, and R ability names and descriptions Parameters:",
"combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name",
"= self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index =",
"'\\n\\n' + R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion): champ_info = get_PQWER(champion)",
"combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add W",
"from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0 self.parent",
"'.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return function if",
"text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1, pady=20) E_text.grid(row=4, column=1,",
"ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon)",
"either with root window or Toplevel Bind Return key to selection method \"\"\"",
"def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted",
"# P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\")",
"champ_info def update_descriptions(champion): champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class",
"'\\n\\n' + E_description champ_info['E'] = combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description",
"value = self.listbox.get(tk.ACTIVE) self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def",
"combined_E = E_name + '\\n\\n' + E_description champ_info['E'] = combined_E # Add R",
"= str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if",
"value) self.returnFunction(value) def changed(self, name, index, mode): if self.var.get() == '': self.deleteListbox() else:",
"R_name = data['data'][champion]['spells'][3]['name'] R_description = data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description",
"champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json with",
"self.listboxUp = True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in",
"adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self, autocompleteList, *args, **kwargs): self.listboxLength = 0",
"# Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\",
"to use as entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32, matchesFunction=matches)",
"ability names and descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary",
"get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry):",
"self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() ==",
"tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index, mode): if self.var.get() == '':",
"tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\" else: index = str(int(index)+1)",
"re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel()",
"'\\n\\n' + W_description champ_info['W'] = combined_W # Add E E_name = data['data'][champion]['spells'][2]['name'] E_description",
"Q, W, E, and R ability names and descriptions Parameters: ----------- champion string",
"index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self): return [w for",
"w)] if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\",
"\"Shaco\",\"Shen\",\"Shyvana\",\"Singed\",\"Sion\",\"Sivir\",\"Skarner\",\"Sona\",\"Soraka\",\"Swain\",\"Sylas\",\"Syndra\",\"<NAME>\",\"Taliyah\",\\ \"Talon\",\"Taric\",\"Teemo\",\"Thresh\",\"Tristana\",\"Trundle\",\"Tryndamere\",\"Twisted Fate\",\"Twitch\",\"Udyr\",\"Urgot\",\"Varus\",\"Vayne\",\"Veigar\",\\ \"Vel'Koz\",\"Vi\",\"Viktor\",\"Vladimir\",\"Volibear\",\"Warwick\",\"Wukong\",\"Xayah\",\"Xerath\",\"<NAME>\",\"Yasuo\",\"Yone\",\"Yorick\",\"Yuumi\",\"Zac\",\"Zed\",\"Ziggs\",\"Zilean\",\"Zoe\",\"Zyra\"] def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE)",
"= True else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words:",
"def matches(fieldValue, acListEntry): pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root",
"= tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() + self.winfo_height())",
"self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\"",
"argument to use as entry's parent widget entry = AutocompleteEntry( autocompleteList, topLevel, width=32,",
"Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' +",
"Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class AutocompleteEntry(tk.Entry): def __init__(self,",
"+ '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches # Custom return function",
"labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon)",
"# Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == ():",
"Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n'",
"pady=20) # Add exit button button_quit = tk.Button(topLevel, text=\"Exit Program\", command=root.quit) button_quit.grid(row=10, column=3)",
"self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp =",
"with root window or Toplevel Bind Return key to selection method \"\"\" #from",
"if words: if not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength)",
"kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs)",
"'\\n\\n' + passive_description champ_info['passive'] = combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description",
"selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event):",
"Use either with root window or Toplevel Bind Return key to selection method",
"== self.listboxLength-1: index = \"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index)",
"Place them inside labels passive_label = tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label",
"E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name + '\\n\\n' + E_description",
"Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20) W_text.grid(row=3, column=1,",
"method \"\"\" #from tkinter import * import tkinter as tk import re from",
"champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive =",
"+ E_description champ_info['E'] = combined_E # Add R R_name = data['data'][champion]['spells'][3]['name'] R_description =",
"R_text.grid(row=5, column=1, pady=20) # Add exit button button_quit = tk.Button(topLevel, text=\"Exit Program\", command=root.quit)",
"# Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name +",
"----------- champion string Example: ----------- get_PQWER(\"Malphite\") -> dictionary \"\"\" # Read champ-specific json",
"ttk # Helper function extracting ability descriptions from champion json files def get_PQWER(champion):",
"pady=20) R_label.grid(row=5, column=0,pady=20) # Add text boxes # Passive_text = tk.Label(topLevel, textvariable= P)",
"justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1,",
"f: data = json.load(f) global champ_info champ_info =dict() # Add passive passive_name =",
"with open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info champ_info =dict() # Add",
"= self.comparison() if words: if not self.listboxUp: self.listboxLength = len(words) self.listbox = tk.Listbox(self.parent,",
"explicitly declared Use either with root window or Toplevel Bind Return key to",
"Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0, pady=20) E_label.grid(row=4,",
"tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text =",
"event): if self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if",
"Add W W_name = data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n'",
"topLevel.title('League Champions Dex') #pass either root or toplevel as the second argument to",
"ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\"))",
"= tk.Tk() topLevel = tk.Toplevel() topLevel.title('League Champions Dex') #pass either root or toplevel",
"= R_name + '\\n\\n' + R_description champ_info['R'] = combined_R return champ_info def update_descriptions(champion):",
"Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label",
"open(f\"data/dragontail-11.1.1/11.1.1/data/en_US/champion/{champion}.json\") as f: data = json.load(f) global champ_info champ_info =dict() # Add passive",
"R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1, column=1,",
"wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text boxes",
"self.listbox.destroy() self.listboxUp = False def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0] value",
"= [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and",
"= data['data'][champion]['spells'][3]['description'] combined_R = R_name + '\\n\\n' + R_description champ_info['R'] = combined_R return",
"def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '-1' else:",
"0 self.parent = args[0] # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction",
"self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None): if self.listboxUp: index = self.listbox.curselection()[0]",
"= tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar()",
"self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp:",
"= args[0] # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction']",
"'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value) self.returnFunction",
"E, and R ability names and descriptions Parameters: ----------- champion string Example: -----------",
"self.listboxLength-1: index = \"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index)",
"justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2, column=1, pady=20)",
"self.listbox.selection_clear(first=index) index = str(int(index) - 1) if int(index) == -1: index = str(self.listboxLength-1)",
"else: self.listboxLength = len(words) self.listbox.config(height=self.listboxLength) self.listbox.delete(0, tk.END) for w in words: self.listbox.insert(tk.END, w)",
"self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if",
"text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) # tk.Button(topLevel, text='New features').grid(column=0)",
"ability descriptions from champion json files def get_PQWER(champion): \"\"\" Consumes a champion name",
"# Add text boxes # Passive_text = tk.Label(topLevel, textvariable= P) # P.set(champ_info['passive']) Passive_text",
"image=R_icon) # Assign locations to image labels passive_label.grid(row=1,column=0, pady=20) Q_label.grid(row=2,column=0, pady=20) W_label.grid(row=3, column=0,",
"W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\",",
"tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") # Assign locations to text boxes Passive_text.grid(row=1, column=1, pady=20) Q_text.grid(row=2,",
"tkinter import ttk # Helper function extracting ability descriptions from champion json files",
"index = '-1' else: index = self.listbox.curselection()[0] if index != tk.END: self.listbox.selection_clear(first=index) if",
"combined_passive # Add Q Q_name = data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name",
"text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0) # tk.Button(topLevel, text='Fixed bugs').grid(column=0) #",
"matchesFunction=matches) entry.grid(row=0, column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save",
"= re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction =",
"toplevel as the second argument to use as entry's parent widget entry =",
"window or Toplevel Bind Return key to selection method \"\"\" #from tkinter import",
"comparison(self): return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ ==",
"textvariable= P) # P.set(champ_info['passive']) Passive_text = tk.Label(topLevel, text=\"Placeholder\", wraplength=600, justify=\"left\") Q_text = tk.Label(topLevel,text=\"Placeholder\",",
"= tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") R_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600,",
"= ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/R.png\")) # Place them inside labels",
"data['data'][champion]['spells'][0]['name'] Q_description = data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q'] =",
"column=0, columnspan=2) search_button = tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions",
"pattern = re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction",
"import ttk # Helper function extracting ability descriptions from champion json files def",
"= data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description'] combined_passive = passive_name + '\\n\\n' + passive_description champ_info['passive']",
"# Add E E_name = data['data'][champion]['spells'][2]['name'] E_description = data['data'][champion]['spells'][2]['description'] combined_E = E_name +",
"self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0'",
"key to selection method \"\"\" #from tkinter import * import tkinter as tk",
"descriptions from champion json files def get_PQWER(champion): \"\"\" Consumes a champion name in",
"champ_info = get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py",
"self.listbox.destroy() self.listboxUp = False self.delete(0, tk.END) self.insert(tk.END, value) self.returnFunction(value) def changed(self, name, index,",
"passive_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Passive.png\")) Q_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/Q.png\")) W_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/W.png\")) E_icon = ImageTk.PhotoImage(Image.open(\"data/inhouse/img/E.png\")) R_icon",
"= tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") W_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600, justify=\"left\") E_text = tk.Label(topLevel,text=\"Placeholder\", wraplength=600,",
"tk.END) for w in words: self.listbox.insert(tk.END, w) else: self.deleteListbox() def selection(self, event): if",
"def comparison(self): return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__",
"data['data'][champion]['spells'][1]['name'] W_description = data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description champ_info['W'] =",
"acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry)",
"data['data'][champion]['spells'][0]['description'] combined_Q = Q_name + '\\n\\n' + Q_description champ_info['Q'] = combined_Q # Add",
"self.listboxUp: self.var.set(self.listbox.get(tk.ACTIVE)) self.listbox.destroy() self.listboxUp = False self.icursor(tk.END) def moveUp(self, event): if self.listboxUp: if",
"W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon) #",
"form and returns a dictionary containing the champion's passive, Q, W, E, and",
"= \"0\" else: index = str(int(index)+1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def comparison(self):",
"self.listbox = tk.Listbox(self.parent, width=self[\"width\"], height=self.listboxLength) self.listbox.bind(\"<Button-1>\", self.selection) self.listbox.bind(\"<Right>\", self.selection) self.listbox.place( x=self.winfo_x(), y=self.winfo_y() +",
"tk.Button(topLevel,text=\"Search\", padx=10, command=lambda: update_descriptions(entry.get())) search_button.grid(row=0,column=3) # Save dynamic descriptions P = tk.StringVar() #",
"= str(int(index) - 1) if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index) #",
"**kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var == '': self.var",
"else: def matches(fieldValue, acListEntry): pattern = re.compile( '.*' + re.escape(fieldValue) + '.*', re.IGNORECASE)",
"root or toplevel as the second argument to use as entry's parent widget",
"Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\ \"Rammus\",\"Rek'Sai\",\"Rell\",\"Renekton\",\"Rengar\",\"Riven\",\"Rumble\",\"Ryze\",\"Samira\",\"Sejuani\",\"Senna\",\"Seraphine\",\"Sett\",\\",
"if self.listboxUp: if self.listbox.curselection() == (): index = '-1' else: index = self.listbox.curselection()[0]",
"= '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) - 1) if",
"index = str(int(index) - 1) if int(index) == -1: index = str(self.listboxLength-1) self.listbox.see(index)",
"tk.Label(topLevel, image=passive_icon) Q_label = tk.Label(topLevel, image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel,",
"selectedValue(value): print(value) self.returnFunction = selectedValue tk.Entry.__init__(self, *args, **kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList =",
"str(self.listboxLength-1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) def moveDown(self, event): if self.listboxUp: if self.listbox.curselection()",
"make widgets parent explicitly declared Use either with root window or Toplevel Bind",
"**kwargs) #super().__init__(*args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self[\"textvariable\"] if self.var ==",
"R ability names and descriptions Parameters: ----------- champion string Example: ----------- get_PQWER(\"Malphite\") ->",
"data['data'][champion]['spells'][1]['description'] combined_W = W_name + '\\n\\n' + W_description champ_info['W'] = combined_W # Add",
"words = self.comparison() if words: if not self.listboxUp: self.listboxLength = len(words) self.listbox =",
"passive, Q, W, E, and R ability names and descriptions Parameters: ----------- champion",
"[\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr. Mundo\",\"Draven\",\\ \"Ekko\",\"Elise\",\"Evelynn\",\"Ezreal\",\"Fiddlesticks\",\"Fiora\",\"Fizz\",\"Galio\",\"Gangplank\",\"Garen\",\"Gnar\",\"Gragas\",\"Graves\",\"Hecarim\",\\ \"Heimerdinger\",\"Illaoi\",\"Irelia\",\"Ivern\",\"Janna\",\"<NAME>\",\"Jax\",\"Jayce\",\"Jhin\",\"Jinx\",\"Kai'Sa\",\"Kalista\",\"Karma\",\"Karthus\",\\ \"Kassadin\",\"Katarina\",\"Kayle\",\"Kayn\",\"Kennen\",\"Kha'Zix\",\"Kindred\",\"Kled\",\"Kog'Maw\",\"LeBlanc\",\"<NAME>\",\"Leona\",\"Lillia\",\"Lissandra\",\\ \"Lucian\",\"Lulu\",\"Lux\",\"Malphite\",\"Malzahar\",\"Maokai\",\"Master Yi\",\"Miss Fortune\",\"Mordekaiser\",\"Morgana\",\"Nami\",\"Nasus\",\"Nautilus\",\\ \"Neeko\",\"Nidalee\",\"Nocturne\",\"Nunu and Willump\",\"Olaf\",\"Orianna\",\"Ornn\",\"Pantheon\",\"Poppy\",\"Pyke\",\"Qiyana\",\"Quinn\",\"Rakan\",\\",
"if index != tk.END: self.listbox.selection_clear(first=index) if int(index) == self.listboxLength-1: index = \"0\" else:",
"self.selection) self.bind(\"<Escape>\", self.deleteListbox) self.listboxUp = False def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp",
"champion json files def get_PQWER(champion): \"\"\" Consumes a champion name in string form",
"+ '.*', re.IGNORECASE) return re.match(pattern, acListEntry) root = tk.Tk() topLevel = tk.Toplevel() topLevel.title('League",
"self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList",
"return [w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w)] if __name__ == '__main__':",
"function extracting ability descriptions from champion json files def get_PQWER(champion): \"\"\" Consumes a",
"image=Q_icon) W_label = tk.Label(topLevel, image=W_icon) E_label = tk.Label(topLevel, image=E_icon) R_label = tk.Label(topLevel, image=R_icon)",
"tk.StringVar() self.var.trace('w', self.changed) self.bind(\"<Right>\", self.selection) self.bind(\"<Up>\", self.moveUp) self.bind(\"<Down>\", self.moveDown) self.bind(\"<Return>\", self.selection) self.bind(\"<Escape>\", self.deleteListbox)",
"global champ_info champ_info =dict() # Add passive passive_name = data['data'][champion]['passive']['name'] passive_description = data['data'][champion]['passive']['description']",
"if __name__ == '__main__': # Taken from https://www.reddit.com/r/leagueoflegends/comments/cumsa6/list_of_league_of_legends_champion_separated_by/ autocompleteList = [\"Aatrox\",\"Ahri\",\"Akali\",\"Alistar\",\"Amumu\",\"Anivia\",\"Annie\",\"Aphelios\",\"Ashe\",\"Aurelion Sol\",\"Azir\",\\ \"Bard\",\"Blitzcrank\",\"Brand\",\"Braum\",\"Caitlyn\",\"Camille\",\"Cassiopeia\",\"Cho'Gath\",\"Corki\",\"Darius\",\"Diana\",\"Dr.",
"def deleteListbox(self, event=None): if self.listboxUp: self.listbox.destroy() self.listboxUp = False def select(self, event=None): if",
"(): index = '0' else: index = self.listbox.curselection()[0] self.listbox.selection_clear(first=index) index = str(int(index) -",
"= get_PQWER(champion) Passive_text.config(text=champ_info['passive']) Q_text.config(text=champ_info['Q']) W_text.config(text=champ_info['W']) E_text.config(text=champ_info['E']) R_text.config(text=champ_info['R']) # Class adopted from samuelkazeem/tkinter-autocomplete-listbox.py class",
"json files def get_PQWER(champion): \"\"\" Consumes a champion name in string form and",
"if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del kwargs['returnFunction'] else: def selectedValue(value): print(value)",
"P = tk.StringVar() # tk.Button(topLevel, text='Python').grid(column=0) # tk.Button(topLevel, text='Tkinter').grid(column=0) # tk.Button(topLevel, text='Regular Expressions').grid(column=0)",
"matches # Custom return function if 'returnFunction' in kwargs: self.returnFunction = kwargs['returnFunction'] del"
] |
[
"s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result if",
"# intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals = [[2,5]] #",
"\"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为",
"input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s =",
"range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window] = 1 # print(window) for",
"def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min",
"= {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for i in range(10): window",
"strDict[window] =1 # print(strDict) return result if __name__ == '__main__': solu = Solution()",
"if __name__ == '__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List",
"intervals = [[2,5]] # newInterval = [5,7] # input_List = 1 # numerator",
"内存90% \"\"\" N = len(s) if N <= 10: return [] result =",
"= [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals = [[2,5]] # newInterval =",
"window &= 1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window] += 1 if",
"\"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result =",
"print(window) for i in range(10,N): # print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]]",
"# -*- coding: utf-8 -*- \"\"\" Created on Fri Oct 8 00:05:44 2021",
"class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试:",
"Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高",
"改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N <= 10: return []",
"= len(s) if N <= 10: return [] result = [] ATCGdict =",
"<= 10: return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0)",
"= \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17]",
"ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N =",
"return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict =",
"s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点",
"= \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals =",
"3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11;",
"# strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str",
"solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s",
"= [2,17] # intervals = [[2,5]] # newInterval = [5,7] # input_List =",
"[[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] #",
"in range(10,N): # print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window &= 1048575",
"intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals = [[2,5]] # newInterval",
"strDict = {} for i in range(10): window <<= 2 window |= ATCGdict[s[i]]",
"1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果:",
"= {} for i in range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window]",
"|= ATCGdict[s[i]] strDict[window] = 1 # print(window) for i in range(10,N): # print(i,'1',bin(window))",
"N = len(s) if N <= 10: return [] result = [] ATCGdict",
"# s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval",
"# print(window) for i in range(10,N): # print(i,'1',bin(window)) window <<= 2 window |=",
"2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N <= 10:",
"&= 1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window] += 1 if s[i-9:i+1]",
"Created on Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\" class Solution: def",
"\"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result = '",
"4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2",
"result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for",
"# print(i,'2',bin(window)) if window in strDict: strDict[window] += 1 if s[i-9:i+1] not in",
"numerator = -50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result",
"\"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result = ' +",
"result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result if __name__ == '__main__':",
"if N <= 10: return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window",
"# newInterval = [2,17] # intervals = [[2,5]] # newInterval = [5,7] #",
"== '__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]",
"# intervals = [[2,5]] # newInterval = [5,7] # input_List = 1 #",
"coding: utf-8 -*- \"\"\" Created on Fri Oct 8 00:05:44 2021 @author: qizhe",
"window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window]",
"= [5,7] # input_List = 1 # numerator = -50 # strs =",
"{} for i in range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window] =",
"return result if __name__ == '__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]",
"=1 # print(strDict) return result if __name__ == '__main__': solu = Solution() #",
"2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10",
"in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result if __name__ ==",
"print(i,'2',bin(window)) if window in strDict: strDict[window] += 1 if s[i-9:i+1] not in result:",
"result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result if __name__ == '__main__': solu",
"str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1",
"strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str =",
"[\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result",
"1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window] += 1 if s[i-9:i+1] not",
"1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return",
"window in strDict: strDict[window] += 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else:",
"读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00",
"2 window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window in strDict:",
"2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N",
"= 1 # print(window) for i in range(10,N): # print(i,'1',bin(window)) window <<= 2",
"# print(strDict) return result if __name__ == '__main__': solu = Solution() # input_List",
"# numerator = -50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"]",
"N <= 10: return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window =",
"2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找",
"else: strDict[window] =1 # print(strDict) return result if __name__ == '__main__': solu =",
"# newInterval = [5,7] # input_List = 1 # numerator = -50 #",
"# input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals",
"-*- \"\"\" Created on Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\" class",
"input_List = 1 # numerator = -50 # strs = [\"eat\", \"tea\", \"tan\",",
"10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N",
"Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s:",
"in range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window] = 1 # print(window)",
"result if __name__ == '__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] #",
"for i in range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window] = 1",
"1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01",
"# print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window))",
"i in range(10,N): # print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window &=",
"print(strDict) return result if __name__ == '__main__': solu = Solution() # input_List =",
"00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s)",
"2 window |= ATCGdict[s[i]] strDict[window] = 1 # print(window) for i in range(10,N):",
"11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N <=",
"= 1 # numerator = -50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\",",
"利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N <= 10: return",
"newInterval = [5,7] # input_List = 1 # numerator = -50 # strs",
"window |= ATCGdict[s[i]] strDict[window] = 1 # print(window) for i in range(10,N): #",
"= Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s =",
"01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\" N = len(s) if",
"ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window] += 1",
"strDict[window] += 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 #",
"on Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self,",
"strDict[window] = 1 # print(window) for i in range(10,N): # print(i,'1',bin(window)) window <<=",
"range(10,N): # print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window &= 1048575 #",
"= [[2,5]] # newInterval = [5,7] # input_List = 1 # numerator =",
"\"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result = ' + str(result)",
"for i in range(10,N): # print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window",
"'__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] #",
"\"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = ' result = ' + str(result) print(output_Str)",
"<<= 2 window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window in",
"# input_List = 1 # numerator = -50 # strs = [\"eat\", \"tea\",",
"1 # numerator = -50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\",",
"+= 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict)",
"window <<= 2 window |= ATCGdict[s[i]] strDict[window] = 1 # print(window) for i",
"[5,7] # input_List = 1 # numerator = -50 # strs = [\"eat\",",
"utf-8 -*- \"\"\" Created on Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\"",
"00:05:44 2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题:",
"[[2,5]] # newInterval = [5,7] # input_List = 1 # numerator = -50",
"= [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]]",
"# input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s",
"= [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for i",
"\"\"\" Created on Fri Oct 8 00:05:44 2021 @author: qizhe \"\"\" class Solution:",
"|= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window in strDict: strDict[window] +=",
"= -50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result =",
"8 00:05:44 2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\"",
"window <<= 2 window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if window",
"if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result",
"not in result: result.append(s[i-9:i+1]) else: strDict[window] =1 # print(strDict) return result if __name__",
"if window in strDict: strDict[window] += 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1])",
"测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口",
"= [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\"",
"[[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" #",
"ATCGdict[s[i]] strDict[window] = 1 # print(window) for i in range(10,N): # print(i,'1',bin(window)) window",
"s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval =",
"Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"",
"i in range(10): window <<= 2 window |= ATCGdict[s[i]] strDict[window] = 1 #",
"len(s) if N <= 10: return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11}",
"window = int(0) strDict = {} for i in range(10): window <<= 2",
"= int(0) strDict = {} for i in range(10): window <<= 2 window",
"= [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s) output_Str = '",
"[] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for i in",
"10: return [] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict",
"print(i,'1',bin(window)) window <<= 2 window |= ATCGdict[s[i]] window &= 1048575 # print(i,'2',bin(window)) if",
"\"\"\" N = len(s) if N <= 10: return [] result = []",
"input_List = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] # s = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals =",
"\"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时",
"1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90% \"\"\"",
"1、测试通过,用时81% 内存90% \"\"\" N = len(s) if N <= 10: return [] result",
"int(0) strDict = {} for i in range(10): window <<= 2 window |=",
"in strDict: strDict[window] += 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window]",
"[[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals = [[2,5]] # newInterval = [5,7]",
"[] result = [] ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {}",
"strDict: strDict[window] += 1 if s[i-9:i+1] not in result: result.append(s[i-9:i+1]) else: strDict[window] =1",
"\"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals = [[2,5]]",
"<<= 2 window |= ATCGdict[s[i]] strDict[window] = 1 # print(window) for i in",
"答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81% 内存90%",
"-*- coding: utf-8 -*- \"\"\" Created on Fri Oct 8 00:05:44 2021 @author:",
"s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] # intervals",
"2、用时10min 答案: 1、答案利用了ATCG进行了位运算的优化,本质上是利用滑动窗口每次只改变1点点 2、这里的做法:1 ATCG映射为 00 01 10 11; 2 利用滑动窗口 改后效果: 1、测试通过,用时81%",
"__name__ == '__main__': solu = Solution() # input_List = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] # input_List =",
"newInterval = [2,17] # intervals = [[2,5]] # newInterval = [5,7] # input_List",
"findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5 4、感觉是一个长度固定为10的滑动窗口,然后做一个哈希表来计数,不确定是否会超时 测试: 1、错误一次,通过,但效率不是很高 2、用时10min 答案:",
"{'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for i in range(10): window <<=",
"ATCGdict = {'A':0b00,'T':0b01,'C':0b10,'G':0b11} window = int(0) strDict = {} for i in range(10):",
"\"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\" s = \"AAAAAAAAAAAAA\" # intervals = [[1,1],[3,5],[6,7],[8,10],[12,16]] # newInterval = [2,17] #",
"-50 # strs = [\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"] result = solu.findRepeatedDnaSequences(s)",
"1 # print(window) for i in range(10,N): # print(i,'1',bin(window)) window <<= 2 window",
"<reponame>qizhenkang/myLeetCode # -*- coding: utf-8 -*- \"\"\" Created on Fri Oct 8 00:05:44",
"@author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法",
"Oct 8 00:05:44 2021 @author: qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str):",
"qizhe \"\"\" class Solution: def findRepeatedDnaSequences(self, s: str): \"\"\" 读题: 1、感觉像是,在找一个重复字符串,同时字符串长度为10,不是找目标,而是没有目标地找 2、心理上感觉比较麻烦,没有想到好办法 3、长度固定为10,字符只有ATCG四种,字符串最长达到1e5",
"[2,17] # intervals = [[2,5]] # newInterval = [5,7] # input_List = 1"
] |
[
"geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def",
"-*- import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures",
"pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import hierachy",
"-*- coding: utf-8 -*- import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import",
"AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune =",
"import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune",
"italy, regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form",
"AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country': italy.pk}, instance=instance) form.full_clean() assert form.is_valid()",
"@pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance",
"= hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type':",
".fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form",
"regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form =",
"comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio',",
"provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name':",
"instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country': italy.pk}, instance=instance) form.full_clean()",
"# -*- coding: utf-8 -*- import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models",
"utf-8 -*- import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from",
"administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country': italy.pk}, instance=instance)",
"import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form =",
"= AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country': italy.pk}, instance=instance) form.full_clean() assert",
"from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db",
"hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk,",
"import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import",
"from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy",
"= administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country': italy.pk},",
"def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance =",
"from geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione,",
"Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea() form = Form({'name': 'Lazio', 'type': regione.pk, 'country':",
"hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy)",
"coding: utf-8 -*- import pytest from geo.forms import administrativeareaform_factory_for_country from geo.models import AdministrativeArea",
"import administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy):",
"geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy, regione, provincia,",
"test_administrativeareaform_factory(hierachy): italy, regione, provincia, comune = hierachy Form = administrativeareaform_factory_for_country(italy) instance = AdministrativeArea()",
"<reponame>saxix/django-geo<filename>tests/test_forms.py # -*- coding: utf-8 -*- import pytest from geo.forms import administrativeareaform_factory_for_country from",
"administrativeareaform_factory_for_country from geo.models import AdministrativeArea from .fixtures import hierachy @pytest.mark.django_db def test_administrativeareaform_factory(hierachy): italy,"
] |
[
"ObjectID: 1000002 # ParentID: 10308 # Character field ID when accessed: 4000032 #",
"Character field ID when accessed: 4000032 # Object Position X: 2522 # Object",
"# ObjectID: 1000002 # ParentID: 10308 # Character field ID when accessed: 4000032",
"ParentID: 10308 # Character field ID when accessed: 4000032 # Object Position X:",
"# ParentID: 10308 # Character field ID when accessed: 4000032 # Object Position",
"# Character field ID when accessed: 4000032 # Object Position X: 2522 #",
"when accessed: 4000032 # Object Position X: 2522 # Object Position Y: -22",
"1000002 # ParentID: 10308 # Character field ID when accessed: 4000032 # Object",
"field ID when accessed: 4000032 # Object Position X: 2522 # Object Position",
"10308 # Character field ID when accessed: 4000032 # Object Position X: 2522",
"ID when accessed: 4000032 # Object Position X: 2522 # Object Position Y:"
] |
[
"import AuthException def token_auth(fn): def wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\",",
"AuthException def token_auth(fn): def wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\", None)",
"demo.exceptions import AuthException def token_auth(fn): def wrapper(*args, **kwargs): from flask import request if",
"wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail",
"**kwargs): from flask import request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to",
"from flask import request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get",
"def token_auth(fn): def wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\", None) !=",
"def wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\", None) != \"123\": raise",
"token_auth(fn): def wrapper(*args, **kwargs): from flask import request if request.headers.get(\"token\", None) != \"123\":",
"if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get access\") return fn(*args, **kwargs)",
"from demo.exceptions import AuthException def token_auth(fn): def wrapper(*args, **kwargs): from flask import request",
"request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get access\") return fn(*args, **kwargs) return",
"flask import request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get access\")",
"request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get access\") return fn(*args,",
"import request if request.headers.get(\"token\", None) != \"123\": raise AuthException(\"Fail to get access\") return",
"None) != \"123\": raise AuthException(\"Fail to get access\") return fn(*args, **kwargs) return wrapper"
] |
[
"adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options):",
"@options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path =",
"@options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path =",
"options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset')",
"foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector)",
"with preprocessors. Saves the labels predicted by the defended model, using the genuine",
"approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model",
"= options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader,",
"adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor",
"adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset,",
"genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation",
"= training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path)",
"click import torch from counter_attack import defenses, rejectors, training, utils from counter_attack.cli import",
"the dataset to train a substitute model for models with preprocessors. Saves the",
"training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset",
"approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options",
"= options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset')",
"adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset,",
"labels predicted by the defended model, using the genuine dataset + an adversarial",
"= options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine",
"\"\"\" Generates the dataset to train a substitute model for models with preprocessors.",
"= options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset =",
"from counter_attack import defenses, rejectors, training, utils from counter_attack.cli import definitions, options, parsing",
"approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader =",
"= options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation",
"@options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader",
"def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a substitute model for models",
"train a substitute model for models with preprocessors. Saves the labels predicted by",
"@options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader",
"Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train')",
"options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset =",
"= options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model =",
"@approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates",
"@options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader",
"defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model,",
"options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel(",
"'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset",
"Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options",
"@options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model']",
"genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model')",
"import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options",
"definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options",
"= training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset')",
"a substitute model for models with preprocessors. Saves the labels predicted by the",
"adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset",
"utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options",
"Generates the dataset to train a substitute model for models with preprocessors. Saves",
"approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector')",
"defenses, rejectors, training, utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset():",
"defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset",
"adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options",
"'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to",
"approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model",
"foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model,",
"Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset +",
"= options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model =",
"genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset =",
"= options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model,",
"'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path']",
"= options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset",
"@options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset",
"options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model,",
"@click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor')",
"adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector",
"@options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the",
"@options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a substitute",
"by the defended model, using the genuine dataset + an adversarial dataset. \"\"\"",
"options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options",
"Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train')",
"Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options",
"import pathlib import click import torch from counter_attack import defenses, rejectors, training, utils",
"pathlib import click import torch from counter_attack import defenses, rejectors, training, utils from",
"using the genuine dataset + an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path",
"training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector')",
"training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model')",
"the defended model, using the genuine dataset + an adversarial dataset. \"\"\" adversarial_loader",
"genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation",
"approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader']",
"import click import torch from counter_attack import defenses, rejectors, training, utils from counter_attack.cli",
"options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model,",
"model for models with preprocessors. Saves the labels predicted by the defended model,",
"= options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader,",
"genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset =",
"import defenses, rejectors, training, utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def",
"options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset",
"+ adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options",
"preprocessors. Saves the labels predicted by the defended model, using the genuine dataset",
"@options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a substitute model for",
"options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial",
"Saves the labels predicted by the defended model, using the genuine dataset +",
"dataset + an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model",
"'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset",
"@options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path']",
"options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector']",
"+ an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model =",
"import torch from counter_attack import defenses, rejectors, training, utils from counter_attack.cli import definitions,",
"rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial",
"defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset =",
"<gh_stars>0 import pathlib import click import torch from counter_attack import defenses, rejectors, training,",
"dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader =",
"\"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader']",
"@options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a",
"adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader",
"@options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options):",
"def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def",
"parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options",
"@options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model",
"= options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor)",
"model, using the genuine dataset + an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader']",
"def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader =",
"options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor']",
"approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options):",
"approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a substitute model for models with",
"torch from counter_attack import defenses, rejectors, training, utils from counter_attack.cli import definitions, options,",
"genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model,",
"@options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model =",
"for models with preprocessors. Saves the labels predicted by the defended model, using",
"approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader']",
"'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader =",
"the genuine dataset + an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path =",
"options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation",
"the labels predicted by the defended model, using the genuine dataset + an",
"+ adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def",
"adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options",
"utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader",
"Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset",
"@options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train a substitute model",
"utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options",
"predicted by the defended model, using the genuine dataset + an adversarial dataset.",
"rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader,",
"training, utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor')",
"to train a substitute model for models with preprocessors. Saves the labels predicted",
"Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset +",
"foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader,",
"counter_attack import defenses, rejectors, training, utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset')",
"options['foolbox_model'] genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset",
"an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model']",
"training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset",
"@options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model']",
"= options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] rejector =",
"from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train',",
"rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation",
"= rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model,",
"pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\"",
"custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset')",
"= training.generate_approximation_dataset(custom_foolbox_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, adversarial_loader, 'Adversarial Approximation Dataset')",
"genuine_loader = options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset =",
"substitute model for models with preprocessors. Saves the labels predicted by the defended",
"genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False)",
"models with preprocessors. Saves the labels predicted by the defended model, using the",
"= defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset =",
"= genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options",
"@options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path",
"= training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path)",
"@approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def",
"= genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options",
"approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options",
"approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model = options['custom_foolbox_model'] genuine_loader = options['loader'] genuine_approximation_dataset = training.generate_approximation_dataset(custom_foolbox_model, genuine_loader,",
"options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset =",
"@options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model =",
"rejectors, training, utils from counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass",
"= options['foolbox_model'] genuine_loader = options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset",
"@options.standard_model_options @options.pretrained_model_options @options.preprocessor_options @options.adversarial_dataset_options @options.approximation_dataset_options('preprocessor') def approximation_dataset_preprocessor(options): \"\"\" Generates the dataset to train",
"preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine Approximation Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial",
"preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine",
"= options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader = options['loader'] preprocessor =",
"options['loader'] preprocessor = options['preprocessor'] defended_model = defenses.PreprocessorDefenseModel( foolbox_model, preprocessor) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader,",
"adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options",
"'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train',",
"def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] foolbox_model = options['foolbox_model'] genuine_loader =",
"@options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path'] custom_foolbox_model",
"Dataset') adversarial_approximation_dataset = training.generate_approximation_dataset(defended_model, adversarial_loader, 'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset",
"genuine dataset + an adversarial dataset. \"\"\" adversarial_loader = options['adversarial_loader'] approximation_dataset_path = options['approximation_dataset_path']",
"genuine_loader = options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model,",
"@options.standard_model_options @options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader']",
"counter_attack.cli import definitions, options, parsing @click.group(name='approximation-dataset') def approximation_dataset(): pass @approximation_dataset.command(name='preprocessor') @options.global_options @options.dataset_options('train', 'train')",
"defended model, using the genuine dataset + an adversarial dataset. \"\"\" adversarial_loader =",
"@options.pretrained_model_options @options.distance_options @options.counter_attack_options(False) @options.detector_options @options.rejector_options @options.adversarial_dataset_options @options.approximation_dataset_options('rejector') def approximation_dataset_rejector(options): adversarial_loader = options['adversarial_loader'] approximation_dataset_path",
"dataset to train a substitute model for models with preprocessors. Saves the labels",
"@approximation_dataset.command(name='model') @options.global_options @options.dataset_options('train', 'train') @options.standard_model_options @options.custom_model_options @options.adversarial_dataset_options @options.approximation_dataset_options('model') def approximation_dataset_model(options): adversarial_loader = options['adversarial_loader']",
"'Adversarial Approximation Dataset') approximation_dataset = genuine_approximation_dataset + adversarial_approximation_dataset utils.save_zip(approximation_dataset, approximation_dataset_path) @approximation_dataset.command(name='rejector') @options.global_options @options.dataset_options('train',",
"options['loader'] rejector = options['rejector'] defended_model = rejectors.RejectorModel(foolbox_model, rejector) genuine_approximation_dataset = training.generate_approximation_dataset(defended_model, genuine_loader, 'Genuine"
] |
[
"0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor: # need conditional",
"conditional in case the tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return",
"float, name: str) -> tf.Tensor: # need conditional in case the tensor is",
"tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda: value,",
"# need conditional in case the tensor is empty to avoid nans with",
"empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda: value, false_fn=lambda: tf.reduce_mean(x),",
"name: str) -> tf.Tensor: # need conditional in case the tensor is empty",
"tf.Tensor, value: float, name: str) -> tf.Tensor: # need conditional in case the",
"-> tf.Tensor: # need conditional in case the tensor is empty to avoid",
"import tensorflow as tf def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def",
"tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor: # need",
"the tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda:",
"value: float, name: str) -> tf.Tensor: # need conditional in case the tensor",
"def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float,",
"need conditional in case the tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)):",
"-> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str) ->",
"tensorflow as tf def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x:",
"avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda: value, false_fn=lambda: tf.reduce_mean(x), name=name, )",
"return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor: #",
"def safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor: # need conditional in",
"in case the tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond(",
"tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor:",
"tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name: str)",
"str) -> tf.Tensor: # need conditional in case the tensor is empty to",
"<filename>kite-python/kite_ml/kite/utils/reduce.py<gh_stars>10-100 import tensorflow as tf def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0)",
"is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value: float, name:",
"tf.Tensor: # need conditional in case the tensor is empty to avoid nans",
"is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda: value, false_fn=lambda:",
"case the tensor is empty to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x),",
"tf def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor, value:",
"safe_reduce_mean(x: tf.Tensor, value: float, name: str) -> tf.Tensor: # need conditional in case",
"to avoid nans with tf.name_scope('{}_safe_mean'.format(name)): return tf.cond( is_empty(x), true_fn=lambda: value, false_fn=lambda: tf.reduce_mean(x), name=name,",
"as tf def is_empty(x: tf.Tensor) -> tf.Tensor: return tf.equal(tf.reduce_sum(tf.shape(x)), 0) def safe_reduce_mean(x: tf.Tensor,"
] |
[
"users = data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID'] == user] #Finding",
"invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\")",
"day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users =",
"mpl import matplotlib.pyplot as plt import numpy as np import scipy as sci",
"user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and user not in invalid_users: invalid_users.append(user)",
"data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row:",
"uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded columns\") data = data.drop(columns=[\"UCC\",\"ALLOC\",\"GIFT\",\"PUB_FLAG\",\"QREDATE\",\"QREDATE_\"],axis=1) data.to_csv('clean_data/'+filename,index=False)",
"= user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and user not in invalid_users:",
"for user in users: user_data = data.loc[data['NEWID'] == user] #Finding invalid users by",
"np import scipy as sci import pandas as pd import numbers import csv",
"as np import scipy as sci import pandas as pd import numbers import",
"axis=1) print('Removing invalid users') invalid_users = [] users = data.NEWID.unique() for user in",
"filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda",
"data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and",
"invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID",
"= [] users = data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID'] ==",
"print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month']",
"= data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = [] users =",
"as pd import numbers import csv import sys filepath = sys.argv[1] filename =",
"users: user_data = data.loc[data['NEWID'] == user] #Finding invalid users by determining if their",
"plt import numpy as np import scipy as sci import pandas as pd",
"data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row:",
"their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0:",
"in users: user_data = data.loc[data['NEWID'] == user] #Finding invalid users by determining if",
"0: invalid_users.append(user) data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n'] if",
"user] #Finding invalid users by determining if their QREDATE is invalid invalid =",
"!= user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping",
"data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = [] users = data.NEWID.unique()",
"= data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'),",
"user_data = data.loc[data['NEWID'] == user] #Finding invalid users by determining if their QREDATE",
"print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users",
"import numbers import csv import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath)",
"axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users')",
"as sci import pandas as pd import numbers import csv import sys filepath",
"if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) >",
"= data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'),",
"pd import numbers import csv import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:]",
"== user] #Finding invalid users by determining if their QREDATE is invalid invalid",
"str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid",
"data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding",
"data.loc[data['NEWID'] == user] #Finding invalid users by determining if their QREDATE is invalid",
"import csv import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data =",
"import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import",
"invalid users by determining if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] ==",
"as plt import numpy as np import scipy as sci import pandas as",
"row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = [] users = data.NEWID.unique() for",
"= data.loc[data['NEWID'] == user] #Finding invalid users by determining if their QREDATE is",
"data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1)",
"= user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID !=",
"matplotlib.pyplot as plt import numpy as np import scipy as sci import pandas",
"print('Removing invalid users') invalid_users = [] users = data.NEWID.unique() for user in users:",
"= sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year']",
"str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day",
"data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID'] == user] #Finding invalid users",
"> 0: invalid_users.append(user) data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n']",
"axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\")",
"filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\")",
"matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import scipy",
"UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded columns\") data",
"import scipy as sci import pandas as pd import numbers import csv import",
"pandas as pd import numbers import csv import sys filepath = sys.argv[1] filename",
"data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY'])",
"> 0 and user not in invalid_users: invalid_users.append(user) data = data[data.NEWID != user]",
"year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] =",
"if len(invalid2) > 0 and user not in invalid_users: invalid_users.append(user) data = data[data.NEWID",
"data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1)",
"= pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month",
"column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda",
"user not in invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC to",
"and user not in invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC",
"determining if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid)",
"row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding",
"import numpy as np import scipy as sci import pandas as pd import",
"print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1)",
"as mpl import matplotlib.pyplot as plt import numpy as np import scipy as",
"in invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata",
"users') invalid_users = [] users = data.NEWID.unique() for user in users: user_data =",
"[] users = data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID'] == user]",
"= data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID'] == user] #Finding invalid",
"user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and user not",
"Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded columns\") data = data.drop(columns=[\"UCC\",\"ALLOC\",\"GIFT\",\"PUB_FLAG\",\"QREDATE\",\"QREDATE_\"],axis=1)",
"filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2],",
"= data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] =",
"invalid_users.append(user) data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2)",
"users by determining if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B']",
"is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user) data",
"print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded columns\")",
"column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\") data['month'] = data.apply(lambda",
"invalid_users = [] users = data.NEWID.unique() for user in users: user_data = data.loc[data['NEWID']",
"user in users: user_data = data.loc[data['NEWID'] == user] #Finding invalid users by determining",
"user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID != user]",
"'B'] if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID != user] invalid2 =",
"invalid users') invalid_users = [] users = data.NEWID.unique() for user in users: user_data",
"= data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) > 0",
"print(\"Adding month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day']",
"data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) >",
"data = data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category']",
"to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded columns\") data =",
"= filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row:",
"by determining if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if",
"sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year column\") data['year'] =",
"month column\") data['month'] = data.apply(lambda row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] =",
"import pandas as pd import numbers import csv import sys filepath = sys.argv[1]",
"data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = [] users",
"invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user) data =",
"0 and user not in invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping",
"import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding",
"not in invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC to Category\")",
"!= user] invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and user",
"#Finding invalid users by determining if their QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_']",
"len(invalid2) > 0 and user not in invalid_users: invalid_users.append(user) data = data[data.NEWID !=",
"csv import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath)",
"scipy as sci import pandas as pd import numbers import csv import sys",
"sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data = pd.read_csv(filepath) print(\"Adding year",
"numpy as np import scipy as sci import pandas as pd import numbers",
"numbers import csv import sys filepath = sys.argv[1] filename = filepath[filepath.rfind('/')+1:] print(filepath) data",
"import matplotlib.pyplot as plt import numpy as np import scipy as sci import",
"sci import pandas as pd import numbers import csv import sys filepath =",
"invalid_users: invalid_users.append(user) data = data[data.NEWID != user] print(\"Mapping UCC to Category\") uccdata =",
"'n'] if len(invalid2) > 0 and user not in invalid_users: invalid_users.append(user) data =",
"if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year",
"row: str(row.QREDATE)[-10:-8].lstrip('0'), axis=1) print(\"Adding day column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing",
"len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID != user] invalid2 = user_data.loc[user_data.year ==",
"str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = [] users = data.NEWID.unique() for user",
"invalid2 = user_data.loc[user_data.year == 'n'] if len(invalid2) > 0 and user not in",
"column\") data['day'] = data.apply(lambda row: str(row.QREDATE)[-8:-6].lstrip('0'), axis=1) print('Removing invalid users') invalid_users = []",
"== 'n'] if len(invalid2) > 0 and user not in invalid_users: invalid_users.append(user) data",
"QREDATE is invalid invalid = user_data.loc[user_data['QREDATE_'] == 'B'] if len(invalid) > 0: invalid_users.append(user)",
"user] print(\"Mapping UCC to Category\") uccdata = pd.read_csv(\"categorized_ucc_dictionary.csv\") data['category'] = data['UCC'].map(uccdata.set_index('UCC')['CATEGORY']) print(\"Dropping unneeded",
"pd.read_csv(filepath) print(\"Adding year column\") data['year'] = data.apply(lambda row: str(row.QREDATE)[-6:-2], axis=1) print(\"Adding month column\")",
"== 'B'] if len(invalid) > 0: invalid_users.append(user) data = data[data.NEWID != user] invalid2"
] |
[
"A shapefile w/ LiDAR coverage to be used to make a ground polygon",
"ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj",
"elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for",
"\"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) #",
"spatial extent (can be raster), station point spacing in ft (3ft is default).",
"m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster, creates a least-cost thalweg centerline",
"import create_centerline import create_station_lines from create_station_lines import create_station_lines_function import os from os import",
"'Meter': cell_size = m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size",
"are Feet') else: print('Linear unit name for %s uncertain, please use a PROJECTED",
"size in meters (default is 1m), and ft spatial reference Returns: Raster name",
"lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated",
"of feet. las_tools_bin must be the location of the 'bin' folder installed with",
"* import create_centerline import create_station_lines from create_station_lines import create_station_lines_function import os from os",
"meters (default is 1m), and ft spatial reference Returns: Raster name for use",
".csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\",",
"% i for i in intermediates] # Create a station point shapefile evenly",
"f in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index files for f",
"= MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\",",
"raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint",
"spatialref_shp): \"\"\"This function converts LAZ files to LAS file format as well as",
"filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker += 1 smooth_ras = (dem_dir",
"'Foot_US': print('DEM units are Feet') else: print('Linear unit name for %s uncertain, please",
"of >0.4. This polygon is erased from the lidar footprint to give a",
"= arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4)",
"+ \"\\\\filt_ras.tif\") # Create least cost centerline from 15x filtered raster print(\"Smoothed DEM",
"= [f for f in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index",
"1m Args: Folder containing LAS files, desired cell size in meters (default is",
"function, as well as a defined NAIP imagery location (in .jpg2) and makes",
"spacing, second item described smoothing distance if not spatial_ref.linearUnitName == 'Meter': params =",
"topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" %",
"naip_imagery = [f for f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp",
"\"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str) try:",
"if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM",
"temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr =",
"files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5] ==",
"f[:-4], laspath, f[:-4])) files_in_laspath = [f for f in listdir(laspath) if isfile(join(laspath, f))]",
"string if sample_meth == 'BINNING': method_str = '%s AVERAGE %s' % (sample_meth, void_meth)",
"a polygon of vegeation using a NDVI threshold of >0.4. This polygon is",
"naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\"",
"polygon delineating values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras",
"DEM output @ %s\" % out_dem) # Notify the user which units the",
"for ticker in range(filt_passes + 1): # Delete intermediate filtered rasters file =",
"f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath",
"lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files to LAS file format as",
"w/ LiDAR coverage to be used to make a ground polygon for LAStools",
"= lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: #",
"lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" %",
"to make a ground polygon for LAStools processing\"\"\" files_in_direct = [f for f",
"%s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" %",
"\"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder temp_files =",
"load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files to LAS",
"openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files",
"def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files to LAS file format",
"method_str = \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' %",
"(sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth)",
"ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff files",
".jpg2) and makes a polygon of vegeation using a NDVI threshold of >0.4.",
"be the location of the 'bin' folder installed with LAStools by rapidlasso Returns:",
"= arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground if",
"at defined spacing (1/20th of channel width is a starting point) which are",
"exist and can't be deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline =",
"must be a directory containing nothing but raw LAZ files spatial_ref must be",
"% (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin,",
"laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4]))",
"return print('Linear unit name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM'",
"simplify=FALSE) # Make polygon representing bare ground if aoi_shp != '': ground_poly =",
"nir_ras = Raster(nir_ras) # Calculate ndvi and generate polygon delineating values > ndvi_thresh",
"adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1',",
"and visually inspect. Run again w/ True to return the [station_points, elevation_table]\"\"\" #",
"create_station_lines import create_station_lines_function import os from os import listdir from os.path import isfile,",
"between browse() input and default if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe",
"LAS files for f in files_in_direct: if f[-4:] == \".laz\": # Correct format,",
"'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref,",
"= arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\")",
"Delete extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @",
"naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir +",
"format as well as producing a LiDAR extent polygon. in_folder must be a",
"feet. las_tools_bin must be the location of the 'bin' folder installed with LAStools",
"with LAStools by rapidlasso Returns: A shapefile w/ LiDAR coverage to be used",
"print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size)",
"+ 1): # Delete intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\" %",
"raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\")",
"in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath):",
"elevation_df.to_csv(elevation_table) # Delete extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile",
"'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i for i in intermediates]",
"spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem,",
"# Delete intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\" % ticker) if",
"tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a LAS dataset, and then",
"values of the lidar raster. Args: raster_name, upstream flow polygon, spatial extent (can",
"filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/",
"spatial reference object with units of feet. las_tools_bin must be the location of",
"in params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing",
"arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else:",
"'\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params = [m_spacing, smooth_dist]",
"= dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes",
"ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while",
"import listdir from os.path import isfile, join import xlrd import shutil from openpyxl.workbook",
"# Create variables with relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir =",
"formatted for LAStools temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref",
"arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster,",
"\"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint,",
"for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set",
"for f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files folder temp_files",
"to override, but first adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table",
"ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\",",
"Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts",
"not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference and convert units if",
"try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster",
"else: method_str = \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s'",
"delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \" % str(elevation_table)) print('Done') return elevation_table",
"> 1: add_to_mosaic = [naipdir + \"\\\\\" + f for f in naip_imagery]",
"unnecessary index files for f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath +",
"make a ground polygon for LAStools processing\"\"\" files_in_direct = [f for f in",
"except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed",
"file_functions import * import create_centerline import create_station_lines from create_station_lines import create_station_lines_function import os",
"== 'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath +",
"out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem)",
"'\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1): #",
"pass filters...\" % filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files +",
"from the lidar_footprint() function, as well as a defined NAIP imagery location (in",
"# Add fields to override, but first adjust detrending functions elevation_table = dem_dir",
"output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate",
"values from each station point, and export to a .csv file elevation_table =",
"print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files",
"1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost",
"temp files folder temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) #",
"= [temp_files + '\\\\%s' % i for i in intermediates] # Create a",
"out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" % out_dem)",
"AVERAGE %s' % (sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM 0\"",
"out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units are",
"in_spatial_ref) try: # Extract bands 1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery,",
"arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras",
"a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes,",
"void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods:",
"function takes the Lidar raster, creates a least-cost thalweg centerline from a smoothed",
"laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for f in listdir(laspath) if isfile(join(laspath,",
"\"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly) except",
"extent to the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference #",
"are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units",
"cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i",
"\"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir",
"filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker)",
"function converts LAZ files to LAS file format as well as producing a",
"% os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This",
"smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline",
"first adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table,",
"os.path.dirname(dem) # Initiate temp files folder temp_files = dem_dir + '\\\\temp_files' if not",
"if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size",
"15x to the raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\"",
"temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files",
"# Set processing extent to the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref",
"extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s",
"aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp,",
"folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) >",
"i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files",
"f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery =",
"openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This",
"+= 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least",
"\"\"\"This function converts LAZ files to LAS file format as well as producing",
"\"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref)",
"output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery",
"from os import listdir from os.path import isfile, join import xlrd import shutil",
"detrending \"\"\" # Create variables with relevant folders lasdir = lidardir + '\\\\las_files'",
"= create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points =",
"point, and export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points",
"+ \"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f)",
"+ \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras)",
"default if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\"",
"must be an ArcGIS spatial reference object with units of feet. las_tools_bin must",
"try: shutil.rmtree(file) except: print(\"Could not remove %s \" % file) else: print(\"Path %s",
"['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION'] = loc_np",
"create_station_lines_function import os from os import listdir from os.path import isfile, join import",
"= arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint =",
"intermediate files, some of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp',",
"units are Feet') else: print('Linear unit name for %s uncertain, please use a",
"ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker += 1 smooth_ras",
"'bin' folder installed with LAStools by rapidlasso Returns: A shapefile w/ LiDAR coverage",
"\"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s \"",
"# Notify the user which units the DEM are in if out_spatial_ref.linearUnitName ==",
"os.makedirs(temp_files) # Define input parameters params = [m_spacing, smooth_dist] # First item defines",
"- red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1)",
"station point shapefile evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0])",
"1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly",
"used to define processing settings\"\"\" # Set processing extent to the LiDAR data",
"file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"])",
"inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc -",
"f in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if not",
"(3ft is default). Run first with centerline_verified=False and visually inspect. Run again w/",
"point shapefile evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points",
"coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery,",
"xlrd import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def",
"elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units are Feet')",
"output @ %s\" % out_dem) # Notify the user which units the DEM",
"from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ",
"+ \"\\\\filter_out%s\" % ticker) while ticker < filt_passes: # Apply an iterative low",
"0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker <",
"format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras =",
"== 'Meter': params = [int(i * 3) for i in params] filt_passes =",
"arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate temp files folder temp_files",
"% (sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif'",
"elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION'] =",
"down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:,",
"please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly,",
"lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4],",
"must be the location of the 'bin' folder installed with LAStools by rapidlasso",
"distance if not spatial_ref.linearUnitName == 'Meter': params = [int(i * 3) for i",
"a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method string if",
"1): # Delete intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\" % ticker)",
"== 'Foot_US': print('DEM units are Feet') else: print('Linear unit name for %s uncertain,",
"Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files)",
"# Calculate ndvi and generate polygon delineating values > ndvi_thresh ndvi = lidardir",
"temp files folder formatted for LAStools temp_files = lidardir + '\\\\temp_files' if not",
"Run again w/ True to return the [station_points, elevation_table]\"\"\" # Set up environment",
"an iterative low pass filter 15x to the raster to smooth the topography",
"lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar footprint from the",
"# Set up interpolation method string if sample_meth == 'BINNING': method_str = '%s",
"for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if",
"to define processing settings\"\"\" # Set processing extent to the LiDAR data extent",
"# Initiate temp files folder temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files):",
"for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem",
"'': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files +",
"+ \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj,",
"i in params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...')",
"Delete intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file):",
"elevation values from each station point, and export to a .csv file elevation_table",
"j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \" % str(elevation_table))",
"temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters",
"not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\" +",
"filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker < filt_passes: # Apply an iterative",
"arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr",
"arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @",
"arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @",
"= lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for",
"inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation",
"smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files +",
"os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function",
"shapefile evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points =",
"some of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates",
"band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\")",
"'\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff files out_dem = lidardir +",
"to give a ground_polygon used to define processing settings\"\"\" # Set processing extent",
"'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if upside down max_loc",
"print('LAS units are Feet') else: return print('Linear unit name for %s uncertain, please",
"f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe",
"lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly =",
"and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName",
"in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery = [f for",
"width is a starting point) which are given the values of the lidar",
"create_station_lines from create_station_lines import create_station_lines_function import os from os import listdir from os.path",
"= (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref)",
"= arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red) and",
"location (in .jpg2) and makes a polygon of vegeation using a NDVI threshold",
"= lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery =",
"intermediates] # Create a station point shapefile evenly sampling the thalweg centerline station_lines",
"filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker < filt_passes:",
"= ((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >=",
"temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr,",
"listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index files for f in files_in_laspath:",
"processing settings\"\"\" # Set processing extent to the LiDAR data extent arcpy.env.extent =",
"spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except",
"size of 1m Args: Folder containing LAS files, desired cell size in meters",
"station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but",
"= arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\")",
"arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes",
"naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar footprint from the lidar_footprint()",
"% file) else: print(\"Path %s does not exist and can't be deleted...\") print('Done')",
"* m_cell_size) print('LAS units are Feet') else: return print('Linear unit name for %s",
"arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values from each station point,",
"name for use in detrending \"\"\" # Create variables with relevant folders lasdir",
"sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output",
"import create_station_lines_function import os from os import listdir from os.path import isfile, join",
"os.remove(laspath + \"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" %",
"and makes a polygon of vegeation using a NDVI threshold of >0.4. This",
"user which units the DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units",
"+ \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras",
"defined spacing (1/20th of channel width is a starting point) which are given",
"ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create",
"\"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras =",
"a LiDAR extent polygon. in_folder must be a directory containing nothing but raw",
"\"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground if aoi_shp != '': ground_poly",
"'\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table)",
"try: # Extract bands 1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files",
"elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i in",
"raw LAZ files spatial_ref must be an ArcGIS spatial reference object with units",
"params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM",
"[\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i for i",
"lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh,",
"laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files",
"of vegeation using a NDVI threshold of >0.4. This polygon is erased from",
"object with units of feet. las_tools_bin must be the location of the 'bin'",
"from arcpy import env from arcpy.sa import * import file_functions from file_functions import",
"(nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\")",
"% (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin,",
"units are Feet') else: return print('Linear unit name for %s uncertain, please use",
"\"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some of which will be deleted",
"compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem,",
"< elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i",
"Raster name for use in detrending \"\"\" # Create variables with relevant folders",
"the defined lidar footprint from the lidar_footprint() function, as well as a defined",
"i in intermediates] # Create a station point shapefile evenly sampling the thalweg",
"centerline_verified=False and visually inspect. Run again w/ True to return the [station_points, elevation_table]\"\"\"",
"range(filt_passes + 1): # Delete intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\"",
"# Flip rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value']",
"intermediate filtered rasters file = (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try:",
"elevation_table]\"\"\" # Set up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent =",
"(dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline from 15x",
"NDVI threshold of >0.4. This polygon is erased from the lidar footprint to",
"\"\\\\filt_ras.tif\") # Create least cost centerline from 15x filtered raster print(\"Smoothed DEM made,",
"+ \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras,",
"create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points,",
"'\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff",
"temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION',",
"# Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files):",
"polygon for LAStools processing\"\"\" files_in_direct = [f for f in listdir(lidardir) if isfile(join(lidardir,",
"for f in files_in_direct: if f[-4:] == \".laz\": # Correct format, can alter",
"folder installed with LAStools by rapidlasso Returns: A shapefile w/ LiDAR coverage to",
"polygon is erased from the lidar footprint to give a ground_polygon used to",
"centerline_verified=False): \"\"\"This function takes the Lidar raster, creates a least-cost thalweg centerline from",
"ArcGIS spatial reference object with units of feet. las_tools_bin must be the location",
"method_str = '%s AVERAGE %s' % (sample_meth, void_meth) else: method_str = \"%s %s",
"lidar raster. Args: raster_name, upstream flow polygon, spatial extent (can be raster), station",
"\"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset",
"+ \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw",
"lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar",
"os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted for LAStools temp_files = lidardir",
"in ft (3ft is default). Run first with centerline_verified=False and visually inspect. Run",
"\"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\",",
"the user which units the DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM",
"in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index files for f in",
"print('Methods: %s' % method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir,",
"in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \" % str(elevation_table)) print('Done')",
"arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\")",
"arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker < filt_passes: # Apply",
"channel width is a starting point) which are given the values of the",
"sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM",
"from each station point, and export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points,",
"import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function",
"which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files",
"import file_functions from file_functions import * import create_centerline import create_station_lines from create_station_lines import",
"centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10)",
"# Extract elevation values from each station point, and export to a .csv",
"%s' % (sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM 0\" %",
"files, desired cell size in meters (default is 1m), and ft spatial reference",
"define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar footprint from",
"dem_dir = os.path.dirname(dem) # Initiate temp files folder temp_files = dem_dir + '\\\\temp_files'",
"spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a LAS",
"while ticker < filt_passes: # Apply an iterative low pass filter 15x to",
"vegeation using a NDVI threshold of >0.4. This polygon is erased from the",
"each station point, and export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem,",
"and generate polygon delineating values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras",
"be an ArcGIS spatial reference object with units of feet. las_tools_bin must be",
"else: print(\"Path %s does not exist and can't be deleted...\") print('Done') else: print('Generating",
"COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1,",
"format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and generate polygon",
"is default). Run first with centerline_verified=False and visually inspect. Run again w/ True",
"'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet')",
"f))] # Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if not",
"folder formatted for LAStools temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files)",
"files out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate",
"ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground",
"smooth_dist] # First item defines XS length and spacing, second item described smoothing",
"red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files",
"in meters (default is 1m), and ft spatial reference Returns: Raster name for",
"+ \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline from 15x filtered",
"ft (3ft is default). Run first with centerline_verified=False and visually inspect. Run again",
"print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i",
"lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath,",
"w/ True to return the [station_points, elevation_table]\"\"\" # Set up environment and output",
"i for i in intermediates] # Create a station point shapefile evenly sampling",
"+ '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT',",
"of the 'bin' folder installed with LAStools by rapidlasso Returns: A shapefile w/",
"add_to_mosaic = [naipdir + \"\\\\\" + f for f in naip_imagery] naip_imagery =",
"= arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker < filt_passes: #",
"CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint",
"%s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up",
"aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly",
"# Set up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem",
"and spacing, second item described smoothing distance if not spatial_ref.linearUnitName == 'Meter': params",
"Apply an iterative low pass filter 15x to the raster to smooth the",
"takes the defined lidar footprint from the lidar_footprint() function, as well as a",
"+ '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd,",
"lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground if aoi_shp !=",
"(3.28 * m_cell_size) print('LAS units are Feet') else: return print('Linear unit name for",
"# Create least cost centerline from 15x filtered raster print(\"Smoothed DEM made, least-cost",
"and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery,",
"arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground if aoi_shp",
"a raster with cell size of 1m Args: Folder containing LAS files, desired",
"%s \" % file) else: print(\"Path %s does not exist and can't be",
"'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f,",
"value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages())",
"to LAS files for f in files_in_direct: if f[-4:] == \".laz\": # Correct",
"not remove %s \" % file) else: print(\"Path %s does not exist and",
"= dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params",
"defines XS length and spacing, second item described smoothing distance if not spatial_ref.linearUnitName",
"< filt_passes: # Apply an iterative low pass filter 15x to the raster",
"for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery",
"= arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker +",
"Folder containing LAS files, desired cell size in meters (default is 1m), and",
"are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName ==",
"import * import file_functions from file_functions import * import create_centerline import create_station_lines from",
"use in detrending \"\"\" # Create variables with relevant folders lasdir = lidardir",
"Set up output spatial reference and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference",
"= pd.read_csv(elevation_table) # Flip rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True)",
"\"\\\\filter_out%s\" % ticker) while ticker < filt_passes: # Apply an iterative low pass",
"shutil.rmtree(file) except: print(\"Could not remove %s \" % file) else: print(\"Path %s does",
"arcpy import env from arcpy.sa import * import file_functions from file_functions import *",
"footprint from the lidar_footprint() function, as well as a defined NAIP imagery location",
"nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\")",
"is a starting point) which are given the values of the lidar raster.",
"and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) #",
"spatial reference and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference",
"not exist and can't be deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline",
"temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi",
"naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red)",
"listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath)",
"loc_np = np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION',",
"m_cell_size) print('LAS units are Feet') else: return print('Linear unit name for %s uncertain,",
"+ '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference and",
"containing nothing but raw LAZ files spatial_ref must be an ArcGIS spatial reference",
"os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\" + f for",
"= (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline from",
"= arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages())",
"nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras)",
"are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else: print('Linear unit",
"las_tools_bin must be the location of the 'bin' folder installed with LAStools by",
"= arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values from each station",
"and ft spatial reference Returns: Raster name for use in detrending \"\"\" #",
"length and spacing, second item described smoothing distance if not spatial_ref.linearUnitName == 'Meter':",
"'Meter': params = [int(i * 3) for i in params] filt_passes = int(filt_passes)",
"= lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder temp_files = lidardir +",
"out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the",
"+ '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1):",
"params = [int(i * 3) for i in params] filt_passes = int(filt_passes) if",
"= arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add",
"SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False):",
"files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \"",
"files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery)",
"= arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras",
"the lidar_footprint() function, as well as a defined NAIP imagery location (in .jpg2)",
"= arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon",
"processed LAS files to a LAS dataset, and then to a raster with",
"= lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic",
"in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units are Feet') else:",
"% (sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth,",
"sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline],",
"import arcpy from arcpy import env from arcpy.sa import * import file_functions from",
"centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract",
"+ '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted for",
"which units the DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are",
"join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but first adjust detrending functions",
"least cost centerline from 15x filtered raster print(\"Smoothed DEM made, least-cost centerline being",
"from the lidar footprint to give a ground_polygon used to define processing settings\"\"\"",
"of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates =",
"-o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\"",
"\"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw =",
"Lidar raster, creates a least-cost thalweg centerline from a smoothed raster. Station points",
"return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes",
"NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem =",
"red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\",",
"again w/ True to return the [station_points, elevation_table]\"\"\" # Set up environment and",
"units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter':",
"(temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove",
"+ \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing",
"SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method string if sample_meth == 'BINNING':",
"= [f for f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files",
"== 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units are Feet') else: return",
"file) else: print(\"Path %s does not exist and can't be deleted...\") print('Done') else:",
"can alter between browse() input and default if lasbin[-1] != 'n': lasbin =",
"arcpy.sa import * import file_functions from file_functions import * import create_centerline import create_station_lines",
"a directory containing nothing but raw LAZ files spatial_ref must be an ArcGIS",
"nothing but raw LAZ files spatial_ref must be an ArcGIS spatial reference object",
"= arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" %",
"file = (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could",
"centerline at defined spacing (1/20th of channel width is a starting point) which",
"a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table,",
"except: print(\"Could not remove %s \" % file) else: print(\"Path %s does not",
"This polygon is erased from the lidar footprint to give a ground_polygon used",
"the [station_points, elevation_table]\"\"\" # Set up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference",
"out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder temp_files = lidardir",
"= arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir +",
"%s\" % out_dem) # Notify the user which units the DEM are in",
"(can be raster), station point spacing in ft (3ft is default). Run first",
"arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS files for f in files_in_direct:",
">0.4. This polygon is erased from the lidar footprint to give a ground_polygon",
"# Extract bands 1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files +",
"station point spacing in ft (3ft is default). Run first with centerline_verified=False and",
"bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp,",
"1: add_to_mosaic = [naipdir + \"\\\\\" + f for f in naip_imagery] naip_imagery",
"rapidlasso Returns: A shapefile w/ LiDAR coverage to be used to make a",
"of intermediate files, some of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp',",
"# Define location of intermediate files, some of which will be deleted intermediates",
"ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras +",
"data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS",
"dem dem_dir = os.path.dirname(dem) # Initiate temp files folder temp_files = dem_dir +",
"veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly =",
"defined NAIP imagery location (in .jpg2) and makes a polygon of vegeation using",
"with cell size of 1m Args: Folder containing LAS files, desired cell size",
"lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder",
"\"\"\"This function takes the defined lidar footprint from the lidar_footprint() function, as well",
"lidardir, spatialref_shp): \"\"\"This function converts LAZ files to LAS file format as well",
"Set processing extent to the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref =",
"m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 *",
"'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units are Feet') else: return print('Linear",
"if isfile(join(laspath, f))] # Delete unnecessary index files for f in files_in_laspath: if",
"create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1): # Delete",
"1m), and ft spatial reference Returns: Raster name for use in detrending \"\"\"",
"from os.path import isfile, join import xlrd import shutil from openpyxl.workbook import Workbook",
"used to make a ground polygon for LAStools processing\"\"\" files_in_direct = [f for",
"if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass",
"LAStools by rapidlasso Returns: A shapefile w/ LiDAR coverage to be used to",
"arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery = [f for f in",
"name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) #",
"XS length and spacing, second item described smoothing distance if not spatial_ref.linearUnitName ==",
"generated along the centerline at defined spacing (1/20th of channel width is a",
"%s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" %",
"low pass filter 15x to the raster to smooth the topography filter_out =",
"print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\" % filt_passes)",
"files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set",
"lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref)",
"create_centerline import create_station_lines from create_station_lines import create_station_lines_function import os from os import listdir",
"lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red) and 4 (NIR)",
"upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list =",
"(ticker + 1)) ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir +",
"calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker",
"= [f for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir +",
"f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath,",
"= np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True)",
"\"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files +",
"processing\"\"\" files_in_direct = [f for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath =",
"int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low",
"not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\"",
"join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but first adjust detrending functions elevation_table",
"-> DEM output @ %s\" % out_dem) # Notify the user which units",
"%s' % method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las,",
"cell size in meters (default is 1m), and ft spatial reference Returns: Raster",
"the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\"",
"PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist,",
"= elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION']",
"COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method string if sample_meth ==",
"print('Linear unit name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' %",
"defined lidar footprint from the lidar_footprint() function, as well as a defined NAIP",
"= lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial",
"% method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref,",
"= arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref)",
"for i in intermediates] # Create a station point shapefile evenly sampling the",
"+ '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params = [m_spacing,",
"LAStools processing\"\"\" files_in_direct = [f for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath",
"= lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff files out_dem",
"LAS files, desired cell size in meters (default is 1m), and ft spatial",
"+ \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir +",
"use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem, flow_poly, aoi_shp,",
"else: print('Generating thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location",
"3) for i in params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth",
"print('DEM units are Feet') else: print('Linear unit name for %s uncertain, please use",
"Feet') else: print('Linear unit name for %s uncertain, please use a PROJECTED COORDINATE",
"isfile(join(laspath, f))] # Delete unnecessary index files for f in files_in_laspath: if f[-4:]",
"given the values of the lidar raster. Args: raster_name, upstream flow polygon, spatial",
"import * import create_centerline import create_station_lines from create_station_lines import create_station_lines_function import os from",
"sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a LAS dataset, and",
"%s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def",
"isfile, join import xlrd import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import",
"values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras)",
"import isfile, join import xlrd import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel",
"not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS",
"== 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\",",
"arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError:",
"spatial_ref.linearUnitName == 'Meter': params = [int(i * 3) for i in params] filt_passes",
"4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files",
"% f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1,",
"cell_size = m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size =",
"in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files folder temp_files = lidardir",
"input and default if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s",
"lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin,",
"lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in",
"centerline from a smoothed raster. Station points are generated along the centerline at",
"arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir,",
"folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate temp",
"a least-cost thalweg centerline from a smoothed raster. Station points are generated along",
"up output spatial reference and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref",
"the raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker),",
"f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset)",
"elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc",
"loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j in intermediates[2:]: delete_gis_files(j)",
"input parameters params = [m_spacing, smooth_dist] # First item defines XS length and",
"and can't be deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline = dem_dir",
"%s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" %",
"if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5] == 'j':",
"-i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s",
"ticker < filt_passes: # Apply an iterative low pass filter 15x to the",
"if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName",
"using a NDVI threshold of >0.4. This polygon is erased from the lidar",
"tri_meth) print('Methods: %s' % method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset =",
"LAS file format as well as producing a LiDAR extent polygon. in_folder must",
"LAS dataset, and then to a raster with cell size of 1m Args:",
"MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem = temp_files",
"# Initiate temp files folder formatted for LAStools temp_files = lidardir + '\\\\temp_files'",
"% os.path.basename(in_spatial_ref)) # Set up interpolation method string if sample_meth == 'BINNING': method_str",
"veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir +",
"max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list()",
"please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method",
"environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem)",
"print('Generating thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of",
"\"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker +=",
"f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files folder temp_files =",
"browse() input and default if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i",
"# Delete extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv)",
"files_in_direct = [f for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir",
"return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined",
"!= 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir,",
".lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd'",
"+ \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr,",
"f in files_in_direct: if f[-4:] == \".laz\": # Correct format, can alter between",
"Make polygon representing bare ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly,",
"Set up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir",
"files for f in files_in_direct: if f[-4:] == \".laz\": # Correct format, can",
"\"\"\" # Create variables with relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir",
"for generated .lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir",
"\"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline from 15x filtered raster",
"no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\"",
"DEM w/ %sx low pass filters...\" % filt_passes) ticker = 0 filter_out =",
"will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files +",
"to be used to make a ground polygon for LAStools processing\"\"\" files_in_direct =",
"station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values from each",
"loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i) for i in loc_list])",
"print('Done') else: print('Generating thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define",
"be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s'",
"listdir from os.path import isfile, join import xlrd import shutil from openpyxl.workbook import",
"in folder naip_imagery = [f for f in listdir(naipdir) if isfile(join(naipdir, f))] #",
"# First item defines XS length and spacing, second item described smoothing distance",
"(lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir,",
"* import file_functions from file_functions import * import create_centerline import create_station_lines from create_station_lines",
"Set up interpolation method string if sample_meth == 'BINNING': method_str = '%s AVERAGE",
"least-cost thalweg centerline from a smoothed raster. Station points are generated along the",
"= m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28",
"+ \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly,",
"files_in_direct: if f[-4:] == \".laz\": # Correct format, can alter between browse() input",
"Returns: Raster name for use in detrending \"\"\" # Create variables with relevant",
"% (ticker + 1)) ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir",
"0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem = temp_files +",
"ndvi and generate polygon delineating values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\"",
"in_folder must be a directory containing nothing but raw LAZ files spatial_ref must",
"cell size of 1m Args: Folder containing LAS files, desired cell size in",
"raster), station point spacing in ft (3ft is default). Run first with centerline_verified=False",
"red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and generate polygon delineating",
"name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return",
"files for f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" %",
"if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir",
"\"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras",
"arcpy from arcpy import env from arcpy.sa import * import file_functions from file_functions",
"give a ground_polygon used to define processing settings\"\"\" # Set processing extent to",
"bands 1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0)",
"+ \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly)",
"print(\"Path %s does not exist and can't be deleted...\") print('Done') else: print('Generating thalweg",
"i) for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete",
"if len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\" + f for f",
"profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some",
"\"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker += 1 smooth_ras =",
"\"\"\"This function takes the Lidar raster, creates a least-cost thalweg centerline from a",
"elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'],",
"ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar footprint from the lidar_footprint() function,",
"for use in detrending \"\"\" # Create variables with relevant folders lasdir =",
"ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s \" % file)",
"+ \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files",
"to LAS file format as well as producing a LiDAR extent polygon. in_folder",
"shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir,",
"of 1m Args: Folder containing LAS files, desired cell size in meters (default",
"from 15x filtered raster print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot =",
"folder temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input",
"file format as well as producing a LiDAR extent polygon. in_folder must be",
"filter 15x to the raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files +",
"footprint to give a ground_polygon used to define processing settings\"\"\" # Set processing",
"[temp_files + '\\\\%s' % i for i in intermediates] # Create a station",
"point spacing in ft (3ft is default). Run first with centerline_verified=False and visually",
"# Make polygon representing bare ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint,",
"listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files folder temp_files = lidardir +",
"converts LAZ files to LAS file format as well as producing a LiDAR",
"+ f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4)",
"+ \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red) and 4 (NIR) red_lyr",
"DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName",
"necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size =",
"in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5]",
"\"\"\"Converts processed LAS files to a LAS dataset, and then to a raster",
"are Feet') else: return print('Linear unit name for %s uncertain, please use a",
"# Find NAIP imagery in folder naip_imagery = [f for f in listdir(naipdir)",
"LAZ files spatial_ref must be an ArcGIS spatial reference object with units of",
"f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath,",
"Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files",
"temp files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if",
"red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras =",
"not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted for LAStools temp_files =",
"smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster, creates a least-cost thalweg",
"else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI",
"% ticker) while ticker < filt_passes: # Apply an iterative low pass filter",
"\"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir",
"dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes +",
"f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath",
"# Correct format, can alter between browse() input and default if lasbin[-1] !=",
"in range(filt_passes + 1): # Delete intermediate filtered rasters file = (temp_files +",
"flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1): # Delete intermediate filtered rasters",
"for LAStools temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref =",
"arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate",
"'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i for i in intermediates] #",
"-i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f",
"for f in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index files for",
"Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and generate polygon delineating values >",
"LAS files to a LAS dataset, and then to a raster with cell",
"% (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for f in listdir(laspath)",
"= dem dem_dir = os.path.dirname(dem) # Initiate temp files folder temp_files = dem_dir",
"\"\\\\\" + f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref,",
"the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2],",
"polygon. in_folder must be a directory containing nothing but raw LAZ files spatial_ref",
"files to a LAS dataset, and then to a raster with cell size",
"params = [m_spacing, smooth_dist] # First item defines XS length and spacing, second",
"installed with LAStools by rapidlasso Returns: A shapefile w/ LiDAR coverage to be",
"\"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker < filt_passes: # Apply an",
"[f for f in listdir(lidardir) if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files'",
"aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1): # Delete intermediate",
"veg_poly, lidardir + \"\\\\ground_poly.shp\") ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\"",
"Create least cost centerline from 15x filtered raster print(\"Smoothed DEM made, least-cost centerline",
"np.array([int(max_loc - i) for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table)",
"visually inspect. Run again w/ True to return the [station_points, elevation_table]\"\"\" # Set",
"function takes the defined lidar footprint from the lidar_footprint() function, as well as",
"veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon",
"= \"%s %s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str)",
"a ground_polygon used to define processing settings\"\"\" # Set processing extent to the",
"lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery = [f",
"= arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr",
"os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s \" % file) else: print(\"Path",
"(lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath,",
"# Create addresses for generated .lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\"",
"Run first with centerline_verified=False and visually inspect. Run again w/ True to return",
"files to LAS file format as well as producing a LiDAR extent polygon.",
"+ '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df =",
"[f for f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate temp files folder",
"PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method string if sample_meth",
"centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\" %",
"thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\",",
"'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i for i in",
"os.makedirs(laspath) # Initiate temp files folder formatted for LAStools temp_files = lidardir +",
"veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground",
"item defines XS length and spacing, second item described smoothing distance if not",
"laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4]))",
"= arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras =",
"filters...\" % filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\"",
"location of intermediate files, some of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\",",
"os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS files for",
"(1/20th of channel width is a starting point) which are given the values",
"raster with cell size of 1m Args: Folder containing LAS files, desired cell",
"arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units are Meters') elif",
"made, least-cost centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot,",
"intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \" % str(elevation_table)) print('Done') return",
"thalweg centerline from a smoothed raster. Station points are generated along the centerline",
"smoothed raster. Station points are generated along the centerline at defined spacing (1/20th",
"(naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try:",
"# Delete unnecessary index files for f in files_in_laspath: if f[-4:] == 'lasx':",
"format, can alter between browse() input and default if lasbin[-1] != 'n': lasbin",
"w/ %sx low pass filters...\" % filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem,",
"pass filter 15x to the raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files",
"= arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS",
"ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\")",
"env from arcpy.sa import * import file_functions from file_functions import * import create_centerline",
"lidar_foot, flow_poly, smooth_distance=10) for ticker in range(filt_passes + 1): # Delete intermediate filtered",
"temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1:",
"laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4]))",
"print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else:",
"cell_size = (3.28 * m_cell_size) print('LAS units are Feet') else: return print('Linear unit",
"def detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar",
"= arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size)",
"for f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f)",
"smooth_distance=10) for ticker in range(filt_passes + 1): # Delete intermediate filtered rasters file",
"= arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but first",
"void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a LAS dataset, and then to",
"filtered rasters file = (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file)",
"by rapidlasso Returns: A shapefile w/ LiDAR coverage to be used to make",
"# Apply an iterative low pass filter 15x to the raster to smooth",
"+ '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff files out_dem = lidardir",
"reference Returns: Raster name for use in detrending \"\"\" # Create variables with",
"def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the defined lidar footprint",
"print(\"LAS -> DEM output @ %s\" % out_dem) # Notify the user which",
"(lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath,",
"+ \"\\\\\" + f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\",",
"the DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif",
"f[:-4])) files_in_laspath = [f for f in listdir(laspath) if isfile(join(laspath, f))] # Delete",
"as a defined NAIP imagery location (in .jpg2) and makes a polygon of",
"= (3.28 * m_cell_size) print('LAS units are Feet') else: return print('Linear unit name",
"= [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i for",
"lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic =",
"True to return the [station_points, elevation_table]\"\"\" # Set up environment and output folder",
"a LAS dataset, and then to a raster with cell size of 1m",
"to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\",",
"except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" % out_dem) # Notify",
"arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr,",
"to a LAS dataset, and then to a raster with cell size of",
"filt_passes: # Apply an iterative low pass filter 15x to the raster to",
"% (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin,",
"if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to",
"Create a station point shapefile evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline,",
".tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' #",
"lidar footprint from the lidar_footprint() function, as well as a defined NAIP imagery",
"folders lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create",
"xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points",
"cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i",
"ft spatial reference Returns: Raster name for use in detrending \"\"\" # Create",
"reference and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if",
"in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size",
"-o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for f",
"rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']:",
"= arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS files for f in",
"> ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) /",
"item described smoothing distance if not spatial_ref.linearUnitName == 'Meter': params = [int(i *",
"takes the Lidar raster, creates a least-cost thalweg centerline from a smoothed raster.",
"centerline from 15x filtered raster print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot",
"intermediates = [temp_files + '\\\\%s' % i for i in intermediates] # Create",
">= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files +",
"arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0])",
"intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' % i",
"extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder",
"+ \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker",
"f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else:",
"= '%s AVERAGE %s' % (sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING",
"len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\" + f for f in",
"out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly,",
"interpolation method string if sample_meth == 'BINNING': method_str = '%s AVERAGE %s' %",
"print(\"Smoothing DEM w/ %sx low pass filters...\" % filt_passes) ticker = 0 filter_out",
"an ArcGIS spatial reference object with units of feet. las_tools_bin must be the",
"files to LAS files for f in files_in_direct: if f[-4:] == \".laz\": #",
"fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if upside",
"sample_meth == 'BINNING': method_str = '%s AVERAGE %s' % (sample_meth, void_meth) else: method_str",
"is erased from the lidar footprint to give a ground_polygon used to define",
"= CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return",
"in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS files for f",
"NAIP imagery location (in .jpg2) and makes a polygon of vegeation using a",
"'\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str,",
"the centerline at defined spacing (1/20th of channel width is a starting point)",
"raster. Station points are generated along the centerline at defined spacing (1/20th of",
"arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" %",
"centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\")",
"-i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las",
"\"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red) and 4 (NIR) red_lyr =",
"temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr,",
"Find NAIP imagery in folder naip_imagery = [f for f in listdir(naipdir) if",
"lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference",
"os import listdir from os.path import isfile, join import xlrd import shutil from",
"described smoothing distance if not spatial_ref.linearUnitName == 'Meter': params = [int(i * 3)",
"containing LAS files, desired cell size in meters (default is 1m), and ft",
"if sample_meth == 'BINNING': method_str = '%s AVERAGE %s' % (sample_meth, void_meth) else:",
"= arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units are Meters')",
"thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\" % filt_passes) ticker =",
"lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe",
"filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster, creates a least-cost",
"out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override,",
"ndvi_ras = ((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi)",
"import os from os import listdir from os.path import isfile, join import xlrd",
"# Set up output spatial reference and convert units if necessary in_spatial_ref =",
"files_in_laspath = [f for f in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary",
"method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True)",
"keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if upside down max_loc = elevation_df['LOCATION'].max()",
"= lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder",
"threshold of >0.4. This polygon is erased from the lidar footprint to give",
"in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir,",
"naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\",",
"= int(filt_passes) if not centerline_verified: print('Generating smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx",
"Delete unnecessary index files for f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath",
"f[-4:] == \".laz\": # Correct format, can alter between browse() input and default",
"== 'Meter': cell_size = m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US':",
"Returns: A shapefile w/ LiDAR coverage to be used to make a ground",
"lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi)",
"= arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except",
"smoothing distance if not spatial_ref.linearUnitName == 'Meter': params = [int(i * 3) for",
"%sx low pass filters...\" % filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\")",
"detrend_prep(dem, flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster,",
"arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" % out_dem) # Notify the",
"csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if",
"out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else: print('Linear unit name for %s",
"Flip rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] <",
"red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras",
"not spatial_ref.linearUnitName == 'Meter': params = [int(i * 3) for i in params]",
"dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some of which will",
"arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) #",
"%s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o",
"print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function takes the",
"raster_name, upstream flow polygon, spatial extent (can be raster), station point spacing in",
"spatial_ref must be an ArcGIS spatial reference object with units of feet. las_tools_bin",
"output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values from",
"ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw,",
"second item described smoothing distance if not spatial_ref.linearUnitName == 'Meter': params = [int(i",
"delineating values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras -",
"in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US':",
"\"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare",
"elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else: print('Linear unit name for",
"laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4],",
"with relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates'",
"lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' # Create addresses",
"for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra",
"= [naipdir + \"\\\\\" + f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic,",
"in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for",
"os from os import listdir from os.path import isfile, join import xlrd import",
"/ (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files +",
"creates a least-cost thalweg centerline from a smoothed raster. Station points are generated",
"Extract bands 1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\",",
"lasdir + '\\\\09_ground_rm_duplicates' # Create addresses for generated .lasd, .tiff files out_dem =",
"Define location of intermediate files, some of which will be deleted intermediates =",
"print(\"Could not remove %s \" % file) else: print(\"Path %s does not exist",
"band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files +",
"file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows",
"out_dem) # Notify the user which units the DEM are in if out_spatial_ref.linearUnitName",
"os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files to LAS files",
"= Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\")",
"points are generated along the centerline at defined spacing (1/20th of channel width",
"centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some of",
"default). Run first with centerline_verified=False and visually inspect. Run again w/ True to",
"+ 1)) ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\")",
"index files for f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\"",
"NAIP imagery in folder naip_imagery = [f for f in listdir(naipdir) if isfile(join(naipdir,",
"polygon representing bare ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files",
"Convert laz files to LAS files for f in files_in_direct: if f[-4:] ==",
"arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def",
"Correct format, can alter between browse() input and default if lasbin[-1] != 'n':",
"arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras =",
"Args: raster_name, upstream flow polygon, spatial extent (can be raster), station point spacing",
"are generated along the centerline at defined spacing (1/20th of channel width is",
"lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder temp_files = lidardir + '\\\\temp_files'",
"lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir",
"ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts",
"in files_in_direct: if f[-4:] == \".laz\": # Correct format, can alter between browse()",
"= arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points)",
"+ \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files",
"lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted",
"the values of the lidar raster. Args: raster_name, upstream flow polygon, spatial extent",
"-i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las",
"well as a defined NAIP imagery location (in .jpg2) and makes a polygon",
"a NDVI threshold of >0.4. This polygon is erased from the lidar footprint",
"in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to",
"= temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset,",
"= loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j in intermediates[2:]:",
"no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster =",
"detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1',",
"with centerline_verified=False and visually inspect. Run again w/ True to return the [station_points,",
"lidar footprint to give a ground_polygon used to define processing settings\"\"\" # Set",
"* 3) for i in params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating",
"= lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4]))",
"alter between browse() input and default if lasbin[-1] != 'n': lasbin = lasbin[:-1]",
"extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def",
"+ '\\\\las_dataset.lasd' # Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if",
"out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units",
"= lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp files",
"print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras,",
"% out_dem) # Notify the user which units the DEM are in if",
"units of feet. las_tools_bin must be the location of the 'bin' folder installed",
"file_functions from file_functions import * import create_centerline import create_station_lines from create_station_lines import create_station_lines_function",
"for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg elevation profile (.csv) @ %s \" %",
"spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate temp files",
"data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in",
"f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir +",
"f))] # Delete unnecessary index files for f in files_in_laspath: if f[-4:] ==",
"a ground polygon for LAStools processing\"\"\" files_in_direct = [f for f in listdir(lidardir)",
"temp files folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) #",
"'lasx': os.remove(laspath + \"\\\\%s\" % f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\"",
"functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID',",
"\"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make",
"files, some of which will be deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf']",
"+ \"\\\\veg_poly_ndvi.shp\", simplify=FALSE) # Make polygon representing bare ground if aoi_shp != '':",
"as well as producing a LiDAR extent polygon. in_folder must be a directory",
"evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0],",
"join import xlrd import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook,",
"spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1])",
"up interpolation method string if sample_meth == 'BINNING': method_str = '%s AVERAGE %s'",
"return the [station_points, elevation_table]\"\"\" # Set up environment and output folder spatial_ref =",
"+ \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly =",
"Notify the user which units the DEM are in if out_spatial_ref.linearUnitName == 'Meter':",
"shapefile w/ LiDAR coverage to be used to make a ground polygon for",
"if isfile(join(naipdir, f))] # Initiate temp files folder temp_files = lidardir + '\\\\temp_files'",
"the location of the 'bin' folder installed with LAStools by rapidlasso Returns: A",
"flow polygon, spatial extent (can be raster), station point spacing in ft (3ft",
"Add fields to override, but first adjust detrending functions elevation_table = dem_dir +",
"deleted intermediates = [\"thalweg_centerline_XS.shp\", 'thalweg_station_points.shp', 'thalweg_station_points1.shp', 'sp_elevation_table.dbf'] intermediates = [temp_files + '\\\\%s' %",
"ticker in range(filt_passes + 1): # Delete intermediate filtered rasters file = (temp_files",
"as well as a defined NAIP imagery location (in .jpg2) and makes a",
"if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list",
"station_points = arcpy.AddXY_management(station_points) # Extract elevation values from each station point, and export",
"isfile(join(naipdir, f))] # Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if",
"[naipdir + \"\\\\\" + f for f in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir,",
"a defined NAIP imagery location (in .jpg2) and makes a polygon of vegeation",
"station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points =",
"(default is 1m), and ft spatial reference Returns: Raster name for use in",
"% ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s \" %",
"def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to",
"os.makedirs(temp_files) # Set up output spatial reference and convert units if necessary in_spatial_ref",
"and default if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o",
"nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\")",
"f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath,",
"convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName ==",
"fields to override, but first adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv'",
"being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly, smooth_distance=10) for",
"%s does not exist and can't be deleted...\") print('Done') else: print('Generating thalweg elevation",
"[int(i * 3) for i in params] filt_passes = int(filt_passes) if not centerline_verified:",
"isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate",
"flow_poly, aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster, creates",
"as producing a LiDAR extent polygon. in_folder must be a directory containing nothing",
"along the centerline at defined spacing (1/20th of channel width is a starting",
"generated .lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir +",
"lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert",
"in naip_imagery] naip_imagery = arcpy.MosaicToNewRaster_management(add_to_mosaic, output_location=lidardir, raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir",
"f))] laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp",
"to the raster to smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" %",
"temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output",
"imagery in folder naip_imagery = [f for f in listdir(naipdir) if isfile(join(naipdir, f))]",
"arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS",
"elevation_df = pd.read_csv(elevation_table) # Flip rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION',",
"use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation method string",
"% ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1):",
"first with centerline_verified=False and visually inspect. Run again w/ True to return the",
"Raster(nir_ras) # Calculate ndvi and generate polygon delineating values > ndvi_thresh ndvi =",
"unit name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref))",
"LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery",
"arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery",
"of channel width is a starting point) which are given the values of",
"= [int(i * 3) for i in params] filt_passes = int(filt_passes) if not",
"%s NO_THINNING MAXIMUM 0\" % (sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem",
"cost centerline from 15x filtered raster print(\"Smoothed DEM made, least-cost centerline being calculated...\")",
"are given the values of the lidar raster. Args: raster_name, upstream flow polygon,",
"import xlrd import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException",
"'BINNING': method_str = '%s AVERAGE %s' % (sample_meth, void_meth) else: method_str = \"%s",
"elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) #",
"== 'BINNING': method_str = '%s AVERAGE %s' % (sample_meth, void_meth) else: method_str =",
"a station point shapefile evenly sampling the thalweg centerline station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0],",
"arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref = arcpy.Describe(aoi_shp).spatialReference if in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units",
"coverage to be used to make a ground polygon for LAStools processing\"\"\" files_in_direct",
"if f[-4:] == \".laz\": # Correct format, can alter between browse() input and",
"arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1))",
"to the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find",
"%s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for",
"LAStools temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference",
"lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint,",
"ground polygon for LAStools processing\"\"\" files_in_direct = [f for f in listdir(lidardir) if",
"folder naip_imagery = [f for f in listdir(naipdir) if isfile(join(naipdir, f))] # Initiate",
"= os.path.dirname(dem) # Initiate temp files folder temp_files = dem_dir + '\\\\temp_files' if",
"dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params =",
"(NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files +",
"raster, creates a least-cost thalweg centerline from a smoothed raster. Station points are",
"be raster), station point spacing in ft (3ft is default). Run first with",
"directory containing nothing but raw LAZ files spatial_ref must be an ArcGIS spatial",
"'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if upside down max_loc =",
"producing a LiDAR extent polygon. in_folder must be a directory containing nothing but",
"== \".laz\": # Correct format, can alter between browse() input and default if",
"las_dataset = arcpy.CreateLasDataset_management(ground_lasdir, out_las, spatial_reference=in_spatial_ref, compute_stats=True) lidar_raster = arcpy.LasDatasetToRaster_conversion(las_dataset, value_field='ELEVATION', data_type='FLOAT', interpolation_type=method_str, sampling_type='CELLSIZE',",
"%s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth,",
"parameters params = [m_spacing, smooth_dist] # First item defines XS length and spacing,",
"filter_out.save(dem_dir + \"\\\\filt_ras.tif\") # Create least cost centerline from 15x filtered raster print(\"Smoothed",
"1 (red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr",
"-o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\"",
"try: # Convert laz files to LAS files for f in files_in_direct: if",
"+ \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: #",
"uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref)) # Set up interpolation",
"define processing settings\"\"\" # Set processing extent to the LiDAR data extent arcpy.env.extent",
"if not spatial_ref.linearUnitName == 'Meter': params = [int(i * 3) for i in",
"variables with relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir +",
"interpolation_type=method_str, sampling_type='CELLSIZE', sampling_value=cell_size) arcpy.CopyRaster_management(lidar_raster, no_prj_dem) arcpy.ProjectRaster_management(no_prj_dem, out_raster=out_dem, out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS ->",
"os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\" + f",
"bare ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\")",
"os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params = [m_spacing, smooth_dist] # First item",
"extent polygon. in_folder must be a directory containing nothing but raw LAZ files",
"laspath, f[:-4])) files_in_laspath = [f for f in listdir(laspath) if isfile(join(laspath, f))] #",
"= arcpy.Describe(lidar_footprint).spatialReference # Find NAIP imagery in folder naip_imagery = [f for f",
"then to a raster with cell size of 1m Args: Folder containing LAS",
"[m_spacing, smooth_dist] # First item defines XS length and spacing, second item described",
"+ \"\\\\red_ras.lyr\") nir_lyr = arcpy.SaveToLayerFile_management(nir_lyr, temp_files + \"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files +",
"arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras,",
"uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(out_spatial_ref)) return out_dem def detrend_prep(dem,",
"+ '\\\\%s' % i for i in intermediates] # Create a station point",
"temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try:",
"the Lidar raster, creates a least-cost thalweg centerline from a smoothed raster. Station",
"in detrending \"\"\" # Create variables with relevant folders lasdir = lidardir +",
"Create addresses for generated .lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las",
"Station points are generated along the centerline at defined spacing (1/20th of channel",
"remove %s \" % file) else: print(\"Path %s does not exist and can't",
"from create_station_lines import create_station_lines_function import os from os import listdir from os.path import",
"but first adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points,",
"ground_poly = arcpy.DefineProjection_management(ground_poly, in_spatial_ref) print(\"AOI bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError:",
"+ \"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some of which will be",
"to return the [station_points, elevation_table]\"\"\" # Set up environment and output folder spatial_ref",
"which are given the values of the lidar raster. Args: raster_name, upstream flow",
"= dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate files, some of which",
"intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values from each station point, and",
"desired cell size in meters (default is 1m), and ft spatial reference Returns:",
"to a raster with cell size of 1m Args: Folder containing LAS files,",
"# Create a station point shapefile evenly sampling the thalweg centerline station_lines =",
"starting point) which are given the values of the lidar raster. Args: raster_name,",
"dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df",
"in intermediates] # Create a station point shapefile evenly sampling the thalweg centerline",
"from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp):",
"inspect. Run again w/ True to return the [station_points, elevation_table]\"\"\" # Set up",
"'\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference and convert",
"(red) and 4 (NIR) red_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\rd_lyr\", band_index=0) nir_lyr =",
"if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference and convert units",
"from file_functions import * import create_centerline import create_station_lines from create_station_lines import create_station_lines_function import",
"the lidar raster. Args: raster_name, upstream flow polygon, spatial extent (can be raster),",
"\"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract",
"Feet') else: return print('Linear unit name for %s uncertain, please use a PROJECTED",
"least-cost centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp, lidar_foot, flow_poly,",
"= lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras + red_ras))",
"temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly",
"DEM made, least-cost centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp' create_centerline.make_centerline(smooth_ras, aoi_shp,",
"'\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz files",
"if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir + \"\\\\\"",
"not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params = [m_spacing, smooth_dist] # First",
"naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1",
"elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) #",
"representing bare ground if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files +",
"Create variables with relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir",
"import shutil from openpyxl.workbook import Workbook from openpyxl.reader.excel import load_workbook, InvalidFileException def lidar_footptint(lasbin,",
"!= '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files",
"% naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands",
"if aoi_shp != '': ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj =",
"aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a LAS dataset,",
"in_spatial_ref.linearUnitName == 'Meter': cell_size = m_cell_size print('LAS units are Meters') elif in_spatial_ref.linearUnitName ==",
"Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else: print('Linear unit name",
"elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate files,",
"%s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for f in",
"raster_dataset_name_with_extension=\"NAIP_mos.tif\", coordinate_system_for_the_raster=in_spatial_ref, number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery =",
"can't be deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline = dem_dir +",
"addresses for generated .lasd, .tiff files out_dem = lidardir + \"\\\\las_dem.tif\" out_las =",
"elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j in intermediates[2:]: delete_gis_files(j) print(\"Thalweg",
"\"\\\\nir_ras.lyr\") red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files +",
"= Raster(nir_ras) # Calculate ndvi and generate polygon delineating values > ndvi_thresh ndvi",
"+ '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir",
"Args: Folder containing LAS files, desired cell size in meters (default is 1m),",
"arcpy.Erase_analysis(lidar_footprint, veg_poly, temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly",
"Calculate ndvi and generate polygon delineating values > ndvi_thresh ndvi = lidardir +",
"import env from arcpy.sa import * import file_functions from file_functions import * import",
"%s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o",
"smooth thalweg centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\" % filt_passes) ticker",
"filtered raster print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot = dem_dir +",
"print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath =",
"LiDAR extent polygon. in_folder must be a directory containing nothing but raw LAZ",
"[station_points, elevation_table]\"\"\" # Set up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent",
"if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s \" % file) else:",
"units the DEM are in if out_spatial_ref.linearUnitName == 'Meter': print('DEM units are Meters')",
"be used to make a ground polygon for LAStools processing\"\"\" files_in_direct = [f",
"out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation",
"LAZ files to LAS file format as well as producing a LiDAR extent",
"up environment and output folder spatial_ref = arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir =",
"thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" # Define location of intermediate",
"compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError:",
"\".laz\": # Correct format, can alter between browse() input and default if lasbin[-1]",
"is 1m), and ft spatial reference Returns: Raster name for use in detrending",
"raster. Args: raster_name, upstream flow polygon, spatial extent (can be raster), station point",
"# Define input parameters params = [m_spacing, smooth_dist] # First item defines XS",
"= (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not",
"= arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) #",
"InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files to LAS file",
"deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\" #",
"if not os.path.exists(temp_files): os.makedirs(temp_files) # Define input parameters params = [m_spacing, smooth_dist] #",
"pd.read_csv(elevation_table) # Flip rows if upside down max_loc = elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if",
"'\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This",
"ground_polygon used to define processing settings\"\"\" # Set processing extent to the LiDAR",
"\" % file) else: print(\"Path %s does not exist and can't be deleted...\")",
"number_of_bands=4) else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir",
"in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but first adjust detrending",
"relevant folders lasdir = lidardir + '\\\\las_files' ground_lasdir = lasdir + '\\\\09_ground_rm_duplicates' #",
"arcpy.ProjectRaster_management(naip_imagery, lidardir + \"\\\\NAIP_prj.tif\", in_spatial_ref) try: # Extract bands 1 (red) and 4",
"polygon, spatial extent (can be raster), station point spacing in ft (3ft is",
"# Convert laz files to LAS files for f in files_in_direct: if f[-4:]",
"dataset, and then to a raster with cell size of 1m Args: Folder",
"units are Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS",
"settings\"\"\" # Set processing extent to the LiDAR data extent arcpy.env.extent = lidar_footprint",
"laz files to LAS files for f in files_in_direct: if f[-4:] == \".laz\":",
"@ %s\" % out_dem) # Notify the user which units the DEM are",
"- i) for i in loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) #",
"ticker) while ticker < filt_passes: # Apply an iterative low pass filter 15x",
"os.path.exists(temp_files): os.makedirs(temp_files) # Set up output spatial reference and convert units if necessary",
"a smoothed raster. Station points are generated along the centerline at defined spacing",
"files spatial_ref must be an ArcGIS spatial reference object with units of feet.",
"files folder formatted for LAStools temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files):",
"+ \"\\\\filter_out%s\" % (ticker + 1)) ticker += 1 smooth_ras = (dem_dir +",
"Extract elevation values from each station point, and export to a .csv file",
"arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate temp files folder temp_files =",
"be a directory containing nothing but raw LAZ files spatial_ref must be an",
"if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted for LAStools temp_files",
"output spatial reference and convert units if necessary in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference out_spatial_ref =",
"folder temp_files = lidardir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Set up",
"= dem_dir + '\\\\xyz_elevation_table.csv' elevation_table = file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[])",
"f in files_in_laspath: if f[-4:] == 'lasx': os.remove(laspath + \"\\\\%s\" % f) if",
"does not exist and can't be deleted...\") print('Done') else: print('Generating thalweg elevation profile...')",
"aoi_shp, filt_passes, smooth_dist, m_spacing=1, centerline_verified=False): \"\"\"This function takes the Lidar raster, creates a",
"the 'bin' folder installed with LAStools by rapidlasso Returns: A shapefile w/ LiDAR",
"else: print('Linear unit name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM'",
"Initiate temp files folder temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files)",
"rasters file = (temp_files + \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except:",
"a starting point) which are given the values of the lidar raster. Args:",
"spacing (1/20th of channel width is a starting point) which are given the",
"lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f,",
"== 'Meter': print('DEM units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are",
"iterative low pass filter 15x to the raster to smooth the topography filter_out",
"'%s AVERAGE %s' % (sample_meth, void_meth) else: method_str = \"%s %s NO_THINNING MAXIMUM",
"point) which are given the values of the lidar raster. Args: raster_name, upstream",
"and export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points =",
"except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp): \"\"\"This function",
"but raw LAZ files spatial_ref must be an ArcGIS spatial reference object with",
"generate polygon delineating values > ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras =",
"else: return print('Linear unit name for %s uncertain, please use a PROJECTED COORDINATE",
"(lasbin, laspath, f[:-4], laspath, f[:-4])) files_in_laspath = [f for f in listdir(laspath) if",
"from a smoothed raster. Station points are generated along the centerline at defined",
"%s\\\\%s -o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o",
"= [m_spacing, smooth_dist] # First item defines XS length and spacing, second item",
"= file_functions.tableToCSV(input_table=station_points, csv_filepath=elevation_table, fld_to_remove_override=['FID_thal_1', 'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip",
"MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly = arcpy.RasterToPolygon_conversion(veg_ras, lidardir + \"\\\\veg_poly_ndvi.shp\", simplify=FALSE)",
"spacing in ft (3ft is default). Run first with centerline_verified=False and visually inspect.",
"import load_workbook, InvalidFileException def lidar_footptint(lasbin, lidardir, spatialref_shp): \"\"\"This function converts LAZ files to",
"centerline...') print(\"Smoothing DEM w/ %sx low pass filters...\" % filt_passes) ticker = 0",
"aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir +",
"\"\\\\rd_lyr\", band_index=0) nir_lyr = arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files",
"from arcpy.sa import * import file_functions from file_functions import * import create_centerline import",
"aoi_shp): \"\"\"This function takes the defined lidar footprint from the lidar_footprint() function, as",
"(in .jpg2) and makes a polygon of vegeation using a NDVI threshold of",
"extent (can be raster), station point spacing in ft (3ft is default). Run",
"of the lidar raster. Args: raster_name, upstream flow polygon, spatial extent (can be",
"@ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth,",
"LiDAR coverage to be used to make a ground polygon for LAStools processing\"\"\"",
"export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points,",
"os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset = arcpy.CreateLasDataset_management(laspath, lidardir + \"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True)",
"'\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) # Initiate temp files folder formatted for LAStools",
"\"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and generate",
"import create_station_lines from create_station_lines import create_station_lines_function import os from os import listdir from",
"loc_list]) elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j",
"arcpy.MakeRasterLayer_management(naip_imagery, temp_files + \"\\\\nr_lyr\", band_index=4) red_lyr = arcpy.SaveToLayerFile_management(red_lyr, temp_files + \"\\\\red_ras.lyr\") nir_lyr =",
"+ red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras",
"if isfile(join(lidardir, f))] laspath = lidardir + '\\\\las_files' if not os.path.exists(laspath): os.makedirs(laspath) #",
"unit name for %s uncertain, please use a PROJECTED COORDINATE SYSTEM' % os.path.basename(in_spatial_ref))",
"fields=[\"Value\"]) # Add fields to override, but first adjust detrending functions elevation_table =",
"arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3]) station_points = arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields",
"'Id_1', 'InLine_FID', 'ORIG_FID'], keep_fields=[]) elevation_df = pd.read_csv(elevation_table) # Flip rows if upside down",
"-o %s\\\\%s_noprj.las\" % (lasbin, lidardir, f, laspath, f[:-4])) print(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\"",
"imagery location (in .jpg2) and makes a polygon of vegeation using a NDVI",
"polygon of vegeation using a NDVI threshold of >0.4. This polygon is erased",
"lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth, tri_meth, void_meth, m_cell_size=1): \"\"\"Converts processed LAS files to a",
"location of the 'bin' folder installed with LAStools by rapidlasso Returns: A shapefile",
"elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np =",
"arcpy.AddXY_management(station_points) # Extract elevation values from each station point, and export to a",
"1)) ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\") filter_out.save(dem_dir + \"\\\\filt_ras.tif\") #",
"lidar_footprint() function, as well as a defined NAIP imagery location (in .jpg2) and",
"15x filtered raster print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot = dem_dir",
"+ \"\\\\filter_out%s\" % ticker) if os.path.exists(file): try: shutil.rmtree(file) except: print(\"Could not remove %s",
"(sample_meth, tri_meth) print('Methods: %s' % method_str) try: no_prj_dem = temp_files + '\\\\noprj_dem.tif' las_dataset",
"= Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and generate polygon delineating values",
"method string if sample_meth == 'BINNING': method_str = '%s AVERAGE %s' % (sample_meth,",
"override, but first adjust detrending functions elevation_table = dem_dir + '\\\\xyz_elevation_table.csv' elevation_table =",
"'\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) if len(naip_imagery) > 1: add_to_mosaic = [naipdir +",
"+ \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp files folder temp_files",
"station_lines = create_station_lines.create_station_lines_function(centerline, spacing=params[0], xs_length=params[0]) station_points = arcpy.Intersect_analysis([intermediates[0], centerline], out_feature_class=intermediates[2], join_attributes=\"ALL\", output_type=\"POINT\") station_points",
"Define input parameters params = [m_spacing, smooth_dist] # First item defines XS length",
"f[:-4])) cmd(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe",
"% ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker + 1)) ticker += 1",
"ndvi_thresh ndvi = lidardir + \"\\\\NDVI.tif\" ndvi_ras = ((nir_ras - red_ras) / (nir_ras",
"arcpy.JoinField_management(station_points, in_field=\"ORIG_FID\", join_table=elevation_table, join_field=\"SrcID_Feat\", fields=[\"Value\"]) # Add fields to override, but first adjust",
"= arcpy.AddXY_management(station_points) # Extract elevation values from each station point, and export to",
"+ '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) in_spatial_ref = arcpy.Describe(spatialref_shp).spatialReference try: # Convert laz",
"upstream flow polygon, spatial extent (can be raster), station point spacing in ft",
"'\\\\las_dataset.lasd' # Initiate temp files folder temp_files = lidardir + '\\\\temp_files' if not",
"= arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir,",
"and then to a raster with cell size of 1m Args: Folder containing",
"raster print(\"Smoothed DEM made, least-cost centerline being calculated...\") lidar_foot = dem_dir + '\\\\las_footprint.shp'",
"((nir_ras - red_ras) / (nir_ras + red_ras)) ndvi_ras.save(ndvi) veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh,",
"with units of feet. las_tools_bin must be the location of the 'bin' folder",
"files folder temp_files = dem_dir + '\\\\temp_files' if not os.path.exists(temp_files): os.makedirs(temp_files) # Define",
"First item defines XS length and spacing, second item described smoothing distance if",
"for i in params] filt_passes = int(filt_passes) if not centerline_verified: print('Generating smooth thalweg",
"low pass filters...\" % filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files",
"if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np = np.array([int(max_loc - i)",
"\"\\\\filter_out%s\" % (ticker + 1)) ticker += 1 smooth_ras = (dem_dir + \"\\\\filt_ras.tif\")",
"polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp, aoi_shp, sample_meth,",
"out_coor_system=out_spatial_ref) except arcpy.ExecuteError: print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" % out_dem) #",
"[f for f in listdir(laspath) if isfile(join(laspath, f))] # Delete unnecessary index files",
"else: naip_imagery = (naipdir + \"\\\\%s\" % naip_imagery[0]) naip_imagery = arcpy.ProjectRaster_management(naip_imagery, lidardir +",
"+ '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages()) return lidar_footprint def define_ground_polygon(lidar_footprint, lidardir, naipdir, ndvi_thresh, aoi_shp):",
"reference object with units of feet. las_tools_bin must be the location of the",
"makes a polygon of vegeation using a NDVI threshold of >0.4. This polygon",
"veg_ras_raw = Con(arcpy.sa.Raster(ndvi) >= ndvi_thresh, 1) veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\",",
"the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference # Find NAIP",
"temp_files + \"\\\\ground_poly_full.shp\") aoi_prj = arcpy.Project_management(aoi_shp, temp_files + \"\\\\aoi_prj_to_inref.shp\", out_coor_system=in_spatial_ref) ground_poly = arcpy.Clip_analysis(ground_poly,",
"station point, and export to a .csv file elevation_table = arcpy.ExtractValuesToTable_ga(station_points, in_rasters=dem, out_table=intermediates[3])",
"erased from the lidar footprint to give a ground_polygon used to define processing",
"os.path.basename(in_spatial_ref)) # Set up interpolation method string if sample_meth == 'BINNING': method_str =",
"veg_ras_raw.save(temp_files + \"\\\\veg_ras_raw.tif\") veg_ras = MajorityFilter(veg_ras_raw, \"EIGHT\", \"MAJORITY\") veg_ras.save(temp_files + \"\\\\veg_ras.tif\") veg_poly =",
"ground_poly = arcpy.Clip_analysis(ground_poly, aoi_prj, lidardir + \"\\\\ground_poly.shp\") else: ground_poly = arcpy.Erase_analysis(lidar_footprint, veg_poly, lidardir",
"print(\"AOI bare-ground polygon @ %s\" % ground_poly) except arcpy.ExecuteError: print(arcpy.GetMessages()) def lidar_to_raster(lidardir, spatialref_shp,",
"filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % (ticker",
"= arcpy.Describe(aoi_shp).spatialReference arcpy.env.extent = dem dem_dir = os.path.dirname(dem) # Initiate temp files folder",
"os.path import isfile, join import xlrd import shutil from openpyxl.workbook import Workbook from",
"= elevation_df['LOCATION'].max() elevation_df.sort_values('LOCATION', inplace=True) if elevation_df.iloc[0]['Value'] < elevation_df.iloc[-1]['Value']: loc_list = elevation_df.loc[:, ['LOCATION']].squeeze().to_list() loc_np",
"= 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" % ticker) while ticker",
"m_cell_size=1): \"\"\"Converts processed LAS files to a LAS dataset, and then to a",
"processing extent to the LiDAR data extent arcpy.env.extent = lidar_footprint in_spatial_ref = arcpy.Describe(lidar_footprint).spatialReference",
"f[:-4], laspath, f[:-4])) print(\"%s\\\\las2las.exe -i %s\\\\%s_noprj.las -o %s\\\\%s.las\" % (lasbin, laspath, f[:-4], laspath,",
"lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp') except arcpy.ExecuteError: print(arcpy.GetMessages())",
"Meters') elif in_spatial_ref.linearUnitName == 'Foot_US': cell_size = (3.28 * m_cell_size) print('LAS units are",
"be deleted...\") print('Done') else: print('Generating thalweg elevation profile...') centerline = dem_dir + \"\\\\thalweg_centerline.shp\"",
"units are Meters') elif out_spatial_ref.linearUnitName == 'Foot_US': print('DEM units are Feet') else: print('Linear",
"temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras =",
"join_attributes=\"ALL\", output_type=\"POINT\") station_points = arcpy.MultipartToSinglepart_management(station_points, intermediates[1]) station_points = arcpy.AddXY_management(station_points) # Extract elevation values",
"% f) if f[-5] == 'j': os.remove(laspath + \"\\\\%s\" % f) raw_las_dataset =",
"Initiate temp files folder formatted for LAStools temp_files = lidardir + '\\\\temp_files' if",
"'\\\\%s' % i for i in intermediates] # Create a station point shapefile",
"red_ras = arcpy.CopyRaster_management(red_lyr, temp_files + \"\\\\red_ras.tif\", format=\"TIFF\") nir_ras = arcpy.CopyRaster_management(nir_lyr, temp_files + \"\\\\nir_ras.tif\",",
"for LAStools processing\"\"\" files_in_direct = [f for f in listdir(lidardir) if isfile(join(lidardir, f))]",
"+ \"\\\\nir_ras.tif\", format=\"TIFF\") red_ras = Raster(red_ras) nir_ras = Raster(nir_ras) # Calculate ndvi and",
"the lidar footprint to give a ground_polygon used to define processing settings\"\"\" #",
"print(arcpy.GetMessages()) print(\"LAS -> DEM output @ %s\" % out_dem) # Notify the user",
"elevation_df['LOCATION'] = loc_np elevation_df.sort_values('LOCATION', inplace=True) elevation_df.to_csv(elevation_table) # Delete extra files for j in",
"\"\\\\raw_las_dataset.lasd\", spatial_reference=in_spatial_ref, compute_stats=True) lidar_ras = CreateConstantRaster(1, extent=raw_las_dataset) lidar_footprint = arcpy.RasterToPolygon_conversion(lidar_ras, lidardir + '\\\\las_footprint.shp')",
"well as producing a LiDAR extent polygon. in_folder must be a directory containing",
"out_dem = lidardir + \"\\\\las_dem.tif\" out_las = lasdir + '\\\\las_dataset.lasd' # Initiate temp",
"if lasbin[-1] != 'n': lasbin = lasbin[:-1] cmd(\"%s\\\\laszip.exe -i %s\\\\%s -o %s\\\\%s_noprj.las\" %",
"% filt_passes) ticker = 0 filter_out = arcpy.sa.Filter(dem, \"LOW\") filter_out.save(temp_files + \"\\\\filter_out%s\" %",
"to smooth the topography filter_out = arcpy.sa.Filter((temp_files + \"\\\\filter_out%s\" % ticker), \"LOW\") filter_out.save(temp_files",
"spatial reference Returns: Raster name for use in detrending \"\"\" # Create variables"
] |
[
"hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the",
"return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\"",
"'-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\"",
"key look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def",
"(url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url = make_url_secure(image_url,",
"md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") #",
"= base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key)",
"%s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look",
"main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url = make_url_secure(image_url, SECRET_KEY) print(secure_url) main()",
"token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url = make_url_secure(image_url, SECRET_KEY)",
"Make the key look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return",
"expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token =",
"def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def",
"= base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx expects. token = base64_encoded.replace('+',",
"make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def main():",
"secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx expects.",
"base64 import hashlib def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url,",
"(url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx",
"(\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key",
"% (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url =",
"def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url = make_url_secure(image_url, SECRET_KEY) print(secure_url)",
"base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx expects. token =",
"secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY",
"return token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url,",
").digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx expects. token",
"look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url,",
"base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/',",
"hashlib def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest()",
"like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key):",
"import base64 import hashlib def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" %",
"base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return",
"<reponame>xei/image-server import base64 import hashlib def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\"",
"token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token)",
"= generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\"",
"secret_key) return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url =",
"def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded",
"Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token",
"'_').rstrip('=') return token def make_url_secure(url, secret_key): token = generate_url_token(url, secret_key) return \"%s?token=%s\" %",
"token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token def make_url_secure(url, secret_key): token = generate_url_token(url,",
"generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded =",
"secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\")",
"= hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make",
"# Make the key look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=')",
"\"%s?token=%s\" % (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url = \"https://img.example.com/img/nowm/watermark.png\" secure_url",
"token = generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY =",
"% (url, secret_key)).encode(\"utf-8\") ).digest() base64_encoded = base64.b64encode(md5_digest).decode(\"utf-8\") # Make the key look like",
"import hashlib def generate_url_token(url, secret_key): md5_digest = hashlib.md5( (\"%s %s\" % (url, secret_key)).encode(\"utf-8\")",
"generate_url_token(url, secret_key) return \"%s?token=%s\" % (url, token) def main(): SECRET_KEY = \"MY_SECRET_KEY\" image_url",
"the key look like Nginx expects. token = base64_encoded.replace('+', '-').replace('/', '_').rstrip('=') return token"
] |
[
"p print(x, y) data = ['ACMD', 50, 90.1, (2012, 11, 12)] name, shares,",
"= (4, 5) x, y = p print(x, y) data = ['ACMD', 50,",
"['ACMD', 50, 90.1, (2012, 11, 12)] name, shares, price, date = data print(name,",
"p = (4, 5) x, y = p print(x, y) data = ['ACMD',",
"50, 90.1, (2012, 11, 12)] name, shares, price, date = data print(name, shares,",
"x, y = p print(x, y) data = ['ACMD', 50, 90.1, (2012, 11,",
"data = ['ACMD', 50, 90.1, (2012, 11, 12)] name, shares, price, date =",
"= ['ACMD', 50, 90.1, (2012, 11, 12)] name, shares, price, date = data",
"= p print(x, y) data = ['ACMD', 50, 90.1, (2012, 11, 12)] name,",
"print(x, y) data = ['ACMD', 50, 90.1, (2012, 11, 12)] name, shares, price,",
"5) x, y = p print(x, y) data = ['ACMD', 50, 90.1, (2012,",
"(4, 5) x, y = p print(x, y) data = ['ACMD', 50, 90.1,",
"y = p print(x, y) data = ['ACMD', 50, 90.1, (2012, 11, 12)]",
"y) data = ['ACMD', 50, 90.1, (2012, 11, 12)] name, shares, price, date",
"90.1, (2012, 11, 12)] name, shares, price, date = data print(name, shares, date)"
] |
[
"from model_new.config import Config from model_new.keras_model import KerasModel from model_new.utils import load_json config",
"model_new.keras_model import KerasModel from model_new.utils import load_json config = Config() model = KerasModel(config)",
"load_json config = Config() model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set =",
"# dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size * 50] model.train(train_set, None, None)",
"KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size *",
"from model_new.utils import load_json config = Config() model = KerasModel(config) train_set = load_json('dataset/train.json')",
"Config() model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set",
"= KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size",
"= load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size * 50] model.train(train_set,",
"config = Config() model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json')",
"model_new.config import Config from model_new.keras_model import KerasModel from model_new.utils import load_json config =",
"import Config from model_new.keras_model import KerasModel from model_new.utils import load_json config = Config()",
"train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size * 50]",
"model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set =",
"load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') # sub_set = dev_set[:config.batch_size * 50] model.train(train_set, None,",
"Config from model_new.keras_model import KerasModel from model_new.utils import load_json config = Config() model",
"KerasModel from model_new.utils import load_json config = Config() model = KerasModel(config) train_set =",
"from model_new.keras_model import KerasModel from model_new.utils import load_json config = Config() model =",
"= Config() model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set = load_json('dataset/dev.json') #",
"import KerasModel from model_new.utils import load_json config = Config() model = KerasModel(config) train_set",
"model_new.utils import load_json config = Config() model = KerasModel(config) train_set = load_json('dataset/train.json') #",
"import load_json config = Config() model = KerasModel(config) train_set = load_json('dataset/train.json') # dev_set"
] |
[
"import patterns, url from Standings import views urlpatterns = patterns( '', # ex:",
"from Standings import views urlpatterns = patterns( '', # ex: /standings/ url(r'^$', views.standings_index,",
"import views urlpatterns = patterns( '', # ex: /standings/ url(r'^$', views.standings_index, name='index'), )",
"django.conf.urls import patterns, url from Standings import views urlpatterns = patterns( '', #",
"Standings import views urlpatterns = patterns( '', # ex: /standings/ url(r'^$', views.standings_index, name='index'),",
"from django.conf.urls import patterns, url from Standings import views urlpatterns = patterns( '',",
"patterns, url from Standings import views urlpatterns = patterns( '', # ex: /standings/",
"url from Standings import views urlpatterns = patterns( '', # ex: /standings/ url(r'^$',"
] |
[
"whenever a user tries to commit something in this repo. # It checks",
"you sure you want to commit these changes? (y/n): \" failCount = 0",
"to decode any found tokens and see if they look like a JSONfragment",
"to proceed with this commit?: \" else: prompt = \"You've entered an incorrect",
"a test). Are you sure you want to commit these changes? (y/n): \"",
"token in longTokens: try: # python's base64 decoder fails if padding is missing;",
"(cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def",
"repo. # It checks the commit for any text that resembled an encoded",
"\" + token + \" gets decoded into: \" + utfOut) raiseIssue =",
"JSONfragment # where :look like a JSON fragment\" is defined as \"contains any",
"proceed with this commit?: \" elif failCount == 1: prompt = \"That's still",
"0 and inputLine[0] == 'y': print(\"OK, proceeding with commit\") return 0 elif len(inputLine)",
"found in commit: \" + token + \" gets decoded into: \" +",
"python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test",
"ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def main(): #get git",
"+ utfOut) raiseIssue = True # be very specific about the exceptions we",
"(y/n): \" failCount = 0 while True: inputLine = input(prompt).lower() if len(inputLine) >",
"you wish to proceed with this commit?: \" else: prompt = \"You've entered",
"that resembled an encoded JSON web token, # and asks the user to",
"for any text that resembled an encoded JSON web token, # and asks",
"'n'. Do you wish to proceed with this commit?: \" elif failCount ==",
"in the 'jwtPattern' regex pattern\" for token in longTokens: try: # python's base64",
"input(prompt).lower() if len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK, proceeding with commit\")",
"resembled an encoded JSON web token, # and asks the user to verify",
"want to commit a JWT if it finds any. import sys import subprocess",
"subprocess import re import base64 import binascii import unittest # run test like",
"to find long (20+ character) words consisting only of valid JWT characters longTokens",
"decoder fails if padding is missing; but does not fail if there's #",
"exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def main():",
"Please respond with 'y' or 'n' (sans apostrophes) regarding whether or not you",
"fail if there's # extra padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\")",
"or 'n'. Do you wish to proceed with this commit?: \" elif failCount",
"text filteredLines = list(filter(lambda line : len(line) > 20 and line[0] == '+',",
"prompt = \"This commit appears to add a JSON web token, which is",
"= \"Please answer with 'y' or 'n'. Do you wish to proceed with",
"test like so: # (cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def",
"\"Please answer with 'y' or 'n'. Do you wish to proceed with this",
"user through prompt sequence to double check if contains_jwt(filteredLines): prompt = \"This commit",
"commit a JWT if it finds any. import sys import subprocess import re",
"= 0 while True: inputLine = input(prompt).lower() if len(inputLine) > 0 and inputLine[0]",
"unittest # run test like so: # (cd .githooks/; python -m unittest pre-commit-python.py)",
"decode any found tokens and see if they look like a JSONfragment #",
"prompt sequence to double check if contains_jwt(filteredLines): prompt = \"This commit appears to",
"send user through prompt sequence to double check if contains_jwt(filteredLines): prompt = \"This",
"a likely JWT, send user through prompt sequence to double check if contains_jwt(filteredLines):",
"utfOut) raiseIssue = True # be very specific about the exceptions we ignore:",
"only # test longer, newly added text filteredLines = list(filter(lambda line : len(line)",
"likely JWTs found, proceeding with commit\") return 0 if __name__ == \"__main__\": sys.exit(main())",
"so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable",
"diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and",
"and asks the user to verify that they want to commit a JWT",
"line[0] == '+', lines)) # found a likely JWT, send user through prompt",
"len(line) > 20 and line[0] == '+', lines)) # found a likely JWT,",
"and inputLine[0] == 'y': print(\"OK, proceeding with commit\") return 0 elif len(inputLine) >",
"re import base64 import binascii import unittest # run test like so: #",
"missing; but does not fail if there's # extra padding; so always add",
"commit for any text that resembled an encoded JSON web token, # and",
"test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for",
"this commit?: \" else: prompt = \"You've entered an incorrect input \" +",
"True # be very specific about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error)",
"\" failCount += 1 else: print(\"No likely JWTs found, proceeding with commit\") return",
"script runs whenever a user tries to commit something in this repo. #",
"a '+' to only # test longer, newly added text filteredLines = list(filter(lambda",
"0 while True: inputLine = input(prompt).lower() if len(inputLine) > 0 and inputLine[0] ==",
"or not you wish to proceed with this commit which possibly contains a",
"runs whenever a user tries to commit something in this repo. # It",
"and see if they look like a JSONfragment # where :look like a",
"now. Please respond with 'y' or 'n' (sans apostrophes) regarding whether or not",
"this commit?: \" elif failCount == 1: prompt = \"That's still neither a",
"JSON fragment\" is defined as \"contains any of the words in the 'jwtPattern'",
"prompt = \"That's still neither a 'y' nor an 'n'. Do you wish",
"else: print(\"No likely JWTs found, proceeding with commit\") return 0 if __name__ ==",
"which possibly contains a JWT: \" failCount += 1 else: print(\"No likely JWTs",
"lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines that",
"if len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK, proceeding with commit\") return",
"commit something in this repo. # It checks the commit for any text",
"any text that resembled an encoded JSON web token, # and asks the",
"verify that they want to commit a JWT if it finds any. import",
"python's base64 decoder fails if padding is missing; but does not fail if",
"they look like a JSONfragment # where :look like a JSON fragment\" is",
":look like a JSON fragment\" is defined as \"contains any of the words",
"> 0 and inputLine[0] == 'y': print(\"OK, proceeding with commit\") return 0 elif",
"this repo. # It checks the commit for any text that resembled an",
"import sys import subprocess import re import base64 import binascii import unittest #",
"commit which possibly contains a JWT: \" failCount += 1 else: print(\"No likely",
"about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue",
"re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found tokens and see if they",
"the 'jwtPattern' regex pattern\" for token in longTokens: try: # python's base64 decoder",
"try to find long (20+ character) words consisting only of valid JWT characters",
"elif len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif",
"-m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"]))",
"if they look like a JSONfragment # where :look like a JSON fragment\"",
"you want to commit these changes? (y/n): \" failCount = 0 while True:",
"token, # and asks the user to verify that they want to commit",
"to commit these changes? (y/n): \" failCount = 0 while True: inputLine =",
"words in the 'jwtPattern' regex pattern\" for token in longTokens: try: # python's",
"match: print(\"Probable JWT found in commit: \" + token + \" gets decoded",
"True: inputLine = input(prompt).lower() if len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK,",
"sure you want to commit these changes? (y/n): \" failCount = 0 while",
"\" gets decoded into: \" + utfOut) raiseIssue = True # be very",
"elif failCount == 0: prompt = \"Please answer with 'y' or 'n'. Do",
"try to decode any found tokens and see if they look like a",
"longer, newly added text filteredLines = list(filter(lambda line : len(line) > 20 and",
"'+', lines)) # found a likely JWT, send user through prompt sequence to",
"self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue =",
"neither a 'y' nor an 'n'. Do you wish to proceed with this",
"'+' to only # test longer, newly added text filteredLines = list(filter(lambda line",
"to proceed with this commit?: \" elif failCount == 1: prompt = \"That's",
"if there's # extra padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match",
"the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def",
"token + \" gets decoded into: \" + utfOut) raiseIssue = True #",
"line) # try to decode any found tokens and see if they look",
"like a JSON fragment\" is defined as \"contains any of the words in",
"regarding whether or not you wish to proceed with this commit which possibly",
"that they want to commit a JWT if it finds any. import sys",
"want to commit these changes? (y/n): \" failCount = 0 while True: inputLine",
"print(\"OK, proceeding with commit\") return 0 elif len(inputLine) > 0 and inputLine[0] ==",
"is missing; but does not fail if there's # extra padding; so always",
"words consisting only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try",
"incorrect input \" + str(failCount) + \" times now. Please respond with 'y'",
"'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines that don't begin with",
"does not fail if there's # extra padding; so always add padding utfOut",
"we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def main(): #get",
"# try to decode any found tokens and see if they look like",
"possibly contains a JWT: \" failCount += 1 else: print(\"No likely JWTs found,",
"import base64 import binascii import unittest # run test like so: # (cd",
"import binascii import unittest # run test like so: # (cd .githooks/; python",
"'jwtPattern' regex pattern\" for token in longTokens: try: # python's base64 decoder fails",
"= re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found tokens and see if",
"= list(filter(lambda line : len(line) > 20 and line[0] == '+', lines)) #",
"# This script runs whenever a user tries to commit something in this",
"(unless it's for a test). Are you sure you want to commit these",
"padding is missing; but does not fail if there's # extra padding; so",
"while True: inputLine = input(prompt).lower() if len(inputLine) > 0 and inputLine[0] == 'y':",
"e: continue return raiseIssue def main(): #get git diff lines lines = subprocess.check_output(['git',",
"fragment\" is defined as \"contains any of the words in the 'jwtPattern' regex",
"It checks the commit for any text that resembled an encoded JSON web",
"to commit something in this repo. # It checks the commit for any",
"# (cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"]))",
"input \" + str(failCount) + \" times now. Please respond with 'y' or",
"problematic (unless it's for a test). Are you sure you want to commit",
"commit?: \" else: prompt = \"You've entered an incorrect input \" + str(failCount)",
"or 'n' (sans apostrophes) regarding whether or not you wish to proceed with",
"# run test like so: # (cd .githooks/; python -m unittest pre-commit-python.py) class",
"contains a JWT: \" failCount += 1 else: print(\"No likely JWTs found, proceeding",
"+ token + \" gets decoded into: \" + utfOut) raiseIssue = True",
"with this commit?: \" elif failCount == 1: prompt = \"That's still neither",
"begin with a '+' to only # test longer, newly added text filteredLines",
"Do you wish to proceed with this commit?: \" elif failCount == 1:",
"JWT if it finds any. import sys import subprocess import re import base64",
"to add a JSON web token, which is often accidental and can be",
"nor an 'n'. Do you wish to proceed with this commit?: \" else:",
": len(line) > 20 and line[0] == '+', lines)) # found a likely",
"in longTokens: try: # python's base64 decoder fails if padding is missing; but",
"import re import base64 import binascii import unittest # run test like so:",
"try: # python's base64 decoder fails if padding is missing; but does not",
"test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k')",
"JWT found in commit: \" + token + \" gets decoded into: \"",
"like so: # (cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self):",
"double check if contains_jwt(filteredLines): prompt = \"This commit appears to add a JSON",
"len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif failCount",
"padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found in",
"'n'. Do you wish to proceed with this commit?: \" else: prompt =",
"failCount == 0: prompt = \"Please answer with 'y' or 'n'. Do you",
"len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK, proceeding with commit\") return 0",
"raiseIssue def main(): #get git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') #",
"prompt = \"You've entered an incorrect input \" + str(failCount) + \" times",
"JSON web token, # and asks the user to verify that they want",
"if match: print(\"Probable JWT found in commit: \" + token + \" gets",
"test). Are you sure you want to commit these changes? (y/n): \" failCount",
"to double check if contains_jwt(filteredLines): prompt = \"This commit appears to add a",
"'y' nor an 'n'. Do you wish to proceed with this commit?: \"",
"\" + utfOut) raiseIssue = True # be very specific about the exceptions",
"JWT: \" failCount += 1 else: print(\"No likely JWTs found, proceeding with commit\")",
"inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif failCount == 0: prompt =",
"'n': print(\"Aborting commit\") return 1 elif failCount == 0: prompt = \"Please answer",
"with 'y' or 'n'. Do you wish to proceed with this commit?: \"",
"prompt = \"Please answer with 'y' or 'n'. Do you wish to proceed",
"there's # extra padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match =",
"finds any. import sys import subprocess import re import base64 import binascii import",
"asks the user to verify that they want to commit a JWT if",
"in this repo. # It checks the commit for any text that resembled",
"check if contains_jwt(filteredLines): prompt = \"This commit appears to add a JSON web",
"else: prompt = \"You've entered an incorrect input \" + str(failCount) + \"",
"== 'n': print(\"Aborting commit\") return 1 elif failCount == 0: prompt = \"Please",
"binascii import unittest # run test like so: # (cd .githooks/; python -m",
"valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found",
"accidental and can be problematic (unless it's for a test). Are you sure",
"binascii.Error) as e: continue return raiseIssue def main(): #get git diff lines lines",
"# be very specific about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as",
"with commit\") return 0 elif len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting",
"raiseIssue = False for line in lines: # try to find long (20+",
"= \"This commit appears to add a JSON web token, which is often",
"to verify that they want to commit a JWT if it finds any.",
"import subprocess import re import base64 import binascii import unittest # run test",
"any found tokens and see if they look like a JSONfragment # where",
"sequence to double check if contains_jwt(filteredLines): prompt = \"This commit appears to add",
"0 and inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif failCount == 0:",
"sys import subprocess import re import base64 import binascii import unittest # run",
"fails if padding is missing; but does not fail if there's # extra",
"but does not fail if there's # extra padding; so always add padding",
"text that resembled an encoded JSON web token, # and asks the user",
"commit: \" + token + \" gets decoded into: \" + utfOut) raiseIssue",
"see if they look like a JSONfragment # where :look like a JSON",
"lines and lines that don't begin with a '+' to only # test",
".githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self):",
"the commit for any text that resembled an encoded JSON web token, #",
"something in this repo. # It checks the commit for any text that",
"for token in longTokens: try: # python's base64 decoder fails if padding is",
"characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found tokens and",
"in commit: \" + token + \" gets decoded into: \" + utfOut)",
"# It checks the commit for any text that resembled an encoded JSON",
"JSON web token, which is often accidental and can be problematic (unless it's",
"often accidental and can be problematic (unless it's for a test). Are you",
"as \"contains any of the words in the 'jwtPattern' regex pattern\" for token",
"test longer, newly added text filteredLines = list(filter(lambda line : len(line) > 20",
"Do you wish to proceed with this commit?: \" else: prompt = \"You've",
"1: prompt = \"That's still neither a 'y' nor an 'n'. Do you",
"lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines",
"checks the commit for any text that resembled an encoded JSON web token,",
"a JWT: \" failCount += 1 else: print(\"No likely JWTs found, proceeding with",
"wish to proceed with this commit?: \" elif failCount == 1: prompt =",
"0: prompt = \"Please answer with 'y' or 'n'. Do you wish to",
"+ \" gets decoded into: \" + utfOut) raiseIssue = True # be",
"likely JWT, send user through prompt sequence to double check if contains_jwt(filteredLines): prompt",
"character) words consisting only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) #",
"found tokens and see if they look like a JSONfragment # where :look",
"user tries to commit something in this repo. # It checks the commit",
"that don't begin with a '+' to only # test longer, newly added",
"with 'y' or 'n' (sans apostrophes) regarding whether or not you wish to",
"# python's base64 decoder fails if padding is missing; but does not fail",
"newly added text filteredLines = list(filter(lambda line : len(line) > 20 and line[0]",
"utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit:",
"a JSON fragment\" is defined as \"contains any of the words in the",
"in lines: # try to find long (20+ character) words consisting only of",
"the user to verify that they want to commit a JWT if it",
"web token, which is often accidental and can be problematic (unless it's for",
"# extra padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut)",
"this commit which possibly contains a JWT: \" failCount += 1 else: print(\"No",
"contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines: # try",
"with this commit?: \" else: prompt = \"You've entered an incorrect input \"",
"for a test). Are you sure you want to commit these changes? (y/n):",
"with a '+' to only # test longer, newly added text filteredLines =",
"'y': print(\"OK, proceeding with commit\") return 0 elif len(inputLine) > 0 and inputLine[0]",
"\"contains any of the words in the 'jwtPattern' regex pattern\" for token in",
"look like a JSONfragment # where :look like a JSON fragment\" is defined",
"proceed with this commit?: \" else: prompt = \"You've entered an incorrect input",
"base64 import binascii import unittest # run test like so: # (cd .githooks/;",
"if contains_jwt(filteredLines): prompt = \"This commit appears to add a JSON web token,",
"return raiseIssue def main(): #get git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n')",
"inputLine[0] == 'y': print(\"OK, proceeding with commit\") return 0 elif len(inputLine) > 0",
"#!/usr/bin/python3 # This script runs whenever a user tries to commit something in",
"\" elif failCount == 1: prompt = \"That's still neither a 'y' nor",
"commit these changes? (y/n): \" failCount = 0 while True: inputLine = input(prompt).lower()",
"lines)) # found a likely JWT, send user through prompt sequence to double",
"failCount = 0 while True: inputLine = input(prompt).lower() if len(inputLine) > 0 and",
"raiseIssue = True # be very specific about the exceptions we ignore: except",
"any. import sys import subprocess import re import base64 import binascii import unittest",
"defined as \"contains any of the words in the 'jwtPattern' regex pattern\" for",
"these changes? (y/n): \" failCount = 0 while True: inputLine = input(prompt).lower() if",
"it finds any. import sys import subprocess import re import base64 import binascii",
"print(\"No likely JWTs found, proceeding with commit\") return 0 if __name__ == \"__main__\":",
"# where :look like a JSON fragment\" is defined as \"contains any of",
"# and asks the user to verify that they want to commit a",
"specific about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue return",
"# try to find long (20+ character) words consisting only of valid JWT",
"== 1: prompt = \"That's still neither a 'y' nor an 'n'. Do",
"and lines that don't begin with a '+' to only # test longer,",
"add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found",
"is often accidental and can be problematic (unless it's for a test). Are",
"appears to add a JSON web token, which is often accidental and can",
"encoded JSON web token, # and asks the user to verify that they",
"except (UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def main(): #get git diff",
"This script runs whenever a user tries to commit something in this repo.",
"added text filteredLines = list(filter(lambda line : len(line) > 20 and line[0] ==",
"of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any",
"run test like so: # (cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase):",
"a 'y' nor an 'n'. Do you wish to proceed with this commit?:",
"to commit a JWT if it finds any. import sys import subprocess import",
"always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT",
"extra padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if",
"if padding is missing; but does not fail if there's # extra padding;",
"not you wish to proceed with this commit which possibly contains a JWT:",
"of the words in the 'jwtPattern' regex pattern\" for token in longTokens: try:",
"str(failCount) + \" times now. Please respond with 'y' or 'n' (sans apostrophes)",
"\" else: prompt = \"You've entered an incorrect input \" + str(failCount) +",
"out short lines and lines that don't begin with a '+' to only",
"\"You've entered an incorrect input \" + str(failCount) + \" times now. Please",
"consisting only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to",
"> 0 and inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif failCount ==",
"def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False",
"short lines and lines that don't begin with a '+' to only #",
"padding; so always add padding utfOut = base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match:",
"= subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines that don't",
"proceeding with commit\") return 0 elif len(inputLine) > 0 and inputLine[0] == 'n':",
"to only # test longer, newly added text filteredLines = list(filter(lambda line :",
"tries to commit something in this repo. # It checks the commit for",
"whether or not you wish to proceed with this commit which possibly contains",
"still neither a 'y' nor an 'n'. Do you wish to proceed with",
"you wish to proceed with this commit?: \" elif failCount == 1: prompt",
"commit?: \" elif failCount == 1: prompt = \"That's still neither a 'y'",
"a JWT if it finds any. import sys import subprocess import re import",
"class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines):",
"wish to proceed with this commit which possibly contains a JWT: \" failCount",
"# test longer, newly added text filteredLines = list(filter(lambda line : len(line) >",
"apostrophes) regarding whether or not you wish to proceed with this commit which",
"any of the words in the 'jwtPattern' regex pattern\" for token in longTokens:",
"subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines that don't begin",
"and inputLine[0] == 'n': print(\"Aborting commit\") return 1 elif failCount == 0: prompt",
"elif failCount == 1: prompt = \"That's still neither a 'y' nor an",
"= False for line in lines: # try to find long (20+ character)",
"commit\") return 0 elif len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting commit\")",
"which is often accidental and can be problematic (unless it's for a test).",
"long (20+ character) words consisting only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\",",
"def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines: #",
"for line in lines: # try to find long (20+ character) words consisting",
"find long (20+ character) words consisting only of valid JWT characters longTokens =",
"very specific about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e: continue",
"longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found tokens and see",
"times now. Please respond with 'y' or 'n' (sans apostrophes) regarding whether or",
"into: \" + utfOut) raiseIssue = True # be very specific about the",
"def main(): #get git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter",
"20 and line[0] == '+', lines)) # found a likely JWT, send user",
"'y' or 'n'. Do you wish to proceed with this commit?: \" elif",
"like a JSONfragment # where :look like a JSON fragment\" is defined as",
"commit\") return 1 elif failCount == 0: prompt = \"Please answer with 'y'",
"test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in",
"def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern =",
"+ \" times now. Please respond with 'y' or 'n' (sans apostrophes) regarding",
"'y' or 'n' (sans apostrophes) regarding whether or not you wish to proceed",
"= base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit: \"",
"self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue",
"commit appears to add a JSON web token, which is often accidental and",
"user to verify that they want to commit a JWT if it finds",
"and can be problematic (unless it's for a test). Are you sure you",
"== '+', lines)) # found a likely JWT, send user through prompt sequence",
"jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit: \" + token + \"",
"0 elif len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting commit\") return 1",
"answer with 'y' or 'n'. Do you wish to proceed with this commit?:",
"re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines: # try to find long",
"= jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit: \" + token +",
"# found a likely JWT, send user through prompt sequence to double check",
"only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode",
"a JSONfragment # where :look like a JSON fragment\" is defined as \"contains",
"= \"That's still neither a 'y' nor an 'n'. Do you wish to",
"line : len(line) > 20 and line[0] == '+', lines)) # found a",
"# filter out short lines and lines that don't begin with a '+'",
"with this commit which possibly contains a JWT: \" failCount += 1 else:",
"the words in the 'jwtPattern' regex pattern\" for token in longTokens: try: #",
"main(): #get git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out",
"JWT, send user through prompt sequence to double check if contains_jwt(filteredLines): prompt =",
"as e: continue return raiseIssue def main(): #get git diff lines lines =",
"longTokens: try: # python's base64 decoder fails if padding is missing; but does",
"lines that don't begin with a '+' to only # test longer, newly",
"to proceed with this commit which possibly contains a JWT: \" failCount +=",
"a user tries to commit something in this repo. # It checks the",
"+= 1 else: print(\"No likely JWTs found, proceeding with commit\") return 0 if",
"return 1 elif failCount == 0: prompt = \"Please answer with 'y' or",
"TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern",
"= \"You've entered an incorrect input \" + str(failCount) + \" times now.",
"an encoded JSON web token, # and asks the user to verify that",
"\" failCount = 0 while True: inputLine = input(prompt).lower() if len(inputLine) > 0",
"a JSON web token, which is often accidental and can be problematic (unless",
"and line[0] == '+', lines)) # found a likely JWT, send user through",
"print(\"Probable JWT found in commit: \" + token + \" gets decoded into:",
"where :look like a JSON fragment\" is defined as \"contains any of the",
"failCount == 1: prompt = \"That's still neither a 'y' nor an 'n'.",
"found a likely JWT, send user through prompt sequence to double check if",
"web token, # and asks the user to verify that they want to",
"Are you sure you want to commit these changes? (y/n): \" failCount =",
"filteredLines = list(filter(lambda line : len(line) > 20 and line[0] == '+', lines))",
"lines: # try to find long (20+ character) words consisting only of valid",
"list(filter(lambda line : len(line) > 20 and line[0] == '+', lines)) # found",
"(UnicodeDecodeError, binascii.Error) as e: continue return raiseIssue def main(): #get git diff lines",
"+ str(failCount) + \" times now. Please respond with 'y' or 'n' (sans",
"inputLine = input(prompt).lower() if len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK, proceeding",
"entered an incorrect input \" + str(failCount) + \" times now. Please respond",
"match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit: \" + token",
"they want to commit a JWT if it finds any. import sys import",
"token, which is often accidental and can be problematic (unless it's for a",
"it's for a test). Are you sure you want to commit these changes?",
"changes? (y/n): \" failCount = 0 while True: inputLine = input(prompt).lower() if len(inputLine)",
"'--staged']).decode(\"utf-8\").split('\\n') # filter out short lines and lines that don't begin with a",
"== 'y': print(\"OK, proceeding with commit\") return 0 elif len(inputLine) > 0 and",
"JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line) # try to decode any found tokens",
"import unittest # run test like so: # (cd .githooks/; python -m unittest",
"base64.urlsafe_b64decode(token+'==').decode(\"utf-8\") match = jwtPattern.search(utfOut) if match: print(\"Probable JWT found in commit: \" +",
"line in lines: # try to find long (20+ character) words consisting only",
"= re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines: # try to find",
"pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def",
"contains_jwt(filteredLines): prompt = \"This commit appears to add a JSON web token, which",
"you wish to proceed with this commit which possibly contains a JWT: \"",
"#get git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short",
"== 0: prompt = \"Please answer with 'y' or 'n'. Do you wish",
"(sans apostrophes) regarding whether or not you wish to proceed with this commit",
"an 'n'. Do you wish to proceed with this commit?: \" else: prompt",
"1 elif failCount == 0: prompt = \"Please answer with 'y' or 'n'.",
"= True # be very specific about the exceptions we ignore: except (UnicodeDecodeError,",
"failCount += 1 else: print(\"No likely JWTs found, proceeding with commit\") return 0",
"wish to proceed with this commit?: \" else: prompt = \"You've entered an",
"be very specific about the exceptions we ignore: except (UnicodeDecodeError, binascii.Error) as e:",
"through prompt sequence to double check if contains_jwt(filteredLines): prompt = \"This commit appears",
"\"This commit appears to add a JSON web token, which is often accidental",
"return 0 elif len(inputLine) > 0 and inputLine[0] == 'n': print(\"Aborting commit\") return",
"pattern\" for token in longTokens: try: # python's base64 decoder fails if padding",
"don't begin with a '+' to only # test longer, newly added text",
"print(\"Aborting commit\") return 1 elif failCount == 0: prompt = \"Please answer with",
"'n' (sans apostrophes) regarding whether or not you wish to proceed with this",
"proceed with this commit which possibly contains a JWT: \" failCount += 1",
"respond with 'y' or 'n' (sans apostrophes) regarding whether or not you wish",
"\"That's still neither a 'y' nor an 'n'. Do you wish to proceed",
"not fail if there's # extra padding; so always add padding utfOut =",
"filter out short lines and lines that don't begin with a '+' to",
"decoded into: \" + utfOut) raiseIssue = True # be very specific about",
"(20+ character) words consisting only of valid JWT characters longTokens = re.findall(\"[A-Za-z0-9_=-]{20,}\", line)",
"self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line",
"tokens and see if they look like a JSONfragment # where :look like",
"base64 decoder fails if padding is missing; but does not fail if there's",
"> 20 and line[0] == '+', lines)) # found a likely JWT, send",
"add a JSON web token, which is often accidental and can be problematic",
"gets decoded into: \" + utfOut) raiseIssue = True # be very specific",
"False for line in lines: # try to find long (20+ character) words",
"can be problematic (unless it's for a test). Are you sure you want",
"\" times now. Please respond with 'y' or 'n' (sans apostrophes) regarding whether",
"an incorrect input \" + str(failCount) + \" times now. Please respond with",
"= input(prompt).lower() if len(inputLine) > 0 and inputLine[0] == 'y': print(\"OK, proceeding with",
"be problematic (unless it's for a test). Are you sure you want to",
"git diff lines lines = subprocess.check_output(['git', 'diff', '--staged']).decode(\"utf-8\").split('\\n') # filter out short lines",
"self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"])) def contains_jwt(lines): jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines:",
"continue return raiseIssue def main(): #get git diff lines lines = subprocess.check_output(['git', 'diff',",
"so: # (cd .githooks/; python -m unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"]))",
"unittest pre-commit-python.py) class TestStringMethods(unittest.TestCase): def test_jwts(self): self.assertTrue(contains_jwt([\"<KEY>\"])) self.assertTrue(contains_jwt([\"<KEY>\"])) def test_ok(self): self.assertFalse(contains_jwt([\"test test\"])) self.assertFalse(contains_jwt([\"thisisnotajwteventhoughitisalongstring\"]))",
"jwtPattern = re.compile('JWT|iat|name|sub|alg|exp|k') raiseIssue = False for line in lines: # try to",
"\" + str(failCount) + \" times now. Please respond with 'y' or 'n'",
"regex pattern\" for token in longTokens: try: # python's base64 decoder fails if",
"1 else: print(\"No likely JWTs found, proceeding with commit\") return 0 if __name__",
"if it finds any. import sys import subprocess import re import base64 import",
"is defined as \"contains any of the words in the 'jwtPattern' regex pattern\""
] |
[
"here which either installs or provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y):",
"This is a custom installation function. By default, it will simply try to",
"'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y)))",
"meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if",
"TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom installation function. By default, it",
"load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing any last minute customizing \"\"\"",
"y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username' in meta.columns: meta['author']=meta['username'] return meta",
"import lltk from lltk.text.text import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass",
"Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs):",
"function. By default, it will simply try to download itself, unless a custom",
"meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username'",
"meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username' in",
"either installs or provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic",
"and doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns:",
"compile(self,**attrs): \"\"\" This is a custom installation function. By default, it will simply",
"it will simply try to download itself, unless a custom function is written",
"installs or provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute",
"meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5",
"import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is",
"x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username' in meta.columns:",
"instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing",
"is a custom installation function. By default, it will simply try to download",
"minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda",
"self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing any last minute",
"custom function is written here which either installs or provides installation instructions. \"\"\"",
"which either installs or provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\"",
"or provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading",
"last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1])",
"any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x:",
"download itself, unless a custom function is written here which either installs or",
"function is written here which either installs or provides installation instructions. \"\"\" return",
"metadata, and doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in",
"to download itself, unless a custom function is written here which either installs",
"\"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y))",
"loading metadata, and doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published'",
"lltk from lltk.text.text import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class",
"installation function. By default, it will simply try to download itself, unless a",
"Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a",
"class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom",
"TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom installation",
"x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username' in meta.columns: meta['author']=meta['username']",
"\"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing any",
"itself, unless a custom function is written here which either installs or provides",
"from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\"",
"a custom function is written here which either installs or provides installation instructions.",
"installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and",
"written here which either installs or provides installation instructions. \"\"\" return self.download(**attrs) def",
"default, it will simply try to download itself, unless a custom function is",
"FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom installation function. By default,",
"return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing any last",
"simply try to download itself, unless a custom function is written here which",
"unless a custom function is written here which either installs or provides installation",
"Magic attribute loading metadata, and doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction'",
"pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom installation function.",
"from lltk.text.text import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus):",
"meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if 'username' in meta.columns: meta['author']=meta['username'] return",
"doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda",
"will simply try to download itself, unless a custom function is written here",
"class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This is a custom installation function. By",
"attribute loading metadata, and doing any last minute customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if",
"if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else",
"lltk.text.text import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic",
"def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata, and doing any last minute customizing",
"lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def compile(self,**attrs): \"\"\" This",
"\"\"\" This is a custom installation function. By default, it will simply try",
"\"\"\" Magic attribute loading metadata, and doing any last minute customizing \"\"\" meta=super().load_metadata()",
"def compile(self,**attrs): \"\"\" This is a custom installation function. By default, it will",
"customizing \"\"\" meta=super().load_metadata() meta['genre']='FanFiction' if 'published' in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y:",
"in meta.columns: meta['year']=meta['published'].apply(lambda x: x.split('/')[-1]) meta['year']=meta['year'].apply(lambda y: int('20'+str(y)) if int(str(y)[0])<5 else int('19'+str(y))) if",
"import os import lltk from lltk.text.text import Text from lltk.corpus.corpus import Corpus class",
"custom installation function. By default, it will simply try to download itself, unless",
"provides installation instructions. \"\"\" return self.download(**attrs) def load_metadata(self,*x,**y): \"\"\" Magic attribute loading metadata,",
"os import lltk from lltk.text.text import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text):",
"By default, it will simply try to download itself, unless a custom function",
"import Text from lltk.corpus.corpus import Corpus class TextFanFic(Text): pass class FanFic(Corpus): TEXT_CLASS=TextFanFic def",
"try to download itself, unless a custom function is written here which either",
"a custom installation function. By default, it will simply try to download itself,",
"is written here which either installs or provides installation instructions. \"\"\" return self.download(**attrs)"
] |
[
"import json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI",
"\"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized']",
"audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) # 안녕하세요 오늘도 멋진 하루",
"access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents } } http = urllib3.PoolManager() try:",
"} http = urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"},",
"open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except:",
"response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason'] return response if",
"response = response_json['return_object']['recognized'] except: response = response_json['reason'] return response if __name__ == \"__main__\":",
"\"audio\": audio_contents } } http = urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL,",
"str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를",
"{ \"language_code\": language_code, \"audio\": audio_contents } } http = urllib3.PoolManager() try: res =",
"= { \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents } } http",
"= json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason'] return response if __name__",
"= \"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = {",
"language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json =",
"@params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\")",
"} } http = urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json;",
"http = urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json)",
"etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\"",
") response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason'] return response",
"audio_contents } } http = urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\":",
"= json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file =",
"access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\")",
"language_code, \"audio\": audio_contents } } http = urllib3.PoolManager() try: res = http.request( \"POST\",",
"os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후",
"= os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code",
"os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code =",
"http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response =",
"= open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\":",
"import os import json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path:",
"= os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) # 안녕하세요 오늘도 멋진 하루 되세요",
"<gh_stars>0 #-*- coding:utf-8 -*- import os import json import base64 import urllib3 BASE_DIR",
"= http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response",
"except: response = response_json['reason'] return response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR,",
"= os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한",
"`Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file =",
"= response_json['return_object']['recognized'] except: response = response_json['reason'] return response if __name__ == \"__main__\": audio_file_path",
"== \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) # 안녕하세요 오늘도",
"import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을",
"response_json['return_object']['recognized'] except: response = response_json['reason'] return response if __name__ == \"__main__\": audio_file_path =",
"\"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\"",
"-*- import os import json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def",
"urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json",
"charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason']",
"response = response_json['reason'] return response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\")",
"base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents",
"return response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path)",
"\"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response =",
"-1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL",
"body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason'] return",
"__name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) # 안녕하세요",
"오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\",
"data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key =",
"response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response)",
"audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\": { \"language_code\": language_code,",
"transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트",
"데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1`",
"\"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents } } http = urllib3.PoolManager()",
"\"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) # 안녕하세요 오늘도 멋진",
"res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\"))",
"base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오",
"`Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key",
"파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params",
"음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\",
"file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key,",
"\"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\": { \"language_code\":",
"etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents =",
"etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file",
"= \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close()",
"음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status",
"file.close() request_json = { \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents }",
"= base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\":",
"open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\": access_key, \"argument\": {",
"#-*- coding:utf-8 -*- import os import json import base64 import urllib3 BASE_DIR =",
"json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리",
"모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted`",
"`\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key",
"@returns `Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read())",
"\\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR,",
"`한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str)",
"\"argument\": { \"language_code\": language_code, \"audio\": audio_contents } } http = urllib3.PoolManager() try: res",
"def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어`",
"open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\")",
"try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json =",
"\"language_code\": language_code, \"audio\": audio_contents } } http = urllib3.PoolManager() try: res = http.request(",
"|| -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"]",
"json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response = response_json['reason'] return response if __name__ ==",
"인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns",
"BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을",
"{ \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents } } http =",
"반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\"",
"headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) ) response_json = json.loads(res.data.decode(\"utf-8\")) response = response_json['return_object']['recognized'] except: response",
"받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"`",
"= urllib3.PoolManager() try: res = http.request( \"POST\", open_api_URL, headers={\"Content-Type\": \"application/json; charset=UTF-8\"}, body=json.dumps(request_json) )",
"if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response = transcribe_etri(audio_file_path) print(response) #",
"import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다.",
"os import json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str):",
"\"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key = json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL =",
"= etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents",
"텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) ||",
"\\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file = os.path.join(BASE_DIR, \"deep/etri.json\") etri_key =",
"@status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response data(str) || -1` \"\"\" etri_json_file",
"urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def transcribe_etri(audio_file_path: str): \"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면",
"\"\"\"ETRI 음성처리 모듈입니다. 오디오 파일을 받으면 음성을 인식한 후 `한국어` 텍스트 데이터를 반환합니다.",
"coding:utf-8 -*- import os import json import base64 import urllib3 BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))",
"= response_json['reason'] return response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response",
"\"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json = { \"access_key\":",
"response_json['reason'] return response if __name__ == \"__main__\": audio_file_path = os.path.join(BASE_DIR, \"src/python/hello.wav\") response =",
"request_json = { \"access_key\": access_key, \"argument\": { \"language_code\": language_code, \"audio\": audio_contents } }",
"json.loads(open(etri_json_file).read()) access_key = etri_key[\"private_key\"] open_api_URL = \"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path,",
"후 `한국어` 텍스트 데이터를 반환합니다. @status `Accepted` \\\\ @params `\"~/src/python/temp2.wav\"` \\\\ @returns `Response",
"\"http://aiopen.etri.re.kr:8000/WiseASR/Recognition\" language_code = \"korean\" file = open(audio_file_path, \"rb\") audio_contents = base64.b64encode(file.read()).decode(\"utf8\") file.close() request_json"
] |
[
"\"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\",",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"# import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client",
"id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris =",
"The ASF licenses this file to You under the Apache License, Version 2.0",
"\"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles =",
"\"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\",",
"the NOTICE file distributed with # this work for additional information regarding copyright",
"redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\",",
"response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0,",
"False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants():",
"\"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos",
"from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) #",
"= [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts,",
"ANY KIND, either express or implied. # See the License for the specific",
"True, True, False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\")",
"\"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\",",
"def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id",
"def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response =",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"work for additional information regarding copyright ownership. # The ASF licenses this file",
"level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with default",
"License. # import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\",",
"the License. # import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient",
"OF ANY KIND, either express or implied. # See the License for the",
"[\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris,",
"realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\",",
"print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \",",
"client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\")",
"ownership. # The ASF licenses this file to You under the Apache License,",
"0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response)",
"contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id,",
"regarding copyright ownership. # The ASF licenses this file to You under the",
"# limitations under the License. # import logging from custos.clients.tenant_management_client import TenantManagementClient from",
"handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with default configuration",
"\"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0,",
"= CustosServerClientSettings() # load APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client =",
"= [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos",
"permissions and # limitations under the License. # import logging from custos.clients.tenant_management_client import",
"Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def",
"copyright ownership. # The ASF licenses this file to You under the Apache",
"False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response",
"handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with default configuration client = TenantManagementClient(custos_settings)",
"# this work for additional information regarding copyright ownership. # The ASF licenses",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles():",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"CustosServerClientSettings() # load APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings)",
"profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\"",
"print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True,",
"\"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts =",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a higher log",
"[\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\",",
"License, Version 2.0 # (the \"License\"); you may not use this file except",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"required by applicable law or agreed to in writing, software # distributed under",
"and # limitations under the License. # import logging from custos.clients.tenant_management_client import TenantManagementClient",
"this file except in compliance with # the License. You may obtain a",
"applicable law or agreed to in writing, software # distributed under the License",
"= client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\",",
"console handler with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings =",
"\"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id)",
"print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant():",
"or agreed to in writing, software # distributed under the License is distributed",
"True, True, True, False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5,",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\",",
"roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\",",
"contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True,",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"under the License. # import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import",
"def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response =",
"redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\",",
"token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response =",
"response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"]",
"IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response",
"compliance with # the License. You may obtain a copy of the License",
"NOTICE file distributed with # this work for additional information regarding copyright ownership.",
"admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts =",
"distributed with # this work for additional information regarding copyright ownership. # The",
"\"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy",
"Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\",",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"= client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5,",
"email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response",
"from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from",
"utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\",",
"License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\",",
"print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response",
"[{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response)",
"agreements. See the NOTICE file distributed with # this work for additional information",
"ASF licenses this file to You under the Apache License, Version 2.0 #",
"a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load",
"2.0 # (the \"License\"); you may not use this file except in compliance",
"get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant(): response = client.delete_tenant(token,",
"logger.setLevel(logging.DEBUG) # create console handler with a higher log level handler = logging.StreamHandler()",
"Apache License, Version 2.0 # (the \"License\"); you may not use this file",
"False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"= \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts",
"in compliance with # the License. You may obtain a copy of the",
"create console handler with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings",
"agreed to in writing, software # distributed under the License is distributed on",
"contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\",",
"Foundation (ASF) under one or more # contributor license agreements. See the NOTICE",
"def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant(): response =",
"file to You under the Apache License, Version 2.0 # (the \"License\"); you",
"custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger =",
"def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First",
"\"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\",",
"response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant(): response = client.delete_tenant(token, \"<PASSWORD>-pv<PASSWORD>ps<PASSWORD>t-10000000\")",
"TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts",
"contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def",
"# Unless required by applicable law or agreed to in writing, software #",
"get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id =",
"may not use this file except in compliance with # the License. You",
"by applicable law or agreed to in writing, software # distributed under the",
"= [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False)",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response =",
"APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings)",
"logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient",
"# Licensed to the Apache Software Foundation (ASF) under one or more #",
"True, False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response)",
"org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response =",
"more # contributor license agreements. See the NOTICE file distributed with # this",
"\"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def get_child_tenants(): response = client.get_child_tenants(token,",
"License for the specific language governing permissions and # limitations under the License.",
"client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris =",
"org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\":",
"Apache Software Foundation (ASF) under one or more # contributor license agreements. See",
"to in writing, software # distributed under the License is distributed on an",
"to You under the Apache License, Version 2.0 # (the \"License\"); you may",
"implied. # See the License for the specific language governing permissions and #",
"custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"\"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response)",
"\"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token,",
"the Apache License, Version 2.0 # (the \"License\"); you may not use this",
"\"License\"); you may not use this file except in compliance with # the",
"= utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\",",
"or implied. # See the License for the specific language governing permissions and",
"\"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\")",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__)",
"log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with",
"False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"\"Galaxy Portal\") print(response) def get_tenant(): client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response)",
"the Apache Software Foundation (ASF) under one or more # contributor license agreements.",
"# load APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client",
"\"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles",
"custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def",
"\"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def get_child_tenants(): response =",
"= [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"] response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\",",
"handler with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings()",
"you may not use this file except in compliance with # the License.",
"from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger",
"use this file except in compliance with # the License. You may obtain",
"response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\",",
"Software Foundation (ASF) under one or more # contributor license agreements. See the",
"= client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris,",
"as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a higher",
"language governing permissions and # limitations under the License. # import logging from",
"for the specific language governing permissions and # limitations under the License. #",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"# (the \"License\"); you may not use this file except in compliance with",
"logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a higher log level",
"higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient",
"# # Unless required by applicable law or agreed to in writing, software",
"\"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant():",
"express or implied. # See the License for the specific language governing permissions",
"Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email",
"except in compliance with # the License. You may obtain a copy of",
"file distributed with # this work for additional information regarding copyright ownership. #",
"(ASF) under one or more # contributor license agreements. See the NOTICE file",
"the License. You may obtain a copy of the License at # #",
"custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings",
"= IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris = [\"http://localhost:8080,http://localhost:8080/user/external_ids\"]",
"client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\",",
"\"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\":",
"client_id = \"custos-8p4baddxvbiusmjorjch-10000401\" response = client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\"",
"either express or implied. # See the License for the specific language governing",
"or more # contributor license agreements. See the NOTICE file distributed with #",
"\"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\",",
"profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\":",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"license agreements. See the NOTICE file distributed with # this work for additional",
"licenses this file to You under the Apache License, Version 2.0 # (the",
"under the Apache License, Version 2.0 # (the \"License\"); you may not use",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"\", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\",",
"Version 2.0 # (the \"License\"); you may not use this file except in",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token,",
"[\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\",",
"response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts,",
"= TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant():",
"SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl",
"# contributor license agreements. See the NOTICE file distributed with # this work",
"CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler",
"client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile",
"\"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token,",
"\"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response =",
"\"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\",",
"See the NOTICE file distributed with # this work for additional information regarding",
"\"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id",
"import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import",
"with default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token",
"custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a",
"\"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\")",
"\"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile",
"with # the License. You may obtain a copy of the License at",
"TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings",
"under one or more # contributor license agreements. See the NOTICE file distributed",
"logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with default configuration client =",
"\"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper():",
"load APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client =",
"law or agreed to in writing, software # distributed under the License is",
"SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"] redirect_uris",
"the License for the specific language governing permissions and # limitations under the",
"# the License. You may obtain a copy of the License at #",
"configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings)",
"import TenantManagementClient from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import",
"client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def",
"import CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console",
"this file to You under the Apache License, Version 2.0 # (the \"License\");",
"not use this file except in compliance with # the License. You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"redirect_uris, \"https://domain.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant():",
"IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG)",
"You under the Apache License, Version 2.0 # (the \"License\"); you may not",
"import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import custos.clients.utils.utilities as",
"= client.get_tenant(client_token=token, client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris",
"= SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token = utl.get_token(custos_settings) def create_tenant(): contacts = [\"2345634324\"]",
"update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"]",
"= client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid",
"one or more # contributor license agreements. See the NOTICE file distributed with",
"with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() #",
"= admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant(): response = client.delete_tenant(token, \"<PASSWORD>-pv<PASSWORD>ps<PASSWORD>t-10000000\") print(response)",
"limitations under the License. # import logging from custos.clients.tenant_management_client import TenantManagementClient from custos.clients.super_tenant_management_client",
"Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}]",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def get_child_tenants(): response",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False)",
"print(response) def get_all_tenants(): response = admin_client.get_all_tenants(token, 0, 5, \"ACTIVE\") print(response) def delete_tenant(): response",
"= logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a higher log level handler",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"Licensed to the Apache Software Foundation (ASF) under one or more # contributor",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"governing permissions and # limitations under the License. # import logging from custos.clients.tenant_management_client",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"(the \"License\"); you may not use this file except in compliance with #",
"# create console handler with a higher log level handler = logging.StreamHandler() handler.setLevel(logging.DEBUG)",
"= logging.StreamHandler() handler.setLevel(logging.DEBUG) custos_settings = CustosServerClientSettings() # load APIServerClient with default configuration client",
"\"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\", \"openid profile email",
"\"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response) def get_child_tenants():",
"for additional information regarding copyright ownership. # The ASF licenses this file to",
"\"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response)",
"the specific language governing permissions and # limitations under the License. # import",
"def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\",",
"client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\", \"Custos1234\", contacts, redirect_uris, \"https://custos.scigap.org/\", \"openid",
"add_protocol_mapper(): response = client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False,",
"additional information regarding copyright ownership. # The ASF licenses this file to You",
"contributor license agreements. See the NOTICE file distributed with # this work for",
"\"domain.org\", \"https://custos.scigap.org/\", \"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False,",
"\"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\", \"<EMAIL>\", \"isjarana\",",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"[\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\", \"Ranawaka\",",
"\"openid profile email org.cilogon.userinfo\", \"domain.org\", \"https://domain.org/static/favicon.png\", \"Galaxy Portal\") print(response) def get_tenant(): client_id =",
"default configuration client = TenantManagementClient(custos_settings) admin_client = SuperTenantManagementClient(custos_settings) id_client = IdentityManagementClient(custos_settings) token =",
"custos_settings = CustosServerClientSettings() # load APIServerClient with default configuration client = TenantManagementClient(custos_settings) admin_client",
"this work for additional information regarding copyright ownership. # The ASF licenses this",
"import custos.clients.utils.utilities as utl logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with",
"\"testing\", \"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def",
"from custos.clients.super_tenant_management_client import SuperTenantManagementClient from custos.clients.identity_management_client import IdentityManagementClient from custos.transport.settings import CustosServerClientSettings import",
"add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token,",
"to the Apache Software Foundation (ASF) under one or more # contributor license",
"with # this work for additional information regarding copyright ownership. # The ASF",
"= [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response = client.update_tenant(token, client_id, \"Custos Portal\", \"<EMAIL>\", \"Isuru\",",
"file except in compliance with # the License. You may obtain a copy",
"= client.add_protocol_mapper(token, \"phone_atr\", \"phone\", \"phone\", \"STRING\", \"USER_ATTRIBUTE\", True, True, True, False, False) print(response)",
"information regarding copyright ownership. # The ASF licenses this file to You under",
"response = client.create_admin_tenant(\"SAMPLE\", \"<EMAIL>\", \"First Name\", \"LastName\", \"email\", \"admin\", \"1234\", contacts, redirect_uris, \"https://domain.org/\",",
"client_id=client_id) print(response) def update_tenant(): client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback",
"specific language governing permissions and # limitations under the License. # import logging",
"\"testing realm\"}] response = client.add_tenant_roles(token, roles, False) print(response) def add_protocol_mapper(): response = client.add_protocol_mapper(token,",
"client_id = \"custos-6nwoqodstpe5mvcq09lh-10000101\" contacts = [\"8123915386\"] redirect_uris = [\"https://custos.scigap.org/callback \", \"http://127.0.0.1:8000/auth/callback/\", \"http://127.0.0.1:8000/\"] response",
"roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing realm\"}] response = client.add_tenant_roles(token, roles,",
"\"Custos Portal\") print(response) def add_tenant_roles(): roles = [{\"name\": \"testing\", \"composite\": False, \"description\": \"testing",
"print(response) def get_child_tenants(): response = client.get_child_tenants(token, 0, 5, \"ACTIVE\") print(response) def get_all_tenants(): response",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # create console handler with a higher log level handler =",
"# The ASF licenses this file to You under the Apache License, Version"
] |
[
"res = _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value) else: # Union",
"infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps,",
"# otherwise fallback on constructing using type_ itself try: res = _get_type_cons(type_)(xs) except",
"partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for field in fields(cls)",
"{field for field in fields(cls) if field.name not in kvs} for field in",
"_obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped",
"collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs =",
"= kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in",
"*, infer_missing: bool = False, only=None, exclude=(), many: bool = False, context=None, load_only=(),",
"many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={},",
"being # serialized when handling nested marshmallow schema # proper fix is to",
"= False): \"\"\" This method loads from YAML file to properties of self",
"as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be in",
"= value elif _issubclass_safe(type_, Enum): # Convert to an Enum using the type",
"field, we can't statically create a schema for it # so we just",
"(MISSING, fields, is_dataclass # type: ignore ) Json = Union[dict, list, str, int,",
"import Enum from marshmallow import post_load, Schema from pyspark_config.errors import * from dataclasses_json",
"init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param:",
"'type' in [f.name for f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param =",
"constructor. # Assumes a direct match is found. res = type_(value) # FIXME",
"a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if",
"is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value",
"_decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing)",
"more hacky # The only problem is the catch all field, we can't",
"is_dataclass # type: ignore ) Json = Union[dict, list, str, int, float, bool,",
"the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict =",
"the marshmallow schema generation # code if is_dataclass(field_value): value = field_value else: value",
"return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,),",
"_user_overrides_or_exts(cls) kvs = {} if kvs is None and infer_missing else kvs field_names",
"statically create a schema for it # so we just update the dumped",
"type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and",
"one of the fields is called type, the corresponding subclass is searched for.",
"None): # FIXME hack if field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name]",
"is not None): # FIXME hack if field_type is type(field_value): init_kwargs[field.name] = field_value",
"enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ =",
"= get_type_hints(cls) for field in fields(cls): # The field should be skipped from",
"fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True else: type_param = False if",
"unsupported 'from_json' used) res = value return res def getSubclass(cls, values): \"\"\" In",
"path_is_absolute: bool = False): \"\"\" This method loads from YAML file to properties",
"else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType]",
"type in `typing` # otherwise fallback on constructing using type_ itself try: res",
"kvs, partial) def dumps(self, *args, **kwargs): if 'cls' not in kwargs: kwargs['cls'] =",
"parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls)",
"elif 'type' in field_names: type_param = True else: type_param = False if field_value",
"subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls):",
"DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs",
"= {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except",
"_decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses",
"res = type_(xs) else: # Optional or Union if not hasattr(type_, \"__args__\"): #",
"_decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value) else: # Union (already decoded",
"YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No such file or directory: %s\"",
"Type[A], kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None,",
"import raise_from from enum import Enum from marshmallow import post_load, Schema from pyspark_config.errors",
"GenericMeta field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param =",
"for f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True else: type_param",
"file load function.\"\"\" def load(self, path: str, path_is_absolute: bool = False): \"\"\" This",
"and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] !=",
"kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None):",
"catch all field, we can't statically create a schema for it # so",
"... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is None: return",
"(_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) # get the constructor if using",
"form; can be relative or absolute. path_is_absolute: indicates whether the path is an",
"dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta':",
"or Union if not hasattr(type_, \"__args__\"): # Any, just accept res = value",
"= field_value continue while True: if not _is_new_type(field_type): break field_type = field_type.__supertype__ if",
"dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe,",
"_decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses import (MISSING, fields,",
"TODO This is hacky, but the other option I can think of is",
"overrides and overrides[field.name].decoder is not None): # FIXME hack if field_type is type(field_value):",
"Any, just accept res = value elif _is_optional(type_) and len(type_.__args__) == 2: #",
"@dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls",
"-> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action",
"= build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if",
"infer_missing else kvs field_names = [field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names,",
"and field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module }) @post_load def",
"virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs,",
"field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type != str and not",
"dataclasses import dataclass from pathlib import Path from typing import (Any, Union,Type, Optional)",
"is None: res = value elif _issubclass_safe(type_, Enum): # Convert to an Enum",
"the type as a constructor. # Assumes a direct match is found. res",
"from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type,",
"= 'type' in [f.name for f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param",
"undefined) if _cls is None: return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined):",
"path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r',",
"hack to fix a deeper underlying issue. A refactor is due. elif _is_collection(type_):",
"class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool = False, only=None, exclude=(),",
"= yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be in YAML format: %s\"",
"other option I can think of is to generate a different schema #",
"partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None:",
"= [field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k,",
"import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import",
"import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe,",
"(_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A",
"ignore ) Json = Union[dict, list, str, int, float, bool, None] from pyspark_config.yamlConfig",
"ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__)",
"= classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ =",
"SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action =",
"is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None # Perform",
"\" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while True: if not",
"fields(cls): # The field should be skipped from being added # to init_kwargs",
"# Union (already decoded or unsupported 'from_json' used) res = value return res",
"value) else: # Union (already decoded or unsupported 'from_json' used) res = value",
"Enum from marshmallow import post_load, Schema from pyspark_config.errors import * from dataclasses_json import",
"# depending on dump and load, which is even more hacky # The",
"Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for",
"and field_type != str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif",
"\"\"\"This class implements YAML file load function.\"\"\" def load(self, path: str, path_is_absolute: bool",
"}) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args,",
"value = field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif",
"can't statically create a schema for it # so we just update the",
"f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema",
"the code in the `dataclasses` module to handle optional-parens decorators. See example below:",
"else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type",
"init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type != str and not type_param: init_kwargs[field.name]",
"type_(value) # FIXME this is a hack to fix a deeper underlying issue.",
"dumped dict if many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\"))",
"from dataclasses import (MISSING, fields, is_dataclass # type: ignore ) Json = Union[dict,",
"from YAML file to properties of self instance. Args: path: The path in",
"@dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool = False, only=None,",
"type_param = True else: type_param = False if field_value is None and not",
"else: pass init_kwargs[field.name] = field_value continue while True: if not _is_new_type(field_type): break field_type",
"import ABCMeta from dataclasses import dataclass from pathlib import Path from typing import",
"is found. res = type_(value) # FIXME this is a hack to fix",
"generation # code if is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type, field_value,",
"even more hacky # The only problem is the catch all field, we",
"k): v for k, v in kvs.items()} missing_fields = {field for field in",
"_decode_generic_subsets(type_, value, infer_missing): if value is None: res = value elif _issubclass_safe(type_, Enum):",
"a constructor. # Assumes a direct match is found. res = type_(value) #",
"depending on dump and load, which is even more hacky # The only",
"{warning} and was defaulted to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the",
"kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *,",
"subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']]",
"exclude=(), many: bool = False, context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None)",
"overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is a band-aid to deal with",
"= _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is None:",
"rewrap classmethod to tag it to cls rather than the literal # DataClassJsonMixin",
"InvalidTypeError(\"Configuration file must \" \"be in YAML format: %s\" % str(built_path)) else: raise",
"context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None) -> SchemaType: Schema = build_schema(cls,",
"cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls)",
"field.default is not MISSING: kvs[field.name] = field.default elif field.default_factory is not MISSING: kvs[field.name]",
"= schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}':",
"ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks,",
"schema # depending on dump and load, which is even more hacky #",
"Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump,",
"only problem is the catch all field, we can't statically create a schema",
"@dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if",
"FIXME this is a hack to fix a deeper underlying issue. A refactor",
"\"\"\" try: subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try:",
"_get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints,",
"of self instance. Args: path: The path in string form; can be relative",
"type {field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and",
"= _user_overrides_or_exts(cls) kvs = {} if kvs is None and infer_missing else kvs",
"= undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def",
"the catch all field, we can't statically create a schema for it #",
"config class.\"\"\" from abc import ABCMeta from dataclasses import dataclass from pathlib import",
"infer_missing): if value is None: res = value elif _issubclass_safe(type_, Enum): # Convert",
"{field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was",
"not _is_optional(field_type): warning = (f\"value of non-optional type {field.name} detected \" f\"when decoding",
"else: # Optional or Union if not hasattr(type_, \"__args__\"): # Any, just accept",
"is not MISSING: kvs[field.name] = field.default elif field.default_factory is not MISSING: kvs[field.name] =",
"= DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag it to cls rather",
"file to properties of self instance. Args: path: The path in string form;",
"implements abstract config class.\"\"\" from abc import ABCMeta from dataclasses import dataclass from",
"= zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value)",
"from being added # to init_kwargs as it's not intended as a constructor",
"below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined)",
"usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema',",
"is None and infer_missing else kvs field_names = [field.name for field in fields(cls)]",
"field.default elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] =",
"Convert to an Enum using the type as a constructor. # Assumes a",
"kvs = {decode_names.get(k, k): v for k, v in kvs.items()} missing_fields = {field",
"intended as a constructor argument. if not field.init: continue from typing import GenericMeta",
"all field, we can't statically create a schema for it # so we",
"= _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for field in",
"hacky # The only problem is the catch all field, we can't statically",
"subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError: raise",
"from typing import GenericMeta field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and",
"Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types",
"Undefined]] = None): \"\"\" Based on the code in the `dataclasses` module to",
"implements YAML file load function.\"\"\" def load(self, path: str, path_is_absolute: bool = False):",
"'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *,",
"or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value,",
"to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent this",
"class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\" def load(self, path:",
"(Any, Any)) # a mapping type has `.keys()` and `.values()` # (see collections.abc)",
"elif _issubclass_safe(type_, Enum): # Convert to an Enum using the type as a",
"_support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses import (MISSING,",
"many=many) # TODO This is hacky, but the other option I can think",
"fix a deeper underlying issue. A refactor is due. elif _is_collection(type_): if _is_mapping(type_):",
"constructor if using corresponding generic type in `typing` # otherwise fallback on constructing",
"str, path_is_absolute: bool = False): \"\"\" This method loads from YAML file to",
"DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool = False, only=None, exclude=(), many:",
"value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg,",
"= value elif _is_supported_generic(field_type) and field_type != str and not type_param: init_kwargs[field.name] =",
"file must \" \"be in YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No",
"@classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs,",
"\"__args__\", (Any, Any)) # a mapping type has `.keys()` and `.values()` # (see",
"MISSING: kvs[field.name] = field.default elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif",
"is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any))",
"not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\"",
"#180 # 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs,",
"_ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None): dumped = Schema.dump(self,",
"field in fields(cls): # The field should be skipped from being added #",
"if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to None by \" f\"infer_missing=True.",
"= overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is a band-aid to deal",
"refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any,",
"# type: ignore ) Json = Union[dict, list, str, int, float, bool, None]",
"to deal with the value already being # serialized when handling nested marshmallow",
"getSubclass(cls, values): \"\"\" In case one of the fields is called type, the",
"A from dataclasses import (MISSING, fields, is_dataclass # type: ignore ) Json =",
"the dumped dict if many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={},",
"elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value) else:",
"dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on the code",
"get_type_hints(cls) for field in fields(cls): # The field should be skipped from being",
"elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing)",
"kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None): dumped",
"issue. A refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_,",
"in fields(cls) if field.name not in kvs} for field in missing_fields: if field.default",
"dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing:",
"cls rather than the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict =",
"`.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(),",
"import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import",
"yaml import os import warnings from future.utils import raise_from from enum import Enum",
"field_type.__args__[0]!=str: type_param = 'type' in [f.name for f in fields(field_type.__args__[0])] elif 'type' in",
"# The field should be skipped from being added # to init_kwargs as",
"can be relative or absolute. path_is_absolute: indicates whether the path is an absolute",
"be relative or absolute. path_is_absolute: indicates whether the path is an absolute path",
"field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is None: res =",
"type as a constructor. # Assumes a direct match is found. res =",
"return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is not None or undefined",
"absolute. path_is_absolute: indicates whether the path is an absolute path \"\"\" path_type=Path(path) built_path",
"= {} types = get_type_hints(cls) for field in fields(cls): # The field should",
"function.\"\"\" def load(self, path: str, path_is_absolute: bool = False): \"\"\" This method loads",
"f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while True: if not _is_new_type(field_type):",
"schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping,",
"if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module':",
"**kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if 'cls' not in",
"obj, many=many) # TODO This is hacky, but the other option I can",
"_issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic,",
"field.name not in kvs} for field in missing_fields: if field.default is not MISSING:",
"int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin,",
"_handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls)",
"= types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name for f",
"decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for k, v in",
"AttributeError): res = type_(xs) else: # Optional or Union if not hasattr(type_, \"__args__\"):",
"and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type,",
"DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined",
"-> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for field in fields(cls) if",
"None or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json =",
"when handling nested marshmallow schema # proper fix is to investigate the marshmallow",
"= type_(xs) else: # Optional or Union if not hasattr(type_, \"__args__\"): # Any,",
"an Enum using the type as a constructor. # Assumes a direct match",
"None # Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs =",
"_is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder,",
"tuple(field.name for field in fields(cls) if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]),",
"'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag it to",
"update the dumped dict if many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj,",
"def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is None: return wrap return",
"classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a virtual subclass",
"value is None: res = value elif _issubclass_safe(type_, Enum): # Convert to an",
"loads from YAML file to properties of self instance. Args: path: The path",
"is to generate a different schema # depending on dump and load, which",
"dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A:",
"def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing)",
"\" \"be in YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No such file",
"dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A],",
"not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str",
"None: res = value elif _issubclass_safe(type_, Enum): # Convert to an Enum using",
"FIXME this is a band-aid to deal with the value already being #",
"field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module",
"2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg,",
"dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be in YAML format:",
"is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap",
"fields(cls) if field.name not in kvs} for field in missing_fields: if field.default is",
"kvs} for field in missing_fields: if field.default is not MISSING: kvs[field.name] = field.default",
"is None and not _is_optional(field_type): warning = (f\"value of non-optional type {field.name} detected",
"cls): return kvs overrides = _user_overrides_or_exts(cls) kvs = {} if kvs is None",
"!= str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and",
"import warnings from future.utils import raise_from from enum import Enum from marshmallow import",
"field_type = field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is not None): #",
"is a hack to fix a deeper underlying issue. A refactor is due.",
"else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value",
"# TODO #180 # 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return",
"yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be in YAML",
"zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) #",
"_decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type != str and",
") Json = Union[dict, list, str, int, float, bool, None] from pyspark_config.yamlConfig import",
"*args, **kwargs): if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args,",
"wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is not None or undefined is",
"in string form; can be relative or absolute. path_is_absolute: indicates whether the path",
"*, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on the code in",
"field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is a",
"Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing)",
"`.keys()` and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs =",
"== 2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res =",
"field_type != str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type)",
"field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing):",
"marshmallow schema generation # code if is_dataclass(field_value): value = field_value else: value =",
"= type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg):",
"of the fields is called type, the corresponding subclass is searched for. \"\"\"",
"a hack to fix a deeper underlying issue. A refactor is due. elif",
"\"__args__\"): # Any, just accept res = value elif _is_optional(type_) and len(type_.__args__) ==",
"res = value elif _is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg =",
"# serialized when handling nested marshmallow schema # proper fix is to investigate",
"load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) ->",
"if not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder",
"not None): # FIXME hack if field_type is type(field_value): init_kwargs[field.name] = field_value else:",
"and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return",
"except: raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass",
"path_is_absolute: indicates whether the path is an absolute path \"\"\" path_type=Path(path) built_path =",
"if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else:",
"just update the dumped dict if many: for i, _obj in enumerate(obj): dumped[i].update(",
"it # so we just update the dumped dict if many: for i,",
"load, which is even more hacky # The only problem is the catch",
"DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides",
"for field in fields(cls) if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), #",
"cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(),",
"for field in fields(cls) if field.name not in kvs} for field in missing_fields:",
"kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None # Perform undefined parameter action",
"in fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True else: type_param = False",
"is not None or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json']",
"= Schema.dump(self, obj, many=many) # TODO This is hacky, but the other option",
"`dataclasses` module to handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example:",
"due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) #",
"constructor argument. if not field.init: continue from typing import GenericMeta field_value = kvs[field.name]",
"the corresponding subclass is searched for. \"\"\" try: subclass_map = {subclass.type: subclass for",
"path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml)",
"res def getSubclass(cls, values): \"\"\" In case one of the fields is called",
"which is even more hacky # The only problem is the catch all",
"'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module }) @post_load",
"this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while True: if",
"instance. Args: path: The path in string form; can be relative or absolute.",
"f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod",
"Union[dict, list, str, int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def",
"Type[A], *, infer_missing: bool = False, only=None, exclude=(), many: bool = False, context=None,",
"= _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res",
"bool = False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if",
"and field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name]",
"return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is None: res = value",
"built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml:",
"res = value elif _issubclass_safe(type_, Enum): # Convert to an Enum using the",
"classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as",
"to init_kwargs as it's not intended as a constructor argument. if not field.init:",
"# unwrap and rewrap classmethod to tag it to cls rather than the",
"elif _is_supported_generic(field_type) and field_type != str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value,",
"_handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin,",
"else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) # get the",
"build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name",
"indicates whether the path is an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type,",
"def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on the",
"field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type):",
"return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool =",
"{cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to None by \"",
"cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs,",
"if many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj,",
"Union (already decoded or unsupported 'from_json' used) res = value return res def",
"YAML file to properties of self instance. Args: path: The path in string",
"from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema,",
"{'fields': tuple(field.name for field in fields(cls) if field.name != 'dataclass_json_config' and field.type !=",
"and infer_missing else kvs field_names = [field.name for field in fields(cls)] decode_names =",
"# FIXME hack if field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] =",
"field in missing_fields: if field.default is not MISSING: kvs[field.name] = field.default elif field.default_factory",
"fix is to investigate the marshmallow schema generation # code if is_dataclass(field_value): value",
"class Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is",
"CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items)",
"unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod",
"field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type'",
"import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema, schema) from",
"init_kwargs = {} types = get_type_hints(cls) for field in fields(cls): # The field",
"Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None): dumped = Schema.dump(self, obj, many=many)",
"letter_case, undefined) if _cls is None: return wrap return wrap(_cls) def _process_class(cls, letter_case,",
"`typing` # otherwise fallback on constructing using type_ itself try: res = _get_type_cons(type_)(xs)",
"# Optional or Union if not hasattr(type_, \"__args__\"): # Any, just accept res",
"False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is",
"Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls)",
"dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined",
"direct match is found. res = type_(value) # FIXME this is a hack",
"\"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is None: return wrap",
"return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A],",
"from typing import (Any, Union,Type, Optional) import yaml import os import warnings from",
"if field.default is not MISSING: kvs[field.name] = field.default elif field.default_factory is not MISSING:",
"= _support_extended_types(type_arg, value) else: # Union (already decoded or unsupported 'from_json' used) res",
"missing_fields: if field.default is not MISSING: kvs[field.name] = field.default elif field.default_factory is not",
"raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class",
"an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'):",
"except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class",
"YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\" def load(self, path: str,",
"field.init: continue from typing import GenericMeta field_value = kvs[field.name] field_type = types[field.name] if",
"infer_missing) else: res = _support_extended_types(type_arg, value) else: # Union (already decoded or unsupported",
"for k, v in kvs.items()} missing_fields = {field for field in fields(cls) if",
"kvs field_names = [field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs",
"import (Any, Union,Type, Optional) import yaml import os import warnings from future.utils import",
"= False, only=None, exclude=(), many: bool = False, context=None, load_only=(), dump_only=(), partial: bool",
"False, only=None, exclude=(), many: bool = False, context=None, load_only=(), dump_only=(), partial: bool =",
"def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs",
"_handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for field in fields(cls):",
"(already decoded or unsupported 'from_json' used) res = value return res def getSubclass(cls,",
"and not _is_optional(field_type): warning = (f\"value of non-optional type {field.name} detected \" f\"when",
"Schema.dump(self, obj, many=many) # TODO This is hacky, but the other option I",
"# Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value,",
"string form; can be relative or absolute. path_is_absolute: indicates whether the path is",
"# FIXME this is a band-aid to deal with the value already being",
"only=None, exclude=(), many: bool = False, context=None, load_only=(), dump_only=(), partial: bool = False,",
"we can't statically create a schema for it # so we just update",
"Optional or Union if not hasattr(type_, \"__args__\"): # Any, just accept res =",
"not hasattr(type_, \"__args__\"): # Any, just accept res = value elif _is_optional(type_) and",
"(), {'fields': tuple(field.name for field in fields(cls) if field.name != 'dataclass_json_config' and field.type",
"path: The path in string form; can be relative or absolute. path_is_absolute: indicates",
"in field_names: type_param = True else: type_param = False if field_value is None",
"return kvs overrides = _user_overrides_or_exts(cls) kvs = {} if kvs is None and",
"bool = False, only=None, exclude=(), many: bool = False, context=None, load_only=(), dump_only=(), partial:",
"for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v",
"_decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name] =",
"DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema =",
"cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag it to cls",
"False if field_value is None and not _is_optional(field_type): warning = (f\"value of non-optional",
"str, int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A],",
"* from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType,",
"dump_only=(), partial: bool = False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing,",
"Based on the code in the `dataclasses` module to handle optional-parens decorators. See",
"import GenericMeta field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param",
"RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while True: if not _is_new_type(field_type): break",
"constructing using type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res =",
"else: raise NotFoundError(\"No such file or directory: %s\" % str(built_path)) self.__dict__.update( self.schema().load(dictionary_config).__dict__ )",
"for it # so we just update the dumped dict if many: for",
"with the value already being # serialized when handling nested marshmallow schema #",
"dumped = Schema.dump(self, obj, many=many) # TODO This is hacky, but the other",
"kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type(",
"being added # to init_kwargs as it's not intended as a constructor argument.",
"(see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs",
"generic type in `typing` # otherwise fallback on constructing using type_ itself try:",
"{} types = get_type_hints(cls) for field in fields(cls): # The field should be",
"infer_missing) xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v",
"# TODO This is hacky, but the other option I can think of",
"= {field for field in fields(cls) if field.name not in kvs} for field",
"infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value,",
"\"be in YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No such file or",
"obj, *, many=None): dumped = Schema.dump(self, obj, many=many) # TODO This is hacky,",
"create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta',",
"_process_class(cls, letter_case, undefined) if _cls is None: return wrap return wrap(_cls) def _process_class(cls,",
"_decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res =",
"path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file",
"it's not intended as a constructor argument. if not field.init: continue from typing",
"(Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass",
"Meta = type('Meta', (), {'fields': tuple(field.name for field in fields(cls) if field.name !=",
"create a schema for it # so we just update the dumped dict",
"cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a virtual subclass of",
"\"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8')",
"def schema(cls: Type[A], *, infer_missing: bool = False, only=None, exclude=(), many: bool =",
"not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None # Perform undefined",
"cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod",
"@classmethod def schema(cls: Type[A], *, infer_missing: bool = False, only=None, exclude=(), many: bool",
"schema generation # code if is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type,",
"{decode_names.get(k, k): v for k, v in kvs.items()} missing_fields = {field for field",
"continue while True: if not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in",
"code in the `dataclasses` module to handle optional-parens decorators. See example below: @dataclass_json",
"match is found. res = type_(value) # FIXME this is a hack to",
"example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case,",
"_decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else:",
"= _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We can just make use",
"context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False)",
"in missing_fields: if field.default is not MISSING: kvs[field.name] = field.default elif field.default_factory is",
"on dump and load, which is even more hacky # The only problem",
"to cls rather than the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict",
"Any)) # a mapping type has `.keys()` and `.values()` # (see collections.abc) ks",
"case one of the fields is called type, the corresponding subclass is searched",
"a direct match is found. res = type_(value) # FIXME this is a",
"[f.name for f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True else:",
"load(self, path: str, path_is_absolute: bool = False): \"\"\" This method loads from YAML",
"from dataclasses_json.api import A from dataclasses import (MISSING, fields, is_dataclass # type: ignore",
"decoded or unsupported 'from_json' used) res = value return res def getSubclass(cls, values):",
"method loads from YAML file to properties of self instance. Args: path: The",
"_is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses import",
"infer_missing: kvs[field.name] = None # Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs,",
"and field_type.__args__[0]!=str: type_param = 'type' in [f.name for f in fields(field_type.__args__[0])] elif 'type'",
"_is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) # a mapping type has",
"of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return",
"= {decode_names.get(k, k): v for k, v in kvs.items()} missing_fields = {field for",
"# code if is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type, field_value, infer_missing)",
"\" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent this \" f\"behavior.\", RuntimeWarning)",
"as a constructor. # Assumes a direct match is found. res = type_(value)",
"for. \"\"\" try: subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise",
"import post_load, Schema from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg",
"subclass is searched for. \"\"\" try: subclass_map = {subclass.type: subclass for subclass in",
"import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons,",
"generate a different schema # depending on dump and load, which is even",
"pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta",
"field_names = [field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs =",
"_is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is not",
"if field.name not in kvs} for field in missing_fields: if field.default is not",
"import yaml import os import warnings from future.utils import raise_from from enum import",
"Optional[Union[str, Undefined]] = None): \"\"\" Based on the code in the `dataclasses` module",
"v for k, v in kvs.items()} missing_fields = {field for field in fields(cls)",
"this is a band-aid to deal with the value already being # serialized",
"Enum using the type as a constructor. # Assumes a direct match is",
"# (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing)",
"_is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or",
"in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_",
"False): \"\"\" This method loads from YAML file to properties of self instance.",
"else: type_param = False if field_value is None and not _is_optional(field_type): warning =",
"# FIXME this is a hack to fix a deeper underlying issue. A",
"We can just make use of the same-named mm keywords unknown = undefined_parameter_action.name.lower()",
"format: %s\" % str(built_path)) else: raise NotFoundError(\"No such file or directory: %s\" %",
"Schema from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config",
"ABCMeta from dataclasses import dataclass from pathlib import Path from typing import (Any,",
"to handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\"",
"None and infer_missing else kvs field_names = [field.name for field in fields(cls)] decode_names",
"continue from typing import GenericMeta field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type)",
"kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if 'cls' not",
"I can think of is to generate a different schema # depending on",
"field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is not None): # FIXME hack",
"type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME",
"already being # serialized when handling nested marshmallow schema # proper fix is",
"for v in value) # get the constructor if using corresponding generic type",
"bool = False, context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None) -> SchemaType:",
"_support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is None: res",
"wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is not None or",
"is to investigate the marshmallow schema generation # code if is_dataclass(field_value): value =",
"in `typing` # otherwise fallback on constructing using type_ itself try: res =",
"on constructing using type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res",
"_undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We can just make use of",
"load function.\"\"\" def load(self, path: str, path_is_absolute: bool = False): \"\"\" This method",
"pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm",
"letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on the code in the",
"if is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] =",
"str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0]",
"type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif",
"field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module }) @post_load def make_instance(self,",
"the other option I can think of is to generate a different schema",
"undefined_parameter_action is not None: # We can just make use of the same-named",
"= _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value) else: # Union (already",
"if letter_case is not None or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case,",
"get the constructor if using corresponding generic type in `typing` # otherwise fallback",
"to properties of self instance. Args: path: The path in string form; can",
"= type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_})",
"a deeper underlying issue. A refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type,",
"{subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError:",
"A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] =",
"Json = Union[dict, list, str, int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field,",
"available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\" def",
"band-aid to deal with the value already being # serialized when handling nested",
"is not None: # We can just make use of the same-named mm",
"kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs = {}",
"= field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is",
"corresponding generic type in `typing` # otherwise fallback on constructing using type_ itself",
"import config from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from",
"_decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses import (MISSING, fields, is_dataclass #",
"dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls,",
"use of the same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many,",
"as it's not intended as a constructor argument. if not field.init: continue from",
"pass init_kwargs[field.name] = field_value continue while True: if not _is_new_type(field_type): break field_type =",
"True: if not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in overrides and",
"undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag it",
"added # to init_kwargs as it's not intended as a constructor argument. if",
"See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return _process_class(cls,",
"in [f.name for f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True",
"option I can think of is to generate a different schema # depending",
"init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def",
"type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else:",
"*, many=None): dumped = Schema.dump(self, obj, many=many) # TODO This is hacky, but",
"# register cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def",
"relative or absolute. path_is_absolute: indicates whether the path is an absolute path \"\"\"",
"import os import warnings from future.utils import raise_from from enum import Enum from",
"in kvs} for field in missing_fields: if field.default is not MISSING: kvs[field.name] =",
"_support_extended_types(type_arg, value) else: # Union (already decoded or unsupported 'from_json' used) res =",
"return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None):",
"res = value return res def getSubclass(cls, values): \"\"\" In case one of",
"from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]:",
"by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent this \" f\"behavior.\",",
"_decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\"",
"schema # proper fix is to investigate the marshmallow schema generation # code",
"than the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict",
"to tag it to cls rather than the literal # DataClassJsonMixin ABC cls.from_json",
"The only problem is the catch all field, we can't statically create a",
"not field.init: continue from typing import GenericMeta field_value = kvs[field.name] field_type = types[field.name]",
"(the default) to prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value",
"be skipped from being added # to init_kwargs as it's not intended as",
"absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with",
"DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump':",
"so we just update the dumped dict if many: for i, _obj in",
"make use of the same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude,",
"can just make use of the same-named mm keywords unknown = undefined_parameter_action.name.lower() return",
"schema for it # so we just update the dumped dict if many:",
"build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection,",
"is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): #",
"literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__)",
"config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag",
"types = get_type_hints(cls) for field in fields(cls): # The field should be skipped",
"import dataclass from pathlib import Path from typing import (Any, Union,Type, Optional) import",
"and overrides[field.name].decoder is not None): # FIXME hack if field_type is type(field_value): init_kwargs[field.name]",
"letter_case, undefined): if letter_case is not None or undefined is not None: cls.dataclass_json_config",
"= field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type)",
"partial: bool = False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial)",
"keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown)",
"and len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value):",
"Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None,",
"using type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs)",
"to investigate the marshmallow schema generation # code if is_dataclass(field_value): value = field_value",
"module to handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ...",
"mapping type has `.keys()` and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(),",
"self instance. Args: path: The path in string form; can be relative or",
"= _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for k, v in kvs.items()}",
"undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types =",
"value elif _is_supported_generic(field_type) and field_type != str and not type_param: init_kwargs[field.name] = _decode_generic(field_type,",
"kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for field in fields(cls): #",
"vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) # get",
"getattr(type_, \"__args__\", (Any, Any)) # a mapping type has `.keys()` and `.values()` #",
"dataclass from pathlib import Path from typing import (Any, Union,Type, Optional) import yaml",
"k, v in kvs.items()} missing_fields = {field for field in fields(cls) if field.name",
"Enum): # Convert to an Enum using the type as a constructor. #",
"future.utils import raise_from from enum import Enum from marshmallow import post_load, Schema from",
"partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A: return",
"import (MISSING, fields, is_dataclass # type: ignore ) Json = Union[dict, list, str,",
"# to init_kwargs as it's not intended as a constructor argument. if not",
"warnings.warn( f\"Missing {warning} and was defaulted to None by \" f\"infer_missing=True. \" f\"Set",
"vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v),",
"A refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\",",
"\"\"\" In case one of the fields is called type, the corresponding subclass",
"in kvs.items()} missing_fields = {field for field in fields(cls) if field.name not in",
"**schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool",
"field_value) elif is_dataclass(field_type): # FIXME this is a band-aid to deal with the",
"unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls,",
"dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional,",
"_is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name for f in fields(field_type.__args__[0])] elif",
"path is an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path):",
"overrides = _user_overrides_or_exts(cls) kvs = {} if kvs is None and infer_missing else",
"# Any, just accept res = value elif _is_optional(type_) and len(type_.__args__) == 2:",
"Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file",
"class implements YAML file load function.\"\"\" def load(self, path: str, path_is_absolute: bool =",
"_process_class(cls, letter_case, undefined): if letter_case is not None or undefined is not None:",
"values): \"\"\" In case one of the fields is called type, the corresponding",
"TODO #180 # 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls,",
"from dataclasses import dataclass from pathlib import Path from typing import (Any, Union,Type,",
"get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from",
"usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema:",
"try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix,",
"from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import",
"None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We can just",
"a different schema # depending on dump and load, which is even more",
"for field in missing_fields: if field.default is not MISSING: kvs[field.name] = field.default elif",
"f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to None",
"This is hacky, but the other option I can think of is to",
"undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls:",
"is an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if",
"None and not _is_optional(field_type): warning = (f\"value of non-optional type {field.name} detected \"",
"type has `.keys()` and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing)",
"field in fields(cls) if field.name not in kvs} for field in missing_fields: if",
"wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is None: return wrap return wrap(_cls)",
"cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__",
"return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None): dumped = Schema.dump(self, obj,",
"kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing)",
"abc import ABCMeta from dataclasses import dataclass from pathlib import Path from typing",
"= _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *, many=None): dumped =",
"value already being # serialized when handling nested marshmallow schema # proper fix",
"for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\"))",
"in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj, *,",
"YAML file load function.\"\"\" def load(self, path: str, path_is_absolute: bool = False): \"\"\"",
"itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else: #",
"a constructor argument. if not field.init: continue from typing import GenericMeta field_value =",
"if value is None: res = value elif _issubclass_safe(type_, Enum): # Convert to",
"infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on",
"load_only=(), dump_only=(), partial: bool = False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix,",
"field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and",
"try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else: # Optional",
"%s\" % str(built_path)) else: raise NotFoundError(\"No such file or directory: %s\" % str(built_path))",
"@post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs):",
"kvs=(), usage=\"init\") # register cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return",
"the `dataclasses` module to handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class",
"subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This",
"dataclasses_json.api import A from dataclasses import (MISSING, fields, is_dataclass # type: ignore )",
"global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self,",
"elif is_dataclass(field_type): # FIXME this is a band-aid to deal with the value",
"defaulted to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent",
"register cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls,",
"@dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\" def load(self,",
"= _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a virtual subclass of DataClassJsonMixin",
"isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs = {} if kvs is",
"= (f\"value of non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing:",
"= {} if kvs is None and infer_missing else kvs field_names = [field.name",
"using corresponding generic type in `typing` # otherwise fallback on constructing using type_",
"raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML",
"def _process_class(cls, letter_case, undefined): if letter_case is not None or undefined is not",
"field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None #",
"infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to None by \" f\"infer_missing=True. \"",
"value, infer_missing): if value is None: res = value elif _issubclass_safe(type_, Enum): #",
"\" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to",
"and was defaulted to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default)",
"= DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\")",
"infer_missing: bool = False, only=None, exclude=(), many: bool = False, context=None, load_only=(), dump_only=(),",
"res = _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else: # Optional or",
"whether the path is an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute)",
"from marshmallow import post_load, Schema from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin",
"infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if",
"_is_optional(field_type): warning = (f\"value of non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\")",
"= _get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else: # Optional or Union",
"subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\"",
"_is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic,",
"if _cls is None: return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if",
"# 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial)",
"= None # Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs",
"typing import GenericMeta field_value = kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str:",
"properties of self instance. Args: path: The path in string form; can be",
"unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We",
"serialized when handling nested marshmallow schema # proper fix is to investigate the",
"skipped from being added # to init_kwargs as it's not intended as a",
"str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value)",
"DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") #",
"cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is None: res = value elif",
"% str(built_path)) else: raise NotFoundError(\"No such file or directory: %s\" % str(built_path)) self.__dict__.update(",
"type('Meta', (), {'fields': tuple(field.name for field in fields(cls) if field.name != 'dataclass_json_config' and",
"to fix a deeper underlying issue. A refactor is due. elif _is_collection(type_): if",
"corresponding subclass is searched for. \"\"\" try: subclass_map = {subclass.type: subclass for subclass",
"schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta,",
"*args, **kwargs) def dump(self, obj, *, many=None): dumped = Schema.dump(self, obj, many=many) #",
"def _decode_generic_subsets(type_, value, infer_missing): if value is None: res = value elif _issubclass_safe(type_,",
"typing import (Any, Union,Type, Optional) import yaml import os import warnings from future.utils",
"**kwargs): if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs)",
"[field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k):",
"= Union[dict, list, str, int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path",
"letter_case is not None or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[",
"warning = (f\"value of non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\") if",
"investigate the marshmallow schema generation # code if is_dataclass(field_value): value = field_value else:",
"infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type != str and not type_param:",
"_decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs =",
"i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else: dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return",
"it to cls rather than the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__)",
"problem is the catch all field, we can't statically create a schema for",
"dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api",
"mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial,",
"is None: return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is",
"was defaulted to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to",
"fields is called type, the corresponding subclass is searched for. \"\"\" try: subclass_map",
"# get the constructor if using corresponding generic type in `typing` # otherwise",
"def load(self, path: str, path_is_absolute: bool = False): \"\"\" This method loads from",
"path in string form; can be relative or absolute. path_is_absolute: indicates whether the",
"make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def",
"= config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap classmethod to",
"is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We can",
"infer_missing, partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not",
"otherwise fallback on constructing using type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError,",
"v in value) # get the constructor if using corresponding generic type in",
"is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing)",
"os import warnings from future.utils import raise_from from enum import Enum from marshmallow",
"for field in fields(cls): # The field should be skipped from being added",
"field.default_factory() elif infer_missing: kvs[field.name] = None # Perform undefined parameter action kvs =",
"_decode_items) from dataclasses_json.api import A from dataclasses import (MISSING, fields, is_dataclass # type:",
"infer_missing): if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs = {} if",
"{} if kvs is None and infer_missing else kvs field_names = [field.name for",
"kvs[field.name] = None # Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\")",
"is the catch all field, we can't statically create a schema for it",
"config from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils",
"not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is",
"k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) # a mapping type has `.keys()`",
"kvs overrides = _user_overrides_or_exts(cls) kvs = {} if kvs is None and infer_missing",
"elif infer_missing: kvs[field.name] = None # Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls,",
"schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance,",
"from pathlib import Path from typing import (Any, Union,Type, Optional) import yaml import",
"kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for field",
"called type, the corresponding subclass is searched for. \"\"\" try: subclass_map = {subclass.type:",
"_decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if 'cls' not in kwargs: kwargs['cls']",
"value return res def getSubclass(cls, values): \"\"\" In case one of the fields",
"dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core",
"_is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else:",
"(TypeError, AttributeError): res = type_(xs) else: # Optional or Union if not hasattr(type_,",
"= build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config",
"= value elif _is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0]",
"else: res = _support_extended_types(type_arg, value) else: # Union (already decoded or unsupported 'from_json'",
"to an Enum using the type as a constructor. # Assumes a direct",
"Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar)",
"None): \"\"\" Based on the code in the `dataclasses` module to handle optional-parens",
"(SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe,",
"from dataclasses_json.mm import (SchemaType, build_schema, schema) from dataclasses_json.undefined import Undefined from dataclasses_json.utils import",
"DataClassJsonMix.to_json # unwrap and rewrap classmethod to tag it to cls rather than",
"classmethod to tag it to cls rather than the literal # DataClassJsonMixin ABC",
"class.\"\"\" from abc import ABCMeta from dataclasses import dataclass from pathlib import Path",
"return cls def _decode_dataclass(cls, kvs, infer_missing): if isinstance(kvs, cls): return kvs overrides =",
"infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value)",
"elif _is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg)",
"def dumps(self, *args, **kwargs): if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return",
"can think of is to generate a different schema # depending on dump",
"undefined): if letter_case is not None or undefined is not None: cls.dataclass_json_config =",
"make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if 'cls'",
"import Path from typing import (Any, Union,Type, Optional) import yaml import os import",
"= False, context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None) -> SchemaType: Schema",
"kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based",
"\"\"\" Based on the code in the `dataclasses` module to handle optional-parens decorators.",
"# DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema",
"hacky, but the other option I can think of is to generate a",
"!= str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type,",
"elif _is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) # a",
"value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else: xs",
"marshmallow import post_load, Schema from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from",
"dataclasses import (MISSING, fields, is_dataclass # type: ignore ) Json = Union[dict, list,",
"init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is a band-aid to",
"= type_(value) # FIXME this is a hack to fix a deeper underlying",
"return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is not None",
"searched for. \"\"\" try: subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except:",
"if field_value is None and not _is_optional(field_type): warning = (f\"value of non-optional type",
"but the other option I can think of is to generate a different",
"xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in",
"= field.default_factory() elif infer_missing: kvs[field.name] = None # Perform undefined parameter action kvs",
"if kvs is None and infer_missing else kvs field_names = [field.name for field",
"type_param = 'type' in [f.name for f in fields(field_type.__args__[0])] elif 'type' in field_names:",
"Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for field in fields(cls) if field.name",
"this is a hack to fix a deeper underlying issue. A refactor is",
"= _decode_dict_keys(k_type, value.keys(), infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs)",
"not None: # We can just make use of the same-named mm keywords",
"= classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a virtual",
"<reponame>Patrizio1301/pyspark-config \"\"\"This module implements abstract config class.\"\"\" from abc import ABCMeta from dataclasses",
"!= 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module })",
"if not field.init: continue from typing import GenericMeta field_value = kvs[field.name] field_type =",
"kvs is None and infer_missing else kvs field_names = [field.name for field in",
"float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing,",
"overrides[field.name].decoder is not None): # FIXME hack if field_type is type(field_value): init_kwargs[field.name] =",
"pathlib import Path from typing import (Any, Union,Type, Optional) import yaml import os",
"Union,Type, Optional) import yaml import os import warnings from future.utils import raise_from from",
"\"\"\" This method loads from YAML file to properties of self instance. Args:",
"infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for field in",
"overrides) kvs = {decode_names.get(k, k): v for k, v in kvs.items()} missing_fields =",
"we just update the dumped dict if many: for i, _obj in enumerate(obj):",
"non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning}",
"return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if 'cls' not in kwargs:",
"decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls): return",
"should be skipped from being added # to init_kwargs as it's not intended",
"_is_supported_generic(field_type) and field_type != str and not type_param: init_kwargs[field.name] = _decode_generic(field_type, field_value, infer_missing)",
"This method loads from YAML file to properties of self instance. Args: path:",
"just make use of the same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only,",
"None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and rewrap",
"_is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys,",
"The field should be skipped from being added # to init_kwargs as it's",
"kvs[field.name] field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name",
"res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else:",
"res = type_(value) # FIXME this is a hack to fix a deeper",
"accept res = value elif _is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg",
"_is_supported_generic(type_arg): res = _decode_generic(type_arg, value, infer_missing) else: res = _support_extended_types(type_arg, value) else: #",
"rather than the literal # DataClassJsonMixin ABC cls.from_json = classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict",
"marshmallow schema # proper fix is to investigate the marshmallow schema generation #",
"return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta):",
"None: return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case is not",
"usage=\"init\") # register cls as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls",
"init_kwargs[field.name] = field_value continue while True: if not _is_new_type(field_type): break field_type = field_type.__supertype__",
"action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for",
"raise InvalidTypeError(\"Configuration file must \" \"be in YAML format: %s\" % str(built_path)) else:",
"not MISSING: kvs[field.name] = field.default elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory()",
"xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) # get the constructor",
"= value return res def getSubclass(cls, values): \"\"\" In case one of the",
"from dataclasses_json.utils import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from",
"not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json # unwrap and",
"_decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for k, v in kvs.items()} missing_fields",
"try: subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()} except: raise try: return",
"from_dict(cls: Type[A], kvs: Json, *, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def",
"from abc import ABCMeta from dataclasses import dataclass from pathlib import Path from",
"if not hasattr(type_, \"__args__\"): # Any, just accept res = value elif _is_optional(type_)",
"Path from typing import (Any, Union,Type, Optional) import yaml import os import warnings",
"v_type = getattr(type_, \"__args__\", (Any, Any)) # a mapping type has `.keys()` and",
"is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res = _decode_generic(type_arg,",
"# Assumes a direct match is found. res = type_(value) # FIXME this",
"field_names: type_param = True else: type_param = False if field_value is None and",
"using the type as a constructor. # Assumes a direct match is found.",
"v in kvs.items()} missing_fields = {field for field in fields(cls) if field.name not",
"for subclass in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type",
"infer_missing) vs = _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else: xs =",
"kvs = {} if kvs is None and infer_missing else kvs field_names =",
"is even more hacky # The only problem is the catch all field,",
"schema(cls: Type[A], *, infer_missing: bool = False, only=None, exclude=(), many: bool = False,",
"= False if field_value is None and not _is_optional(field_type): warning = (f\"value of",
"break field_type = field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is not None):",
"mixin, infer_missing) DataClassSchema: Type[SchemaType] = type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps':",
"undefined: Optional[Union[str, Undefined]] = None): \"\"\" Based on the code in the `dataclasses`",
"{'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class",
"mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields': tuple(field.name for field",
"Union if not hasattr(type_, \"__args__\"): # Any, just accept res = value elif",
"_ExtendedEncoder, _decode_generic, _decode_items) from dataclasses_json.api import A from dataclasses import (MISSING, fields, is_dataclass",
"fields, is_dataclass # type: ignore ) Json = Union[dict, list, str, int, float,",
"None by \" f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent this \"",
"deeper underlying issue. A refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type",
"is searched for. \"\"\" try: subclass_map = {subclass.type: subclass for subclass in cls.__args__[0].__subclasses__()}",
"field_value continue while True: if not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name",
"'from_json' used) res = value return res def getSubclass(cls, values): \"\"\" In case",
"argument. if not field.init: continue from typing import GenericMeta field_value = kvs[field.name] field_type",
"in fields(cls): # The field should be skipped from being added # to",
"with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must",
"None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) ->",
"fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for k, v",
"if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration",
"Optional) import yaml import os import warnings from future.utils import raise_from from enum",
"handling nested marshmallow schema # proper fix is to investigate the marshmallow schema",
"_issubclass_safe(type_, Enum): # Convert to an Enum using the type as a constructor.",
"bool = False): \"\"\" This method loads from YAML file to properties of",
"(field.name in overrides and overrides[field.name].decoder is not None): # FIXME hack if field_type",
"= _decode_generic(field_type, field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name]",
"= True else: type_param = False if field_value is None and not _is_optional(field_type):",
"if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) # a mapping type",
"is a band-aid to deal with the value already being # serialized when",
"dumps(self, *args, **kwargs): if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self,",
"if field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif",
"in overrides and overrides[field.name].decoder is not None): # FIXME hack if field_type is",
"code if is_dataclass(field_value): value = field_value else: value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name]",
"yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be in YAML format: %s\" %",
"in fields(cls) if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180",
"'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls:",
"a mapping type has `.keys()` and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type,",
"fields(cls) if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO #180 #",
"has `.keys()` and `.values()` # (see collections.abc) ks = _decode_dict_keys(k_type, value.keys(), infer_missing) vs",
"cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not available.\")",
"(Any, Union,Type, Optional) import yaml import os import warnings from future.utils import raise_from",
"else kvs field_names = [field.name for field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides)",
"value) # get the constructor if using corresponding generic type in `typing` #",
"= _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type != str",
"_decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value,",
"except (TypeError, AttributeError): res = type_(xs) else: # Optional or Union if not",
"in the `dataclasses` module to handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL)",
"is called type, the corresponding subclass is searched for. \"\"\" try: subclass_map =",
"many: bool = False, context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None) ->",
"and load, which is even more hacky # The only problem is the",
"KeyError: raise Exception(\"Type \"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements",
"= type('Meta', (), {'fields': tuple(field.name for field in fields(cls) if field.name != 'dataclass_json_config'",
"DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is",
"enum import Enum from marshmallow import post_load, Schema from pyspark_config.errors import * from",
"field in fields(cls) if field.name != 'dataclass_json_config' and field.type != Optional[CatchAllVar]), # TODO",
"decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted to None by",
"warnings from future.utils import raise_from from enum import Enum from marshmallow import post_load,",
"if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def",
"if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res =",
"type: ignore ) Json = Union[dict, list, str, int, float, bool, None] from",
"v, infer_missing) for v in value) # get the constructor if using corresponding",
"in cls.__args__[0].__subclasses__()} except: raise try: return subclass_map[values['type']] except KeyError: raise Exception(\"Type \"+values['type']+\" not",
"type_param = False if field_value is None and not _is_optional(field_type): warning = (f\"value",
"def getSubclass(cls, values): \"\"\" In case one of the fields is called type,",
"same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only,",
"build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action",
"on the code in the `dataclasses` module to handle optional-parens decorators. See example",
"from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types, _decode_dict_keys, _ExtendedEncoder, _decode_generic, _decode_items) from",
"# so we just update the dumped dict if many: for i, _obj",
"build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (),",
"= _decode_items(v_type, value.values(), infer_missing) xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v,",
"*, infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined:",
"or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json",
"usage=\"from\") init_kwargs = {} types = get_type_hints(cls) for field in fields(cls): # The",
"field_type = types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name for",
"a schema for it # so we just update the dumped dict if",
"types[field.name] if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name for f in",
"\" f\"Set infer_missing=False (the default) to prevent this \" f\"behavior.\", RuntimeWarning) else: pass",
"# a mapping type has `.keys()` and `.values()` # (see collections.abc) ks =",
"Assumes a direct match is found. res = type_(value) # FIXME this is",
"metaclass=ABCMeta): \"\"\"This class implements YAML file load function.\"\"\" def load(self, path: str, path_is_absolute:",
"Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs:",
"if _is_supported_generic(field_type) and field_type.__args__[0]!=str: type_param = 'type' in [f.name for f in fields(field_type.__args__[0])]",
"bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial)",
"partial) def dumps(self, *args, **kwargs): if 'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder",
"# We can just make use of the same-named mm keywords unknown =",
"if using corresponding generic type in `typing` # otherwise fallback on constructing using",
"type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res = _decode_dataclass(type_arg, value, infer_missing) elif _is_supported_generic(type_arg): res",
"fallback on constructing using type_ itself try: res = _get_type_cons(type_)(xs) except (TypeError, AttributeError):",
"# The only problem is the catch all field, we can't statically create",
"False, context=None, load_only=(), dump_only=(), partial: bool = False, unknown=None) -> SchemaType: Schema =",
"hack if field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value)",
"= getattr(type_, \"__args__\", (Any, Any)) # a mapping type has `.keys()` and `.values()`",
"res = _support_extended_types(type_arg, value) else: # Union (already decoded or unsupported 'from_json' used)",
"field_value is None and not _is_optional(field_type): warning = (f\"value of non-optional type {field.name}",
"many=None): dumped = Schema.dump(self, obj, many=many) # TODO This is hacky, but the",
"type, the corresponding subclass is searched for. \"\"\" try: subclass_map = {subclass.type: subclass",
"type_(xs) else: # Optional or Union if not hasattr(type_, \"__args__\"): # Any, just",
"build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config =",
"_is_collection(type_): if _is_mapping(type_): k_type, v_type = getattr(type_, \"__args__\", (Any, Any)) # a mapping",
"_is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides, _is_supported_generic, _support_extended_types,",
"= _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_,",
"and rewrap classmethod to tag it to cls rather than the literal #",
"dumped.update(_handle_undefined_parameters_safe(cls=obj, kvs={}, usage=\"dump\")) return dumped schema_ = schema(cls, mixin, infer_missing) DataClassSchema: Type[SchemaType] =",
"used) res = value return res def getSubclass(cls, values): \"\"\" In case one",
"if undefined_parameter_action is not None: # We can just make use of the",
"None: # We can just make use of the same-named mm keywords unknown",
"the path is an absolute path \"\"\" path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if",
"found. res = type_(value) # FIXME this is a hack to fix a",
"in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for k,",
"(_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts,",
"the fields is called type, the corresponding subclass is searched for. \"\"\" try:",
"of the same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context,",
"_get_type_cons(type_)(xs) except (TypeError, AttributeError): res = type_(xs) else: # Optional or Union if",
"The path in string form; can be relative or absolute. path_is_absolute: indicates whether",
"is_dataclass(field_type): # FIXME this is a band-aid to deal with the value already",
"os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise",
"default) to prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue",
"# proper fix is to investigate the marshmallow schema generation # code if",
"'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def",
"infer_missing) for v in value) # get the constructor if using corresponding generic",
"or absolute. path_is_absolute: indicates whether the path is an absolute path \"\"\" path_type=Path(path)",
"_cls is None: return wrap return wrap(_cls) def _process_class(cls, letter_case, undefined): if letter_case",
"from future.utils import raise_from from enum import Enum from marshmallow import post_load, Schema",
"tag it to cls rather than the literal # DataClassJsonMixin ABC cls.from_json =",
"not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self, obj,",
"(f\"value of non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn(",
"DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin): @classmethod def schema(cls: Type[A], *, infer_missing: bool = False,",
"to generate a different schema # depending on dump and load, which is",
"dict if many: for i, _obj in enumerate(obj): dumped[i].update( _handle_undefined_parameters_safe(cls=_obj, kvs={}, usage=\"dump\")) else:",
"not None or undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json",
"f in fields(field_type.__args__[0])] elif 'type' in field_names: type_param = True else: type_param =",
"in YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No such file or directory:",
"if unknown is None: undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: #",
"init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs) def _decode_generic_subsets(type_, value, infer_missing): if value is",
"abstract config class.\"\"\" from abc import ABCMeta from dataclasses import dataclass from pathlib",
"optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def wrap(cls):",
"Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return DataClassSchema @dataclass class DataClassJsonMix(DataClassJsonMixin):",
"def make_instance(self, kvs, **kwargs): return _decode_dataclass(cls, kvs, partial) def dumps(self, *args, **kwargs): if",
"raise_from from enum import Enum from marshmallow import post_load, Schema from pyspark_config.errors import",
"# Convert to an Enum using the type as a constructor. # Assumes",
"to prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while",
"undefined_parameter_action = _undefined_parameter_action_safe(cls) if undefined_parameter_action is not None: # We can just make",
"else: raise InvalidTypeError(\"Configuration file must \" \"be in YAML format: %s\" % str(built_path))",
"think of is to generate a different schema # depending on dump and",
"infer_missing=False) -> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str,",
"while True: if not _is_new_type(field_type): break field_type = field_type.__supertype__ if (field.name in overrides",
"the constructor if using corresponding generic type in `typing` # otherwise fallback on",
"'cls' not in kwargs: kwargs['cls'] = _ExtendedEncoder return Schema.dumps(self, *args, **kwargs) def dump(self,",
"In case one of the fields is called type, the corresponding subclass is",
"if isinstance(kvs, cls): return kvs overrides = _user_overrides_or_exts(cls) kvs = {} if kvs",
"str(built_path)) else: raise NotFoundError(\"No such file or directory: %s\" % str(built_path)) self.__dict__.update( self.schema().load(dictionary_config).__dict__",
"prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] = field_value continue while True:",
"True else: type_param = False if field_value is None and not _is_optional(field_type): warning",
"the value already being # serialized when handling nested marshmallow schema # proper",
"nested marshmallow schema # proper fix is to investigate the marshmallow schema generation",
"= False, unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown",
"dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from dataclasses_json.mm import (SchemaType, build_schema, schema)",
"else: # Union (already decoded or unsupported 'from_json' used) res = value return",
"detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing {warning} and was defaulted",
"= field.default elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name]",
"f\"Set infer_missing=False (the default) to prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name]",
"encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \" \"be",
"dump(self, obj, *, many=None): dumped = Schema.dump(self, obj, many=many) # TODO This is",
"of non-optional type {field.name} detected \" f\"when decoding {cls.__name__}\") if infer_missing: warnings.warn( f\"Missing",
"else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this is a band-aid",
"len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0] if is_dataclass(type_arg) or is_dataclass(value): res",
"dump and load, which is even more hacky # The only problem is",
"is hacky, but the other option I can think of is to generate",
"infer_missing=False (the default) to prevent this \" f\"behavior.\", RuntimeWarning) else: pass init_kwargs[field.name] =",
"underlying issue. A refactor is due. elif _is_collection(type_): if _is_mapping(type_): k_type, v_type =",
"-> A: return _decode_dataclass(cls, kvs, infer_missing) def dataclass_json(_cls=None, *, letter_case=None, undefined: Optional[Union[str, Undefined]]",
"as a constructor argument. if not field.init: continue from typing import GenericMeta field_value",
"list, str, int, float, bool, None] from pyspark_config.yamlConfig import create_file_path_field, build_path def build_schema(cls:",
"unwrap and rewrap classmethod to tag it to cls rather than the literal",
"= classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls",
"path_type=Path(path) built_path = build_path(path_type, path_is_absolute) if os.path.exists(path): if path.endswith('.yaml'): with built_path.open('r', encoding='UTF-8') as",
"\"\"\"This module implements abstract config class.\"\"\" from abc import ABCMeta from dataclasses import",
"value.values(), infer_missing) xs = zip(ks, vs) else: xs = (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for",
"= field_type.__supertype__ if (field.name in overrides and overrides[field.name].decoder is not None): # FIXME",
"handle optional-parens decorators. See example below: @dataclass_json @dataclass_json(letter_case=Lettercase.CAMEL) class Example: ... \"\"\" def",
"type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] = _support_extended_types(field_type, field_value) return cls(**init_kwargs)",
"many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json, *,",
"init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder( field_value) elif is_dataclass(field_type): # FIXME this",
"kvs.items()} missing_fields = {field for field in fields(cls) if field.name not in kvs}",
"return res def getSubclass(cls, values): \"\"\" In case one of the fields is",
"Example: ... \"\"\" def wrap(cls): return _process_class(cls, letter_case, undefined) if _cls is None:",
"from enum import Enum from marshmallow import post_load, Schema from pyspark_config.errors import *",
"exclude=exclude, many=many, context=context, load_only=load_only, dump_only=dump_only, partial=partial, unknown=unknown) @classmethod def from_dict(cls: Type[A], kvs: Json,",
"Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs, **kwargs):",
"not intended as a constructor argument. if not field.init: continue from typing import",
"\"+values['type']+\" not available.\") @dataclass class YamlDataClassConfig(DataClassJsonMix, metaclass=ABCMeta): \"\"\"This class implements YAML file load",
"built_path.open('r', encoding='UTF-8') as yml: dictionary_config = yaml.load(yml) else: raise InvalidTypeError(\"Configuration file must \"",
"of is to generate a different schema # depending on dump and load,",
"'type' in field_names: type_param = True else: type_param = False if field_value is",
"value elif _issubclass_safe(type_, Enum): # Convert to an Enum using the type as",
"if (field.name in overrides and overrides[field.name].decoder is not None): # FIXME hack if",
"field_value, infer_missing) elif _is_supported_generic(field_type) and field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type,",
"field should be skipped from being added # to init_kwargs as it's not",
"path: str, path_is_absolute: bool = False): \"\"\" This method loads from YAML file",
"init_kwargs as it's not intended as a constructor argument. if not field.init: continue",
"classmethod(DataClassJsonMix.from_json.__func__) cls.to_dict = DataClassJsonMix.to_dict cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls,",
"!= Optional[CatchAllVar]), # TODO #180 # 'render_module': global_config.json_module }) @post_load def make_instance(self, kvs,",
"value elif _is_optional(type_) and len(type_.__args__) == 2: # Optional type_arg = type_.__args__[0] if",
"MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None # Perform undefined parameter",
"def dump(self, obj, *, many=None): dumped = Schema.dump(self, obj, many=many) # TODO This",
"hasattr(type_, \"__args__\"): # Any, just accept res = value elif _is_optional(type_) and len(type_.__args__)",
"just accept res = value elif _is_optional(type_) and len(type_.__args__) == 2: # Optional",
"_handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import (_user_overrides_or_exts, get_type_hints, _decode_letter_case_overrides,",
"elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing: kvs[field.name] = None",
"f\"Missing {warning} and was defaulted to None by \" f\"infer_missing=True. \" f\"Set infer_missing=False",
"module implements abstract config class.\"\"\" from abc import ABCMeta from dataclasses import dataclass",
"in value) # get the constructor if using corresponding generic type in `typing`",
"cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register cls as a",
"cls.from_dict = classmethod(DataClassJsonMix.from_dict.__func__) cls.schema = classmethod(DataClassJsonMix.schema.__func__) cls.__init__ = _handle_undefined_parameters_safe(cls, kvs=(), usage=\"init\") # register",
"= None): \"\"\" Based on the code in the `dataclasses` module to handle",
"field in fields(cls)] decode_names = _decode_letter_case_overrides(field_names, overrides) kvs = {decode_names.get(k, k): v for",
"import A from dataclasses import (MISSING, fields, is_dataclass # type: ignore ) Json",
"**kwargs) def dump(self, obj, *, many=None): dumped = Schema.dump(self, obj, many=many) # TODO",
"return _process_class(cls, letter_case, undefined) if _cls is None: return wrap return wrap(_cls) def",
"or unsupported 'from_json' used) res = value return res def getSubclass(cls, values): \"\"\"",
"as a virtual subclass of DataClassJsonMixin DataClassJsonMixin.register(cls) return cls def _decode_dataclass(cls, kvs, infer_missing):",
"= (_decode_dataclass(getSubclass(type_,v), v, infer_missing) for v in value) # get the constructor if",
"def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta = type('Meta', (), {'fields':",
"unknown=None) -> SchemaType: Schema = build_schema(cls, DataClassJsonMix, infer_missing, partial) if unknown is None:",
"missing_fields = {field for field in fields(cls) if field.name not in kvs} for",
"the same-named mm keywords unknown = undefined_parameter_action.name.lower() return Schema(only=only, exclude=exclude, many=many, context=context, load_only=load_only,",
"undefined is not None: cls.dataclass_json_config = config(letter_case=letter_case, undefined=undefined)[ 'dataclasses_json'] cls.to_json = DataClassJsonMix.to_json #",
"# Perform undefined parameter action kvs = _handle_undefined_parameters_safe(cls, kvs, usage=\"from\") init_kwargs = {}",
"deal with the value already being # serialized when handling nested marshmallow schema",
"from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import config from",
"value = _decode_dataclass(field_type, field_value, infer_missing) init_kwargs[field.name] = value elif _is_supported_generic(field_type) and field_type !=",
"FIXME hack if field_type is type(field_value): init_kwargs[field.name] = field_value else: init_kwargs[field.name] = overrides[field.name].decoder(",
"value, infer_missing) else: res = _support_extended_types(type_arg, value) else: # Union (already decoded or",
"must \" \"be in YAML format: %s\" % str(built_path)) else: raise NotFoundError(\"No such",
"Args: path: The path in string form; can be relative or absolute. path_is_absolute:",
"import create_file_path_field, build_path def build_schema(cls: Type[A], mixin, infer_missing, partial) -> Type[SchemaType]: Meta =",
"import (_undefined_parameter_action_safe, _get_type_cons, _handle_undefined_parameters_safe, _is_collection, _is_mapping, _is_new_type, _is_optional, _issubclass_safe, CatchAllVar) from dataclasses_json.core import",
"field_type.__args__[0] != str and type_param: init_kwargs[field.name] = _decode_generic_subsets(field_type, field_value, infer_missing) else: init_kwargs[field.name] =",
"a band-aid to deal with the value already being # serialized when handling",
"type( f'{cls.__name__.capitalize()}Schema', (Schema,), {'Meta': Meta, f'make_{cls.__name__.lower()}': make_instance, 'dumps': dumps, 'dump': dump, **schema_}) return",
"not in kvs} for field in missing_fields: if field.default is not MISSING: kvs[field.name]",
"f\"infer_missing=True. \" f\"Set infer_missing=False (the default) to prevent this \" f\"behavior.\", RuntimeWarning) else:",
"post_load, Schema from pyspark_config.errors import * from dataclasses_json import DataClassJsonMixin from dataclasses_json.cfg import",
"kvs[field.name] = field.default elif field.default_factory is not MISSING: kvs[field.name] = field.default_factory() elif infer_missing:",
"different schema # depending on dump and load, which is even more hacky",
"proper fix is to investigate the marshmallow schema generation # code if is_dataclass(field_value):"
] |
[
"# [GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy import *",
"bytecode 3.5 (3351) # Decompiled from: Python 3.5.3 (default, Jan 19 2017, 14:11:04)",
"3.5 (3351) # Decompiled from: Python 3.5.3 (default, Jan 19 2017, 14:11:04) #",
"6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm",
"uncompyle6 version 2.13.2 # Python bytecode 3.5 (3351) # Decompiled from: Python 3.5.3",
"3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded file",
"= Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None def __init__(self,",
"license_key = None def __init__(self, license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]'",
"# uncompyle6 version 2.13.2 # Python bytecode 3.5 (3351) # Decompiled from: Python",
"from sqlalchemy import * from sqlalchemy.orm import mapper from db.tables import metadata LicensesTable",
"import * from sqlalchemy.orm import mapper from db.tables import metadata LicensesTable = Table('licenses',",
"Python bytecode 3.5 (3351) # Decompiled from: Python 3.5.3 (default, Jan 19 2017,",
"import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key =",
"version 2.13.2 # Python bytecode 3.5 (3351) # Decompiled from: Python 3.5.3 (default,",
"from db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object):",
"def __init__(self, license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def",
"file name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import mapper from db.tables",
"# Python bytecode 3.5 (3351) # Decompiled from: Python 3.5.3 (default, Jan 19",
"= None def __init__(self, license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]' %",
"# Decompiled from: Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0",
"metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key",
"Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key =",
"= license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def __repr__(self): return self.__str__() mapper(LicenseRow,",
"metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None",
"[GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy import * from",
"Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py",
"19 2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from",
"14:11:04) # [GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy import",
"__init__(self, license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def __repr__(self):",
"license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def __repr__(self): return self.__str__() mapper(LicenseRow, LicensesTable)",
"from: Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] #",
"sqlalchemy.orm import mapper from db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT,",
"mapper from db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class",
"license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def __repr__(self): return",
"import mapper from db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True))",
"* from sqlalchemy.orm import mapper from db.tables import metadata LicensesTable = Table('licenses', metadata,",
"None def __init__(self, license_key): self.license_key = license_key def __str__(self): return 'R_license[%s]' % (self.license_key,)",
"# Embedded file name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import mapper",
"name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import mapper from db.tables import",
"Decompiled from: Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118]",
"Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None def __init__(self, license_key):",
"class LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key = license_key def __str__(self):",
"Embedded file name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import mapper from",
"primary_key=True)) class LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key = license_key def",
"db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key",
"Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded",
"TEXT, primary_key=True)) class LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key = license_key",
"(default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded file name:",
"LicensesTable = Table('licenses', metadata, Column('license_key', TEXT, primary_key=True)) class LicenseRow(object): license_key = None def",
"db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import mapper from db.tables import metadata",
"20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy import * from sqlalchemy.orm import",
"sqlalchemy import * from sqlalchemy.orm import mapper from db.tables import metadata LicensesTable =",
"LicenseRow(object): license_key = None def __init__(self, license_key): self.license_key = license_key def __str__(self): return",
"(3351) # Decompiled from: Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC",
"from sqlalchemy.orm import mapper from db.tables import metadata LicensesTable = Table('licenses', metadata, Column('license_key',",
"self.license_key = license_key def __str__(self): return 'R_license[%s]' % (self.license_key,) def __repr__(self): return self.__str__()",
"2.13.2 # Python bytecode 3.5 (3351) # Decompiled from: Python 3.5.3 (default, Jan",
"2017, 14:11:04) # [GCC 6.3.0 20170118] # Embedded file name: db\\tables\\licenses.py from sqlalchemy"
] |
[
"= xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave= os.path.join(datapath,'folders.txt') def translate(text): return",
"import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder =",
"= 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder =",
"xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave= os.path.join(datapath,'folders.txt') def translate(text): return selfAddon.getLocalizedString(text).encode('utf-8')",
"datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave=",
"3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8')",
"xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok",
"addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave= os.path.join(datapath,'folders.txt') def translate(text):",
"\"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder",
"Author: enen92 License: I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id =",
"= xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok =",
"coding: UTF-8 -*- \"\"\" Author: enen92 License: I don't care version 3.0 \"\"\"",
"UTF-8 -*- \"\"\" Author: enen92 License: I don't care version 3.0 \"\"\" import",
"xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave= os.path.join(datapath,'folders.txt') def",
"'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img')",
"#!/usr/bin/env python # -*- coding: UTF-8 -*- \"\"\" Author: enen92 License: I don't",
"addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder",
"xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8')",
"= xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok = xbmcgui.Dialog().ok platformsave= os.path.join(datapath,'folders.txt')",
"-*- coding: UTF-8 -*- \"\"\" Author: enen92 License: I don't care version 3.0",
"python # -*- coding: UTF-8 -*- \"\"\" Author: enen92 License: I don't care",
"care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath",
"don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id)",
"\"\"\" Author: enen92 License: I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id",
"enen92 License: I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames'",
"selfAddon = xbmcaddon.Addon(id=addon_id) datapath = xbmc.translatePath(selfAddon.getAddonInfo('profile')).decode('utf-8') addonfolder = xbmc.translatePath(selfAddon.getAddonInfo('path')).decode('utf-8') artfolder = os.path.join(addonfolder,'resources','img') msgok",
"version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon = xbmcaddon.Addon(id=addon_id) datapath =",
"-*- \"\"\" Author: enen92 License: I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os",
"# -*- coding: UTF-8 -*- \"\"\" Author: enen92 License: I don't care version",
"I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon =",
"License: I don't care version 3.0 \"\"\" import xbmc,xbmcgui,xbmcaddon,os addon_id = 'script.retrogames' selfAddon"
] |
[
"control setup cpu = cpuFreq() # Get and check current frequencies. freqs =",
"not freqs: print(\"No frequency reads available.\") exit() # Print frecuencies by CPU. print(\"CPU",
"cpu = cpuFreq() # Get and check current frequencies. freqs = cpu.get_frequencies() if",
"Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\") for core",
"frequency reads available.\") exit() # Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [",
"frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\") for core in",
"print(\"No frequency reads available.\") exit() # Print frecuencies by CPU. print(\"CPU frequencies (KHz):\")",
"available.\") exit() # Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}:",
"by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\") for core in sorted(freqs)",
"and check current frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No frequency reads",
"cpuFreq # CPU control setup cpu = cpuFreq() # Get and check current",
"cpufreq import cpuFreq # CPU control setup cpu = cpuFreq() # Get and",
"= cpuFreq() # Get and check current frequencies. freqs = cpu.get_frequencies() if not",
"# Get and check current frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No",
"check current frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\")",
"if not freqs: print(\"No frequency reads available.\") exit() # Print frecuencies by CPU.",
"CPU control setup cpu = cpuFreq() # Get and check current frequencies. freqs",
"import cpuFreq # CPU control setup cpu = cpuFreq() # Get and check",
"= cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\") exit() # Print frecuencies",
"from cpufreq import cpuFreq # CPU control setup cpu = cpuFreq() # Get",
"exit() # Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\")",
"Get and check current frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No frequency",
"setup cpu = cpuFreq() # Get and check current frequencies. freqs = cpu.get_frequencies()",
"cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\") exit() # Print frecuencies by",
"reads available.\") exit() # Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU",
"freqs = cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\") exit() # Print",
"cpuFreq() # Get and check current frequencies. freqs = cpu.get_frequencies() if not freqs:",
"frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\") exit() #",
"current frequencies. freqs = cpu.get_frequencies() if not freqs: print(\"No frequency reads available.\") exit()",
"CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\") for core in sorted(freqs) ]",
"# Print frecuencies by CPU. print(\"CPU frequencies (KHz):\") [ print(f\"CPU {core}: {freqs[core]}\") for",
"# CPU control setup cpu = cpuFreq() # Get and check current frequencies.",
"<filename>python/freq/getfreqs.py from cpufreq import cpuFreq # CPU control setup cpu = cpuFreq() #",
"freqs: print(\"No frequency reads available.\") exit() # Print frecuencies by CPU. print(\"CPU frequencies"
] |
[
"FWCore.ParameterSet.Config as cms #-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( #",
"should be enabled # == mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*',",
"enabled # == mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*',",
"#'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', #",
"ME4/2 chambers should be enabled # == mask most or ME+4/2 chambers, except",
"#'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask all",
"#'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*',",
"#'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*',",
"== mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*',",
"CSCMaskedHW = cms.untracked.vstring( # == Post LS1 - All ME4/2 chambers should be",
"#'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*',",
"#'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*',",
"#'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*',",
"== Post LS1 - All ME4/2 chambers should be enabled # == mask",
"#'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask all ME-4/2 chambers",
"= cms.untracked.vstring( # == Post LS1 - All ME4/2 chambers should be enabled",
"be enabled # == mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*',",
"#'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*',",
"#'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*',",
"# == mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*',",
"#-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1",
"Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1 - All",
"#'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*',",
"except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*',",
"#'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*',",
"#'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*',",
"chambers should be enabled # == mask most or ME+4/2 chambers, except 9,10,11,12,13",
"#'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*',",
"#'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*',",
"#'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*',",
"chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*',",
"#'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask all ME-4/2 chambers #'2,4,2,*,*,*,*',",
"#'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask all ME-4/2",
"Post LS1 - All ME4/2 chambers should be enabled # == mask most",
"LS1 - All ME4/2 chambers should be enabled # == mask most or",
"cms.untracked.vstring( # == Post LS1 - All ME4/2 chambers should be enabled #",
"#'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask",
"#'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # == mask all ME-4/2 chambers #'2,4,2,*,*,*,*', )",
"9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*',",
"as cms #-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # ==",
"<reponame>ckamtsikis/cmssw<filename>DQM/CSCMonitorModule/python/csc_dqm_masked_hw_cfi.py<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms #-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW =",
"Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1 - All ME4/2 chambers",
"import FWCore.ParameterSet.Config as cms #-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring(",
"#'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*',",
"# Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1 -",
"most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*',",
"#-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1 - All ME4/2 chambers should",
"cms #-------------------------- # Masked HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post",
"#'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*',",
"All ME4/2 chambers should be enabled # == mask most or ME+4/2 chambers,",
"- All ME4/2 chambers should be enabled # == mask most or ME+4/2",
"#'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*', # ==",
"#'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*',",
"or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*',",
"# == Post LS1 - All ME4/2 chambers should be enabled # ==",
"mask most or ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*',",
"#'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*', #'1,4,2,15,*,*,*', #'1,4,2,16,*,*,*', #'1,4,2,17,*,*,*', #'1,4,2,18,*,*,*', #'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*',",
"ME+4/2 chambers, except 9,10,11,12,13 #'1,4,2,1,*,*,*', #'1,4,2,2,*,*,*', #'1,4,2,3,*,*,*', #'1,4,2,4,*,*,*', #'1,4,2,5,*,*,*', #'1,4,2,6,*,*,*', #'1,4,2,7,*,*,*', #'1,4,2,8,*,*,*', #'1,4,2,14,*,*,*',",
"#'1,4,2,19,*,*,*', #'1,4,2,20,*,*,*', #'1,4,2,21,*,*,*', #'1,4,2,22,*,*,*', #'1,4,2,23,*,*,*', #'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*',",
"HW Elements #-------------------------- CSCMaskedHW = cms.untracked.vstring( # == Post LS1 - All ME4/2",
"#'1,4,2,24,*,*,*', #'1,4,2,25,*,*,*', #'1,4,2,26,*,*,*', #'1,4,2,27,*,*,*', #'1,4,2,28,*,*,*', #'1,4,2,29,*,*,*', #'1,4,2,30,*,*,*', #'1,4,2,31,*,*,*', #'1,4,2,32,*,*,*', #'1,4,2,33,*,*,*', #'1,4,2,34,*,*,*', #'1,4,2,35,*,*,*', #'1,4,2,36,*,*,*',"
] |
[
"from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\",",
"from .cli import cli from .decorator import makes from .environment import env, PATH",
"= True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\",",
".environment import env, PATH from .shell import sh from .make import make, make_sync",
"import makes from .environment import env, PATH from .shell import sh from .make",
"Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\",",
"__FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\",",
"make_sync from .targets import Makefile, Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__",
".decorator import makes from .environment import env, PATH from .shell import sh from",
"makes from .environment import env, PATH from .shell import sh from .make import",
".cli import cli from .decorator import makes from .environment import env, PATH from",
"sh from .make import make, make_sync from .targets import Makefile, Target, Dependencies, Group",
"Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\",",
"\"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\", \"__FLAG_IS_PYMAKEFILE__\", \"Makefile\", \"Target\", \"Dependencies\", \"Group\"]",
"True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\", \"__FLAG_IS_PYMAKEFILE__\",",
"import cli from .decorator import makes from .environment import env, PATH from .shell",
"= [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\", \"__FLAG_IS_PYMAKEFILE__\", \"Makefile\", \"Target\",",
"from .environment import env, PATH from .shell import sh from .make import make,",
".shell import sh from .make import make, make_sync from .targets import Makefile, Target,",
".make import make, make_sync from .targets import Makefile, Target, Dependencies, Group from pathlib",
"cli from .decorator import makes from .environment import env, PATH from .shell import",
"import env, PATH from .shell import sh from .make import make, make_sync from",
"from .shell import sh from .make import make, make_sync from .targets import Makefile,",
".targets import Makefile, Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True",
"[\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\", \"__FLAG_IS_PYMAKEFILE__\", \"Makefile\", \"Target\", \"Dependencies\",",
"import sh from .make import make, make_sync from .targets import Makefile, Target, Dependencies,",
"make, make_sync from .targets import Makefile, Target, Dependencies, Group from pathlib import Path",
"from .decorator import makes from .environment import env, PATH from .shell import sh",
"pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\",",
"Makefile, Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ =",
"import make, make_sync from .targets import Makefile, Target, Dependencies, Group from pathlib import",
"env, PATH from .shell import sh from .make import make, make_sync from .targets",
"TimestampCache from .cli import cli from .decorator import makes from .environment import env,",
"from .targets import Makefile, Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ =",
"import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\",",
"import TimestampCache from .cli import cli from .decorator import makes from .environment import",
"import Makefile, Target, Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__",
".cache import TimestampCache from .cli import cli from .decorator import makes from .environment",
"from .cache import TimestampCache from .cli import cli from .decorator import makes from",
"Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\", \"makes\",",
"__all__ = [\"TimestampCache\", \"cli\", \"makes\", \"env\", \"PATH\", \"Path\", \"sh\", \"make\", \"make_sync\", \"__FLAG_IS_PYMAKEFILE__\", \"Makefile\",",
"from .make import make, make_sync from .targets import Makefile, Target, Dependencies, Group from",
"Dependencies, Group from pathlib import Path __FLAG_IS_PYMAKEFILE__ = True __all__ = [\"TimestampCache\", \"cli\",",
"PATH from .shell import sh from .make import make, make_sync from .targets import"
] |
[
"do jogador ''' def __init__(self): self.itens = [] self.nomes = [] ### implementar",
"class Inventory: '''Classe que representa o inventário do jogador ''' def __init__(self): self.itens",
"\"\\nSeu inventário contém os seguintes itens:\\n\" return title + \"\\n\".join(['-'+i for i in",
"in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in",
"item): if type(item) == list: for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item)",
"i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return False",
"self.nomes = [] ### implementar isso def add(self, item): if type(item) == list:",
"um item esta no inventario nome_do_item: str ''' return nome_do_item in self.nomes def",
"isso def add(self, item): if type(item) == list: for i in item: self.itens.append(i)",
"nome_do_item: str ''' return nome_do_item in self.nomes def __str__(self): title = \"\\nSeu inventário",
"player inventory class Inventory: '''Classe que representa o inventário do jogador ''' def",
"se um item esta no inventario nome_do_item: str ''' return nome_do_item in self.nomes",
"== list: for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self,",
"= [] ### implementar isso def add(self, item): if type(item) == list: for",
"self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return False def check(self, nome_do_item): '''",
"range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return False def check(self,",
"name: self.nomes.pop(i) self.itens.pop(i) return True return False def check(self, nome_do_item): ''' Verifica se",
"__str__(self): title = \"\\nSeu inventário contém os seguintes itens:\\n\" return title + \"\\n\".join(['-'+i",
"inventário do jogador ''' def __init__(self): self.itens = [] self.nomes = [] ###",
"self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)): if",
"self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)): if self.nomes[i]",
"# player inventory class Inventory: '''Classe que representa o inventário do jogador '''",
"def __str__(self): title = \"\\nSeu inventário contém os seguintes itens:\\n\" return title +",
"self.itens = [] self.nomes = [] ### implementar isso def add(self, item): if",
"return True return False def check(self, nome_do_item): ''' Verifica se um item esta",
"if type(item) == list: for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name)",
"que representa o inventário do jogador ''' def __init__(self): self.itens = [] self.nomes",
"remove(self, name): for i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return",
"add(self, item): if type(item) == list: for i in item: self.itens.append(i) self.nomes.append(i.name) else:",
"self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i)",
"def __init__(self): self.itens = [] self.nomes = [] ### implementar isso def add(self,",
"[] self.nomes = [] ### implementar isso def add(self, item): if type(item) ==",
"self.itens.pop(i) return True return False def check(self, nome_do_item): ''' Verifica se um item",
"''' def __init__(self): self.itens = [] self.nomes = [] ### implementar isso def",
"= [] self.nomes = [] ### implementar isso def add(self, item): if type(item)",
"self.nomes.pop(i) self.itens.pop(i) return True return False def check(self, nome_do_item): ''' Verifica se um",
"check(self, nome_do_item): ''' Verifica se um item esta no inventario nome_do_item: str '''",
"i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i",
"in self.nomes def __str__(self): title = \"\\nSeu inventário contém os seguintes itens:\\n\" return",
"else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)): if self.nomes[i] ==",
"in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return False def",
"### implementar isso def add(self, item): if type(item) == list: for i in",
"str ''' return nome_do_item in self.nomes def __str__(self): title = \"\\nSeu inventário contém",
"inventory class Inventory: '''Classe que representa o inventário do jogador ''' def __init__(self):",
"'''Classe que representa o inventário do jogador ''' def __init__(self): self.itens = []",
"True return False def check(self, nome_do_item): ''' Verifica se um item esta no",
"nome_do_item): ''' Verifica se um item esta no inventario nome_do_item: str ''' return",
"esta no inventario nome_do_item: str ''' return nome_do_item in self.nomes def __str__(self): title",
"__init__(self): self.itens = [] self.nomes = [] ### implementar isso def add(self, item):",
"def check(self, nome_do_item): ''' Verifica se um item esta no inventario nome_do_item: str",
"no inventario nome_do_item: str ''' return nome_do_item in self.nomes def __str__(self): title =",
"''' return nome_do_item in self.nomes def __str__(self): title = \"\\nSeu inventário contém os",
"title = \"\\nSeu inventário contém os seguintes itens:\\n\" return title + \"\\n\".join(['-'+i for",
"== name: self.nomes.pop(i) self.itens.pop(i) return True return False def check(self, nome_do_item): ''' Verifica",
"for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for",
"implementar isso def add(self, item): if type(item) == list: for i in item:",
"False def check(self, nome_do_item): ''' Verifica se um item esta no inventario nome_do_item:",
"self.nomes def __str__(self): title = \"\\nSeu inventário contém os seguintes itens:\\n\" return title",
"def add(self, item): if type(item) == list: for i in item: self.itens.append(i) self.nomes.append(i.name)",
"inventário contém os seguintes itens:\\n\" return title + \"\\n\".join(['-'+i for i in self.nomes])",
"list: for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name):",
"return False def check(self, nome_do_item): ''' Verifica se um item esta no inventario",
"[] ### implementar isso def add(self, item): if type(item) == list: for i",
"= \"\\nSeu inventário contém os seguintes itens:\\n\" return title + \"\\n\".join(['-'+i for i",
"name): for i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True",
"jogador ''' def __init__(self): self.itens = [] self.nomes = [] ### implementar isso",
"Inventory: '''Classe que representa o inventário do jogador ''' def __init__(self): self.itens =",
"item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)):",
"representa o inventário do jogador ''' def __init__(self): self.itens = [] self.nomes =",
"o inventário do jogador ''' def __init__(self): self.itens = [] self.nomes = []",
"self.itens.append(item) self.nomes.append(item.name) def remove(self, name): for i in range(len(self.itens)): if self.nomes[i] == name:",
"if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return False def check(self, nome_do_item):",
"type(item) == list: for i in item: self.itens.append(i) self.nomes.append(i.name) else: self.itens.append(item) self.nomes.append(item.name) def",
"inventario nome_do_item: str ''' return nome_do_item in self.nomes def __str__(self): title = \"\\nSeu",
"def remove(self, name): for i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i)",
"for i in range(len(self.itens)): if self.nomes[i] == name: self.nomes.pop(i) self.itens.pop(i) return True return",
"Verifica se um item esta no inventario nome_do_item: str ''' return nome_do_item in",
"''' Verifica se um item esta no inventario nome_do_item: str ''' return nome_do_item",
"item esta no inventario nome_do_item: str ''' return nome_do_item in self.nomes def __str__(self):",
"return nome_do_item in self.nomes def __str__(self): title = \"\\nSeu inventário contém os seguintes",
"nome_do_item in self.nomes def __str__(self): title = \"\\nSeu inventário contém os seguintes itens:\\n\""
] |
[
"bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash",
"at specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk",
"Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import",
"# load mnemonic & generate seed bytes mnemonic = \"comfort rough close flame",
"Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress,",
"ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress",
"from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import",
"generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load mnemonic & generate seed",
"Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib",
"= 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate",
"miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb",
"is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific",
"<gh_stars>1-10 # -*- coding: UTF-8 -*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from",
"like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child",
"from hashlib import sha256 # load mnemonic & generate seed bytes mnemonic =",
"seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx",
"import sha256 # load mnemonic & generate seed bytes mnemonic = \"comfort rough",
"'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress = %s\" % (child_id_uint32, sk,",
"sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address",
"import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 #",
"hashlib import sha256 # load mnemonic & generate seed bytes mnemonic = \"comfort",
"bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32)",
"child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub",
"from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE,",
"address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load mnemonic &",
"root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") #",
"debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path",
"close flame uniform chapter unique announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate()",
"Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address",
"rough close flame uniform chapter unique announce miracle debris space like\" seed_bytes =",
"bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32",
"flame uniform chapter unique announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() #",
"= \"comfort rough close flame uniform chapter unique announce miracle debris space like\"",
"= bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args =",
"Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes)",
"import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from",
"Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32 = 220342",
"from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load mnemonic",
"path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at",
"print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress = %s\" % (child_id_uint32, sk, address))",
"= generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress = %s\"",
"seed bytes mnemonic = \"comfort rough close flame uniform chapter unique announce miracle",
"generate seed bytes mnemonic = \"comfort rough close flame uniform chapter unique announce",
"uniform chapter unique announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate",
"= Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32 =",
"Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load",
"# -*- coding: UTF-8 -*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils",
"generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at",
"get childkey at specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk =",
"-*- coding: UTF-8 -*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import",
"location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex()",
"bytes mnemonic = \"comfort rough close flame uniform chapter unique announce miracle debris",
"child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE,",
"ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey",
"m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location",
"& generate seed bytes mnemonic = \"comfort rough close flame uniform chapter unique",
"= bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32 = 220342 child_key =",
"unique announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root",
"UTF-8 -*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from",
"bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32",
"childkey at specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex()",
"sha256 # load mnemonic & generate seed bytes mnemonic = \"comfort rough close",
"blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey",
"generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx =",
"chapter unique announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD",
"= Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx =",
"bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256",
"child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args",
"address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress =",
"mnemonic & generate seed bytes mnemonic = \"comfort rough close flame uniform chapter",
"from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base import",
"child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() #",
"= child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address =",
"= child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet')",
"bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get childkey at specific location child_id_uint32 = 220342 child_key",
"CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load mnemonic & generate seed bytes",
"load mnemonic & generate seed bytes mnemonic = \"comfort rough close flame uniform",
"220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address",
"ckbhash from hashlib import sha256 # load mnemonic & generate seed bytes mnemonic",
"import Bip39SeedGenerator from bip_utils.bip.bip44_base import Bip32 from address import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from",
"pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args,",
"-*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator from bip_utils.bip.bip44_base",
"specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk =",
"import generateShortAddress, CODE_INDEX_SECP256K1_SINGLE, ckbhash from hashlib import sha256 # load mnemonic & generate",
"= ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey =",
"# generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key",
"blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress = %s\" % (child_id_uint32,",
"HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\")",
"address blake160_args = ckbhash(bytes.fromhex(pk))[:40] address = generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d",
"key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx = bip32_ctx.DerivePath(\"44'/309'/0'/0\") # get",
"# get childkey at specific location child_id_uint32 = 220342 child_key = bip32_ctx.ChildKey(child_id_uint32) sk",
"# generate HD root key, ckb path is m/44'/309'/0'/change_or_not/child bip32_ctx = Bip32.FromSeed(seed_bytes) bip32_ctx",
"announce miracle debris space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key,",
"bip32_ctx.ChildKey(child_id_uint32) sk = child_key.PrivateKey().Raw().ToHex() pk = child_key.PublicKey().RawCompressed().ToHex() # generate address blake160_args = ckbhash(bytes.fromhex(pk))[:40]",
"generateShortAddress(CODE_INDEX_SECP256K1_SINGLE, blake160_args, 'mainnet') print(\"Sub Key at %d is:\\nPrivatekey = %s\\nAddress = %s\" %",
"coding: UTF-8 -*- from bip_utils import Bip39ChecksumError, Bip39Languages, Bip39MnemonicValidator from bip_utils import Bip39SeedGenerator",
"mnemonic = \"comfort rough close flame uniform chapter unique announce miracle debris space",
"\"comfort rough close flame uniform chapter unique announce miracle debris space like\" seed_bytes",
"space like\" seed_bytes = Bip39SeedGenerator(mnemonic).Generate() # generate HD root key, ckb path is"
] |
[] |
[
"test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words):",
"\"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national',",
"assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence",
"palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def",
"def words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"]",
"return words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type',",
"This test case fails for some unknown reason Fails. Palmetto can not handle",
"== 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence ==",
"palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence =",
"= Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with",
"doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results):",
"in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\",",
"def test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type)",
"palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words)",
"Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with",
"pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\",",
"reason Fails. Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids =",
"import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test",
"fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore():",
"i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case",
"\"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture",
"@pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'subject',",
"from palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words():",
"palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type)",
"= Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for",
"words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return words",
"\"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in",
"test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto",
"1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words):",
"palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto =",
"fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto',",
"Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def",
"fails for some unknown reason Fails. Palmetto can not handle underscores. \"\"\" palmetto",
"words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241)",
"coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words,",
"def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some unknown reason Fails. Palmetto",
"palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words):",
"'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words",
"[\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test data",
"= Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto",
"fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load",
"def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words):",
"def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some unknown reason Fails. Palmetto",
"= palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\"",
"test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys,",
"Fails. Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results)",
"words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character',",
"return words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence ==",
"palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] ==",
"Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto()",
"= Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\")",
"\"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in range(0, len(words_no_results)): assert(doc_ids[i][0]",
"\"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0]",
"palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto =",
"content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids",
"coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words):",
"data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results():",
"with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type in",
"== words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some unknown reason",
"len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some",
"words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return",
"@pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\",",
"from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\"",
"with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence",
"palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]:",
"'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence",
"'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words):",
"= ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return",
"= [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test",
"test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto =",
"\"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words,",
"palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto()",
"= Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto =",
"'isoexception'] return words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence",
"Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto =",
"palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def",
"\"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words",
"Fails. Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore)",
"test data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def",
"coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown):",
"'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto =",
"= Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i])",
"= Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in range(0, len(words_no_results)): assert(doc_ids[i][0] == words_no_results[i])",
"= Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto()",
"Palmetto.\"\"\" import pytest from palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType",
"underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in range(0, len(words_no_results)):",
"Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def",
"palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words",
"test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0]",
"'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto = Palmetto()",
"palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\")",
"test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some unknown reason Fails. Palmetto can",
"coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence",
"i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case",
"import pytest from palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture",
"\"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words =",
"data fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam',",
"'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words =",
"import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words =",
"\"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label',",
"with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type",
"coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def",
"in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails",
"unknown reason Fails. Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids",
"pytest from palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def",
"palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] ==",
"content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0,",
"for some unknown reason Fails. Palmetto can not handle underscores. \"\"\" palmetto =",
"\"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for",
"== 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def",
"assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words)",
"words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some unknown reason Fails.",
"def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def",
"'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words)",
"CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\",",
"= palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\")",
"= Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] == words[i])",
"= palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\"",
"can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i",
"['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\"",
"can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i",
"def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)):",
"range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for",
"pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence =",
"test case fails for some unknown reason Fails. Palmetto can not handle underscores.",
"words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic',",
"palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words) for i",
"def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto",
"def test_get_coherence(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def",
"case fails for some unknown reason Fails. Palmetto can not handle underscores. \"\"\"",
"handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in range(0,",
"palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This",
"for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto() with pytest.raises(WrongContentType):",
"words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load",
"\"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words",
"'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def",
"coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types:",
"def words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline',",
"0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024)",
"in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids =",
"palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto =",
"for i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test",
"not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in",
"palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in range(0, len(words_no_results)): assert(doc_ids[i][0] ==",
"words): palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words):",
"pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in",
"words = ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test",
"words): palmetto = Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto",
"def words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment'] return",
"EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\",",
"palmetto = Palmetto() coherence = palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto",
"words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some unknown reason Fails.",
"Palmetto() coherence = palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with",
"return words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type',",
"words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character',",
"'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys,",
"test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some unknown reason Fails. Palmetto can",
"Palmetto() with pytest.raises(WrongContentType): palmetto._request_by_service(words, \"cv\", \"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type",
"\"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\"",
"Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for",
"data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture def",
"= ['label', 'type', 'character', 'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test data",
"handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0,",
"assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some unknown",
"test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto =",
"\"\"\" This test case fails for some unknown reason Fails. Palmetto can not",
"test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\", \"cherry\", \"chocolate\"] return words @pytest.fixture",
"test data fixture.\"\"\" words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor',",
"WrongContentType @pytest.fixture def words(): \"\"\"Load test data fixture.\"\"\" words = [\"cake\", \"apple\", \"banana\",",
"@pytest.fixture def words_underscore(): \"\"\"Load test data fixture.\"\"\" words = ['label', 'type', 'character', 'foundation_garment']",
"= palmetto.get_coherence(words) assert(coherence == 0.5678879445677241) def test_get_coherence_fast(capsys, words): palmetto = Palmetto() coherence =",
"some unknown reason Fails. Palmetto can not handle underscores. \"\"\" palmetto = Palmetto()",
"'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto",
"doc_ids = palmetto.get_df_for_words(words) for i in range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore):",
"for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto()",
"'foundation_garment'] return words @pytest.fixture def words_no_results(): \"\"\"Load test data fixture.\"\"\" words = ['label',",
"'fam', 'glotto', 'isoexception'] return words def test_get_coherence(capsys, words): palmetto = Palmetto() coherence =",
"Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable):",
"for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test",
"coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words,",
"in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails",
"assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some unknown",
"test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def",
"Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load test data",
"def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto",
"= palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words,",
"len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for some",
"underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)):",
"['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception'] return words",
"palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence = palmetto.get_coherence(words) def test_wrong_coherence_type(words): palmetto = Palmetto()",
"palmetto.get_df_for_words(words_underscore) for i in range(0, len(words_underscore)): assert(doc_ids[i][0] == words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This",
"= Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto = Palmetto()",
"not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for i in",
"\"\"\"Test Palmetto.\"\"\" import pytest from palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown,",
"Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_underscore) for",
"words = ['label', 'type', 'character', 'subject', 'discipline', 'topic', 'national', 'familycolor', 'fam', 'glotto', 'isoexception']",
"[\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\", content_type) def test_get_df_for_words(words): palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words)",
"test_all_coherence_types(words): palmetto = Palmetto() for coherence_type in palmetto.all_coherence_types: palmetto.get_coherence(words, coherence_type=coherence_type) def test_wrong_content_type(words): palmetto",
"\"bla\") def test_all_content_types(words): palmetto = Palmetto() for content_type in [\"text\", \"bytes\"]: palmetto._request_by_service(words, \"umass\",",
"= palmetto.get_coherence_fast(words) assert(coherence == 1779.6591356383024) def test_wrong_endpoint(words): palmetto = Palmetto(\"http://example.com/nothinghere/\") with pytest.raises(EndpointDown): coherence",
"Palmetto can not handle underscores. \"\"\" palmetto = Palmetto() doc_ids = palmetto.get_df_for_words(words_no_results) for",
"def test_wrong_coherence_type(words): palmetto = Palmetto() with pytest.raises(CoherenceTypeNotAvailable): coherence = palmetto.get_coherence(words, coherence_type=\"asdf\") def test_all_coherence_types(words):",
"range(0, len(words)): assert(doc_ids[i][0] == words[i]) def test_get_df_for_words_underscore(words_underscore): \"\"\" This test case fails for",
"palmettopy.palmetto import Palmetto from palmettopy.exceptions import CoherenceTypeNotAvailable, EndpointDown, WrongContentType @pytest.fixture def words(): \"\"\"Load",
"== words_underscore[i]) def test_get_df_for_words_with_no_results(words_no_results): \"\"\" This test case fails for some unknown reason"
] |
[
"32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox =",
"mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for",
"M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3,",
"= M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib =",
"activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU,",
"self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle() mod =",
"res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1",
"e = self.c7_s1(e) # frame encoding f = dt2 f = self.c1_s2(f) f",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128,",
"self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2",
"self.gx(x) gh = self.gh(h) ox = self.ox(x) oh = self.oh(h) fx = self.fx(x)",
"self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 = Stage1()",
"axis=-1) g = self.g(x) + self.gb i = self.i(x) + self.ib o =",
"i h = o * tf.tanh(c) # decoder branch x = self.mc1(h) x",
"tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox + oh + self.ob) i",
"self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2",
"values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU,",
"= self.ix(x) ih = self.ih(h) g = tf.tanh(gx + gh + self.gb) o",
"values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2'))",
"= self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model): def",
"# print(res[0].shape) return res def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias'])",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e =",
"= self.c7_s1(e) # frame encoding f = dt2 f = self.c1_s2(f) f =",
"tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx + fh + self.fb) c",
"o = tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix + ih +",
"pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb =",
"hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap, cent, h,",
"self.ih(h) g = tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox + oh",
"self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128,",
"mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce = tf.pad(centermap,",
"as np import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def",
"tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32))",
"* i h = o * tf.tanh(c) # decoder branch x = self.mc1(h)",
"= M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c): # frame",
"self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob",
"tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch x = tf.concat([f, e,",
"res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name):",
"# print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def initialize(self): #",
"pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID')",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3,",
"activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512,",
"= tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e,",
"48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48,",
"= M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 =",
"res class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"o = tf.sigmoid(o) c = g * i h = o * tf.tanh(c)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g",
"= self.gx(x) gh = self.gh(h) ox = self.ox(x) oh = self.oh(h) fx =",
"= np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test",
"= Stage0() self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle() mod = mods.s0",
"tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32))",
"self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e",
"values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU,",
"tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3'))",
"M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3,",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1,",
"= self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e)",
"self.pool(ce) # lstm branch x = tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x)",
"f = self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f =",
"self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) #",
"= mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2",
"tf.sigmoid(i) o = tf.sigmoid(o) c = g * i h = o *",
"= M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb =",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5,",
"M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 =",
"self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e",
"import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res",
"class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e)",
"32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm",
"values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c):",
"values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"= self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f)",
"2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2,",
"self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1'))",
"= M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center",
"res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def initialize(self): # init encoding",
"import numpy as np import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 =",
"128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap,",
"self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle() mod = mods.s0 x =",
"48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48,",
"pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID')",
"2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512,",
"self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce",
"pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool =",
"= tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"frame encoding f = x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class",
"= tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x = tf.concat([f,",
"self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i",
"self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib",
"tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c = g * i h",
"x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap",
"activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2'))",
"= M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1",
"Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2'))",
"tf.tanh(c) # decoder branch x = self.mc1(h) x = self.mc2(x) x = self.mc3(x)",
"e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e =",
"= M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 =",
"self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) #",
"values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3,",
"= tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih =",
"self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48,",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1,",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2'))",
"fx = self.fx(x) fh = self.fh(h) ix = self.ix(x) ih = self.ih(h) g",
"print(out) print(out.shape) input('Test deploy2 finished. Input for saving converted weights ') saver =",
"= tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f,",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"= c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32))",
"= np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT',",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32))",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3'))",
"mode='SYMMETRIC') x = self.pool(x) # LSTM branch x = tf.concat([f, e, x], axis=-1)",
"activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init",
"c): # frame encoding f = x f = self.c1_s2(f) f = tf.pad(f,",
"# frame encoding f = dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]],",
"values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3'))",
"= self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) # frame",
"512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1,",
"params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) #",
"initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 =",
"self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2",
"# center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48,",
"= self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT',",
"f = tf.sigmoid(fx + fh + self.fb) c = f*c + i*g h",
"2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2,",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3,",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"= self.pool(x) # LSTM branch x = tf.concat([f, e, x], axis=-1) g =",
"print(res[0].shape) return res class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9,",
"tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3,",
"= self.oh(h) fx = self.fx(x) fh = self.fh(h) ix = self.ix(x) ih =",
"* tf.tanh(c) # decoder branch x = self.mc1(h) x = self.mc2(x) x =",
"ix = self.ix(x) ih = self.ih(h) g = tf.tanh(gx + gh + self.gb)",
"activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3'))",
"M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2'))",
"input('Test deploy1 finished. Input for testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32)",
"deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c",
"self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb",
"self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1",
"tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3'))",
"+ self.gb i = self.i(x) + self.ib o = self.o(x) + self.ob g",
"frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2,",
"finished. Input for testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent =",
"activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128,",
"48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1",
"self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 =",
"= tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob =",
"M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') #",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3'))",
"encoding f = x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f",
"self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self,",
"self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) #",
"self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0()",
"cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for testing deploy2')",
"values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15,",
"activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128,",
"values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11,",
"= tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e)",
"np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap,",
"= tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"= np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights'])",
"Stage1() if __name__=='__main__': mods = ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent",
"= tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e,",
"self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e",
"x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch x =",
"out class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce =",
"c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x =",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb =",
"lstm branch x = tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh =",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob =",
"values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11,",
"activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h,",
"mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x = tf.pad(centermap,",
"= tf.sigmoid(o) c = g * i h = o * tf.tanh(c) #",
"e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e =",
"tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 =",
"np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1",
"= self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e)",
"self.gh(h) ox = self.ox(x) oh = self.oh(h) fx = self.fx(x) fh = self.fh(h)",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch x = tf.concat([f, e, x],",
"= tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox + oh + self.ob)",
"= M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1'))",
"self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) # frame encoding",
"def forward(self, x, hmap, centermap, h, c): # frame encoding f = x",
"x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out =",
"values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3'))",
"print(res[0].shape) return res def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) #",
"res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model):",
"# frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3,",
"dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e",
"self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob",
"self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self,",
"#init enc e = dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"e = self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) #",
"M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') #",
"return out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 = Stage1() if",
"decoder branch x = self.mc1(h) x = self.mc2(x) x = self.mc3(x) x =",
"values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 =",
"activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e =",
"= self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"= self.c6_s1(e) e = self.c7_s1(e) # frame encoding f = dt2 f =",
"self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 =",
"tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x = tf.concat([f, hmap,",
"0 x = mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape)",
"lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3'))",
"= self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) # frame encoding f =",
"= self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e)",
"self.fh(h) ix = self.ix(x) ih = self.ih(h) g = tf.tanh(gx + gh +",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3,",
"self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48,",
"= tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh = self.gh(h) ox =",
"values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc",
"activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__':",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]],",
"x = self.mc2(x) x = self.mc3(x) x = self.mc4(x) out = self.mc5(x) return",
"self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb",
"pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID')",
"encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID')",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1,",
"[] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def initialize(self):",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32,",
"+ fh + self.fb) c = f*c + i*g h = o *",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 =",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx =",
"= tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh =",
"activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128,",
"gh = self.gh(h) ox = self.ox(x) oh = self.oh(h) fx = self.fx(x) fh",
"self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2",
"M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3,",
"f = dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f =",
"cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape)",
"activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e)",
"2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2,",
"self.fx(x) fh = self.fh(h) ix = self.ix(x) ih = self.ih(h) g = tf.tanh(gx",
"res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights'])",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 =",
"e = self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e =",
"ce = self.pool(ce) # lstm branch x = tf.concat([f, hmap, ce], axis=-1) gx",
"print(out.shape) input('Test deploy2 finished. Input for saving converted weights ') saver = M.Saver(mods)",
"pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID')",
"pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID')",
"i = tf.sigmoid(i) o = tf.sigmoid(o) c = g * i h =",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5,",
"f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]],",
"self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c): #",
"ih + self.ib) f = tf.sigmoid(fx + fh + self.fb) c = f*c",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9,",
"self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc e",
"self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1'))",
"= Stage1() if __name__=='__main__': mods = ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32)",
"# print(res[0].shape) return res class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 =",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb =",
"testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h =",
"axis=-1) gx = self.gx(x) gh = self.gh(h) ox = self.ox(x) oh = self.oh(h)",
"tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"= self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model): def",
"self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e",
"= M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 =",
"encoding f = dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f",
"print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res = [] #",
"centermap): #init enc e = dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]],",
"self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb",
"hmap, centermap, h, c): # frame encoding f = x f = self.c1_s2(f)",
"f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap",
"values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2'))",
"self.ib = tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3'))",
"= M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID')",
"= self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e)",
"mods = ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x",
"decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128,",
"values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3,",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 =",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"= mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent)",
"= tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c = g * i",
"activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1'))",
"15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc e = dt1 e",
"values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def",
"= self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"= np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1]",
"= self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e =",
"tf.sigmoid(o) c = g * i h = o * tf.tanh(c) # decoder",
"= self.i(x) + self.ib o = self.o(x) + self.ob g = tf.tanh(g) i",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx",
"self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh",
"initialize(self): self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle() mod",
"f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f =",
"np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for testing deploy2') mod = mods.s1",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1,",
"self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8,",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3",
"i = self.i(x) + self.ib o = self.o(x) + self.ob g = tf.tanh(g)",
"M import numpy as np import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2",
"M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9,",
"self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f",
"self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2'))",
"ih = self.ih(h) g = tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox",
"return res class Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128,",
"+ i*g h = o * tf.tanh(c) # decoder branch x = self.mc1(h)",
"self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"= [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def",
"= tf.concat([f, e, x], axis=-1) g = self.g(x) + self.gb i = self.i(x)",
"decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128,",
"activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx =",
"for testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h",
"x[:,-1] = 0 x = mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2])",
"= np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap =",
"self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model): def initialize(self):",
"48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib",
"= M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center",
"mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x = tf.concat([f, hmap, ce], axis=-1)",
"self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 =",
"out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for testing deploy2') mod",
"params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name])",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9,",
"values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1'))",
"= mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input",
"= tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__': mods =",
"encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID')",
"48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1",
"g = tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox + oh +",
"e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e =",
"ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x,",
"branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"self.ix(x) ih = self.ih(h) g = tf.tanh(gx + gh + self.gb) o =",
"+ self.ib) f = tf.sigmoid(fx + fh + self.fb) c = f*c +",
"self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix",
"values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2'))",
"x, hmap, centermap, h, c): # frame encoding f = x f =",
"self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"f = self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x =",
"# LSTM branch x = tf.concat([f, e, x], axis=-1) g = self.g(x) +",
"g = self.g(x) + self.gb i = self.i(x) + self.ib o = self.o(x)",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9,",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 =",
"# frame encoding f = x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]],",
"x = mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test",
"f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f =",
"15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2",
"M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3,",
"+ self.gb) o = tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix +",
"self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f",
"centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch",
"Stage0() self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle() mod = mods.s0 x",
"np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for saving converted weights ') saver",
"# init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3,",
"mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32)",
"= f*c + i*g h = o * tf.tanh(c) # decoder branch x",
"tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob)",
"e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e =",
"= tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx + fh + self.fb)",
"+ ih + self.ib) f = tf.sigmoid(fx + fh + self.fb) c =",
"+ self.ib o = self.o(x) + self.ob g = tf.tanh(g) i = tf.sigmoid(i)",
"pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2",
"cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32)",
"activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"f*c + i*g h = o * tf.tanh(c) # decoder branch x =",
"= self.fh(h) ix = self.ix(x) ih = self.ih(h) g = tf.tanh(gx + gh",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4",
"def initialize(self): self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__': mods = ModelBundle()",
"= M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 =",
"e = self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e = self.c6_s1(e) e",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32,",
"mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x,",
"tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3,",
"M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1",
"= M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding",
"tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]],",
"i*g h = o * tf.tanh(c) # decoder branch x = self.mc1(h) x",
"values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2'))",
"print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res class Stage0(M.Model): def initialize(self): # init",
"x = tf.concat([f, e, x], axis=-1) g = self.g(x) + self.gb i =",
"tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce",
"= self.pool(ce) # lstm branch x = tf.concat([f, hmap, ce], axis=-1) gx =",
"# print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res = []",
"M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2",
"self.ob g = tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c = g",
"numpy as np import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item()",
"= mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46,",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch",
"32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 =",
"self.fb) c = f*c + i*g h = o * tf.tanh(c) # decoder",
"128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap):",
"= np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x,",
"= M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc e =",
"e = self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) # frame encoding f",
"mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f",
"mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f",
"tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]],",
"= [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res",
"= self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f)",
"+ self.ob g = tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c =",
"pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"# lstm branch x = tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32,",
"map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3'))",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder",
"= self.mc5(x) return out class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 =",
"self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"e = self.c6_s1(e) e = self.c7_s1(e) # frame encoding f = dt2 f",
"= x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f)",
"values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 = M.ConvLayer(9, 128,",
"ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x =",
"values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2'))",
"dt1, dt2, centermap): #init enc e = dt1 e = self.c1_s1(e) e =",
"branch x = tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh = self.gh(h)",
"x = self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model):",
"= M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1,",
"self.ob) i = tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx + fh",
"__name__=='__main__': mods = ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32)",
"self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1",
"ox = self.ox(x) oh = self.oh(h) fx = self.fx(x) fh = self.fh(h) ix",
"= tf.sigmoid(fx + fh + self.fb) c = f*c + i*g h =",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9,",
"return out class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128,",
"2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2,",
"f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f =",
"M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3,",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch",
"# decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11,",
"as M import numpy as np import tensorflow as tf params = np.load('lstmpm_d1.npy').item()",
"forward(self, x, hmap, centermap, h, c): # frame encoding f = x f",
"# lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib",
"= tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib =",
"= tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11,",
"pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool =",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5",
"f = self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f =",
"+ self.ob) i = tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx +",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 =",
"activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128,",
"# centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM",
"48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb",
"map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2'))",
"= g * i h = o * tf.tanh(c) # decoder branch x",
"# centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm",
"+ self.fb) c = f*c + i*g h = o * tf.tanh(c) #",
"np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap, cent, h, c) out",
"values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc e = dt1 e =",
"2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2,",
"= 0 x = mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out)",
"self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2",
"self.ib o = self.o(x) + self.ob g = tf.tanh(g) i = tf.sigmoid(i) o",
"15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c): # frame encoding f",
"tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e = self.c4_s1(e) e = self.c5_s1(e) e",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x =",
"out = self.mc5(x) return out class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2",
"mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e",
"e = dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e =",
"LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb)",
"activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128,",
"enc e = dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e",
"x], axis=-1) g = self.g(x) + self.gb i = self.i(x) + self.ib o",
"get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def",
"pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID')",
"= self.p3_s2(f) f = self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"x = self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0",
"self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1",
"values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb)",
"dt2, centermap): #init enc e = dt1 e = self.c1_s1(e) e = tf.pad(e,",
"self.o(x) + self.ob g = tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c",
"fh + self.fb) c = f*c + i*g h = o * tf.tanh(c)",
"x = self.pool(x) # LSTM branch x = tf.concat([f, e, x], axis=-1) g",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5,",
"h = o * tf.tanh(c) # decoder branch x = self.mc1(h) x =",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x = tf.concat([f, hmap, ce],",
"self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8,",
"tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3'))",
"= self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce)",
"out = self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1",
"encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID')",
"pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3,",
"= self.mc1(h) x = self.mc2(x) x = self.mc3(x) x = self.mc4(x) out =",
"def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return res",
"tf.sigmoid(fx + fh + self.fb) c = f*c + i*g h = o",
"= np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for saving converted weights ')",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder",
"self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model): def initialize(self):",
"values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_h_stage3')) self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb)",
"self.ox(x) oh = self.oh(h) fx = self.fx(x) fh = self.fh(h) ix = self.ix(x)",
"M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3,",
"mod(x, hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished.",
"tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]],",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 =",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9,",
"tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x",
"e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e =",
"o * tf.tanh(c) # decoder branch x = self.mc1(h) x = self.mc2(x) x",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11,",
"self.pool(x) # LSTM branch x = tf.concat([f, e, x], axis=-1) g = self.g(x)",
"= tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f,",
"self.g(x) + self.gb i = self.i(x) + self.ib o = self.o(x) + self.ob",
"np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46,",
"= tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3,",
"mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out",
"input('Test deploy2 finished. Input for saving converted weights ') saver = M.Saver(mods) saver.save('./LSTMPM/lstmpm.ckpt')",
"tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh = self.gh(h) ox = self.ox(x)",
"activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"x = self.mc1(h) x = self.mc2(x) x = self.mc3(x) x = self.mc4(x) out",
"tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res =",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def",
"48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb",
"x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f",
"= self.mc4(x) out = self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0 =",
"= self.g(x) + self.gb i = self.i(x) + self.ib o = self.o(x) +",
"= M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh =",
"f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f =",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3",
"print(out.shape) input('Test deploy1 finished. Input for testing deploy2') mod = mods.s1 x =",
"res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res = [] # print(params[name])",
"self.i(x) + self.ib o = self.o(x) + self.ob g = tf.tanh(g) i =",
"self.gb) o = tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix + ih",
"self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) #",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9,",
"x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished.",
"# decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11,",
"c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for saving converted",
"values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c): # frame encoding",
"M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map",
"x = self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model): def initialize(self): #",
"o = self.o(x) + self.ob g = tf.tanh(g) i = tf.sigmoid(i) o =",
"activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2,",
"= self.o(x) + self.ob g = tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o)",
"pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('g_x_stage3')) self.gh = M.ConvLayer(3, 48,",
"hmap, ce], axis=-1) gx = self.gx(x) gh = self.gh(h) ox = self.ox(x) oh",
"fh = self.fh(h) ix = self.ix(x) ih = self.ih(h) g = tf.tanh(gx +",
"tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] #",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2'))",
"self.mc5(x) return out class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9,",
"f = x f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f =",
"self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x",
"= M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID')",
"= self.gh(h) ox = self.ox(x) oh = self.oh(h) fx = self.fx(x) fh =",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3,",
"c = f*c + i*g h = o * tf.tanh(c) # decoder branch",
"self.oh(h) fx = self.fx(x) fh = self.fh(h) ix = self.ix(x) ih = self.ih(h)",
"self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2",
"2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv4_stage2')) # center map self.pool",
"Input for testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32)",
"pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob =",
"values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1'))",
"self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame",
"x = self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model):",
"pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT',",
"g * i h = o * tf.tanh(c) # decoder branch x =",
"= tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh =",
"48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48,",
"pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"= M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x,",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 =",
"self.c6_s1(e) e = self.c7_s1(e) # frame encoding f = dt2 f = self.c1_s2(f)",
"pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch x",
"x, cent) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for testing",
"48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap, cent,",
"self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32))",
"M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2, centermap): #init enc e = dt1",
"self.gb = tf.convert_to_tensor(params2['g_stage3'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh",
"class Stage1(M.Model): def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"self.ib) f = tf.sigmoid(fx + fh + self.fb) c = f*c + i*g",
"if __name__=='__main__': mods = ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent =",
"def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res",
"centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch",
"branch x = tf.concat([f, e, x], axis=-1) g = self.g(x) + self.gb i",
"class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 = Stage1() if __name__=='__main__': mods",
"activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g =",
"48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48,",
"dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f",
"= tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling",
"tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = []",
"= self.mc5(x) return out class ModelBundle(M.Model): def initialize(self): self.s0 = Stage0() self.s1 =",
"values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2'))",
"self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb = tf.Variable(self.fb) self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix =",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15,",
"self.ox = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob",
"activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1 = M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU,",
"self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) #",
"f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f) f =",
"tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3,",
"oh = self.oh(h) fx = self.fx(x) fh = self.fh(h) ix = self.ix(x) ih",
"15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap, cent, h, c) out =",
"= self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f) f = self.c2_s2(f)",
"= self.ih(h) g = tf.tanh(gx + gh + self.gb) o = tf.sigmoid(ox +",
"centermap, h, c): # frame encoding f = x f = self.c1_s2(f) f",
"center map self.pool = M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128,",
"= M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 =",
"center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2'))",
"h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0",
"+ oh + self.ob) i = tf.sigmoid(ix + ih + self.ib) f =",
"self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage1')) self.p3_s1",
"initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 =",
"48, pad='SAME_LEFT', values=get_conv2('o_x_stage3')) self.oh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob",
"self.p1_s2(f) f = self.c2_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p2_s2(f) f",
"self.p2_s2(f) f = self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f",
"= self.fx(x) fh = self.fh(h) ix = self.ix(x) ih = self.ih(h) g =",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 = M.ConvLayer(9, 512, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1,",
"self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128,",
"self.gb = tf.Variable(self.gb) self.fx = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48,",
"np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return",
"= self.c3_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p3_s2(f) f = self.c4_s2(f)",
"= tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) # LSTM branch x = tf.concat([f,",
"np.ones([1,368,368,1]).astype(np.float32) h = c = np.ones([1,46,46, 48]).astype(np.float32) hmap = np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] =",
"2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map self.pool",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9, 128,",
"mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) h = c =",
"values=get_conv2('Mres5_stage3')) def forward(self, x, hmap, centermap, h, c): # frame encoding f =",
"# decoder branch x = self.mc1(h) x = self.mc2(x) x = self.mc3(x) x",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT',",
"M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 = M.ConvLayer(1, 15, values=get_conv2('Mres5_stage3')) def forward(self, x, hmap,",
"= np.ones([1,46,46, 15]).astype(np.float32) x[:,-1] = 0 x = mod(x, hmap, cent, h, c)",
"return res def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape)",
"M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2, pad='VALID') self.c2_s1 = M.ConvLayer(9,",
"= self.ox(x) oh = self.oh(h) fx = self.fx(x) fh = self.fh(h) ix =",
"pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb",
"pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce = self.pool(ce) # lstm branch x",
"pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"# LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb =",
"pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) # decoder branch self.mc1 =",
"print(out) print(out.shape) input('Test deploy1 finished. Input for testing deploy2') mod = mods.s1 x",
"= o * tf.tanh(c) # decoder branch x = self.mc1(h) x = self.mc2(x)",
"self.mc2(x) x = self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out class",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i =",
"48, pad='SAME_LEFT', values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48,",
"out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for saving converted weights",
"def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1",
"self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3'))",
"M.MaxPool(3, 2, pad='VALID') self.c4_s2 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage2')) # center map",
"def initialize(self): # frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2",
"i = tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx + fh +",
"tf.concat([f, e, x], axis=-1) g = self.g(x) + self.gb i = self.i(x) +",
"deploy1 finished. Input for testing deploy2') mod = mods.s1 x = np.ones([1,368,368,3]).astype(np.float32) cent",
"def forward(self, dt1, dt2, centermap): #init enc e = dt1 e = self.c1_s1(e)",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 =",
"tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib)",
"= M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5",
"pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32)) self.fb =",
"f = self.c4_s2(f) # centermap pooling ce = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') ce =",
"values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2'))",
"# center map self.pool = M.AvgPool(9,8, pad='VALID') # lstm self.gx = M.ConvLayer(3, 48,",
"np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2]) print(out)",
"2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2,",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT',",
"self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib",
"gx = self.gx(x) gh = self.gh(h) ox = self.ox(x) oh = self.oh(h) fx",
"tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix + ih + self.ib) f",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage1')) self.p2_s1 = M.MaxPool(3, 2, pad='VALID') self.c3_s1 =",
"= M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 =",
"[] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias']) # print(res[0].shape) return res def get_conv2(name): res =",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres2_stage3')) self.mc3 =",
"self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2",
"x = tf.concat([f, hmap, ce], axis=-1) gx = self.gx(x) gh = self.gh(h) ox",
"mode='SYMMETRIC') e = self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e",
"= tf.sigmoid(i) o = tf.sigmoid(o) c = g * i h = o",
"[[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres3_stage3')) self.mc4 = M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv2('Mres4_stage3')) self.mc5 =",
"branch x = self.mc1(h) x = self.mc2(x) x = self.mc3(x) x = self.mc4(x)",
"self.c2_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2",
"np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name): res = [] # print(params[name]) res.append(params[name]['weights']) res.append(params[name]['bias'])",
"c = g * i h = o * tf.tanh(c) # decoder branch",
"self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p3_s1(e) e",
"= ModelBundle() mod = mods.s0 x = np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x =",
"h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for saving",
"self.c3_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2",
"f = self.p3_s2(f) f = self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]],",
"M.ConvLayer(1, 128, activation=M.PARAM_RELU, values=get_conv('Mconv4_stage2')) self.mc5 = M.ConvLayer(1, 15, values=get_conv('Mconv5_stage2')) def forward(self, dt1, dt2,",
"pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib =",
"self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model): def initialize(self): # frame encoding",
"self.c5_s1(e) e = self.c6_s1(e) e = self.c7_s1(e) # frame encoding f = dt2",
"values=get_conv2('o_h_stage3')) self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3'))",
"res def get_conv2(name): res = [] # print(params[name]) res.append(params2[name]['weights']) res.append(params2[name]['bias']) # print(res[0].shape) return",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 =",
"values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_h_stage3')) self.ib = tf.convert_to_tensor(params2['i_stage3'][1].astype(np.float32)) self.ib = tf.Variable(self.ib)",
"gh + self.gb) o = tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix",
"values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) #",
"import model3 as M import numpy as np import tensorflow as tf params",
"LSTM branch x = tf.concat([f, e, x], axis=-1) g = self.g(x) + self.gb",
"np import tensorflow as tf params = np.load('lstmpm_d1.npy').item() params2 = np.load('lstmpm_d2.npy').item() def get_conv(name):",
"self.gb i = self.i(x) + self.ib o = self.o(x) + self.ob g =",
"oh + self.ob) i = tf.sigmoid(ix + ih + self.ib) f = tf.sigmoid(fx",
"# frame encoding self.c1_s2 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv1_stage2')) self.p1_s2 = M.MaxPool(3,",
"self.ob = tf.convert_to_tensor(params2['o_stage3'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih",
"frame encoding f = dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC')",
"branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2 = M.ConvLayer(11, 128, pad='SAME_LEFT',",
"= tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob =",
"= dt1 e = self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e)",
"= self.mc2(x) x = self.mc3(x) x = self.mc4(x) out = self.mc5(x) return out",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage2')) self.p1_s2 = M.MaxPool(3, 2, pad='VALID') self.c2_s2 = M.ConvLayer(9, 128,",
"= M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('conv3_stage2')) self.p3_s2 = M.MaxPool(3, 2, pad='VALID') self.c4_s2 =",
"pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) # decoder branch self.mc1 =",
"= np.ones([1,368,368,3]).astype(np.float32) cent = np.ones([1,368,368,1]).astype(np.float32) x = mod(x, x, cent) out = np.transpose(x,[0,3,1,2])",
"model3 as M import numpy as np import tensorflow as tf params =",
"pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv5_stage1')) self.c6_s1 = M.ConvLayer(1, 512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15,",
"= M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib = tf.convert_to_tensor(params['i_stage2'][1].astype(np.float32)) self.ib = tf.Variable(self.ib) self.o =",
"= self.mc4(x) out = self.mc5(x) return out class Stage1(M.Model): def initialize(self): # frame",
"self.c4_s2(f) # centermap pooling x = tf.pad(centermap, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') x = self.pool(x) #",
"ce], axis=-1) gx = self.gx(x) gh = self.gh(h) ox = self.ox(x) oh =",
"h, c): # frame encoding f = x f = self.c1_s2(f) f =",
"+ gh + self.gb) o = tf.sigmoid(ox + oh + self.ob) i =",
"512, activation=M.PARAM_RELU, values=get_conv('conv6_stage1')) self.c7_s1 = M.ConvLayer(1, 15, values=get_conv('conv7_stage1')) # frame encoding self.c1_s2 =",
"Stage0(M.Model): def initialize(self): # init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1'))",
"init encoding self.c1_s1 = M.ConvLayer(9, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv1_stage1')) self.p1_s1 = M.MaxPool(3, 2,",
"= tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32)) self.gb = tf.Variable(self.gb) self.i = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('i_x_stage2')) self.ib =",
"self.o = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('o_x_stage2')) self.ob = tf.convert_to_tensor(params['o_stage2'][1].astype(np.float32)) self.ob = tf.Variable(self.ob) #",
"M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv2_stage2')) self.mc3 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv3_stage2')) self.mc4",
"forward(self, dt1, dt2, centermap): #init enc e = dt1 e = self.c1_s1(e) e",
"= self.c1_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e = self.p1_s1(e) e = self.c2_s1(e)",
"e = self.p2_s1(e) e = self.c3_s1(e) e = tf.pad(e, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') e =",
"g = tf.tanh(g) i = tf.sigmoid(i) o = tf.sigmoid(o) c = g *",
"= tf.sigmoid(ox + oh + self.ob) i = tf.sigmoid(ix + ih + self.ib)",
"cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input for",
"hmap, cent, h, c) out = np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy2 finished. Input",
"M.AvgPool(9,8, pad='VALID') # LSTM0 self.g = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv('g_x_stage2')) self.gb = tf.convert_to_tensor(params['g_stage2'][1].astype(np.float32))",
"e, x], axis=-1) g = self.g(x) + self.gb i = self.i(x) + self.ib",
"self.mc1(h) x = self.mc2(x) x = self.mc3(x) x = self.mc4(x) out = self.mc5(x)",
"= M.MaxPool(3, 2, pad='VALID') self.c4_s1 = M.ConvLayer(5, 32, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv4_stage1')) self.c5_s1 =",
"self.c7_s1(e) # frame encoding f = dt2 f = self.c1_s2(f) f = tf.pad(f,",
"= dt2 f = self.c1_s2(f) f = tf.pad(f, [[0,0],[0,1],[0,1],[0,0]], mode='SYMMETRIC') f = self.p1_s2(f)",
"= np.transpose(x,[0,3,1,2]) print(out) print(out.shape) input('Test deploy1 finished. Input for testing deploy2') mod =",
"128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('conv2_stage2')) self.p2_s2 = M.MaxPool(3, 2, pad='VALID') self.c3_s2 = M.ConvLayer(9, 128,",
"= tf.Variable(self.ib) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv2('Mres1_stage3')) self.mc2",
"self.ob = tf.Variable(self.ob) # decoder branch self.mc1 = M.ConvLayer(11, 128, pad='SAME_LEFT', activation=M.PARAM_RELU, values=get_conv('Mconv1_stage2'))",
"= tf.Variable(self.ob) self.ix = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('i_x_stage3')) self.ih = M.ConvLayer(3, 48, pad='SAME_LEFT',",
"M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_x_stage3')) self.fh = M.ConvLayer(3, 48, pad='SAME_LEFT', values=get_conv2('f_h_stage3')) self.fb = tf.convert_to_tensor(params2['f_stage3'][1].astype(np.float32))"
] |
[
"* R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of",
"house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba",
"or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset",
"coordinates should be tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts))",
"param_list): \"\"\"Function for using dataset to train a model and predicting prices for",
"\"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data =",
"columns out of defined columns. Created dummy columns have the name of source",
"the predicted prices for houses in g_data (np.array) \"\"\" # Base Model xgb_reg",
"jit from numba import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join",
"in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\",",
"remaining unnecessary columns in case of differences in airbnb datasets col_list = list(g_data.columns)",
"0, \"t\": 1}) elif rule == \"lengthen\": for l in var_list: dataset[l +",
"ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating",
"house, calculates each venue's influential score on that house with dividing venue's check-in",
"ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\"",
"only the length is considered, similarly listed in src/specs/var_len.txt. Args: | date (str):",
"dataset with venues' latitude, longitude and check_in_counts Returns: house_data with additional column called",
"| data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated",
"using dataset to train a model and predicting prices for a generated data.",
"Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters in",
"from numba import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as",
"20 for i in range(1, 11)], \"min_child_weight\": [i for i in range(3, 12)],",
"prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the",
"and max_depth, min_child_weight, gamma and colsample_bytree can be included. Args: | data (pd.Dataframe):",
") house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list,",
"g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data",
"} # Only includes selected parameters params = {key: params[key] for key in",
"values 'exclude', 'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if rule",
"# Preliminary elimination based on coordinates red_venue_list = np.array( list( filter( lambda x:",
"the name of source column as prefix and \"_\". Function drops the source",
"dataset including house features especially latitude, longitude | venue_data (pd.Dataframe): dataset with venues'",
"= [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item]",
"based on coordinates red_venue_list = np.array( list( filter( lambda x: ( x[0] -",
"data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search, param_list):",
"\"\"\"Function for getting the variable names from txt file and converting into a",
"count with the distance. With that division, score is adjusted to popularity and",
"categorical data | column_list (list): list of columns to get dummy variables Returns:",
"house's score is the mean of relevant venues' influential scores. Args: | house_data",
"to popularity and distance. In the end, that house's score is the mean",
"txt file and converting into a list. Args: keyword (str): the name of",
"for prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe):",
"name also indicating scraping date | venue_data (pd.Dataframe): the dataset including venues' information",
"venue's check-in count with the distance. With that division, score is adjusted to",
"R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng",
"column from the dataset. Args: | data (pd.Dataframe): dataset of interest contaning columns",
"includes selected parameters params = {key: params[key] for key in param_list} xgb_reg =",
"addition, for some features only the length is considered, similarly listed in src/specs/var_len.txt.",
"drops the source column from the dataset. Args: | data (pd.Dataframe): dataset of",
"key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, )",
"l in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else:",
"1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for house in",
"unnecessary columns in case of differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\")",
"in case of differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data =",
"+ \".txt\"), \"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset,",
"for i in range(3, 8)], \"subsample\": [i / 10.0 for i in range(7,",
"calculates each venue's influential score on that house with dividing venue's check-in count",
"airbnb dataset including house features especially latitude, longitude | venue_data (pd.Dataframe): dataset with",
"a part of airbnb dataset's name also indicating scraping date | venue_data (pd.Dataframe):",
"in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: #",
"can be included. Args: | data (pd.Dataframe): the dataset including house features and",
"g_data (pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date +",
"2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) ** 2",
"distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: # venues closer than 1",
"= pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function for data",
"xgboost as xgb from numba import jit from numba import prange from sklearn.model_selection",
"i in range(1, 11)], \"min_child_weight\": [i for i in range(3, 12)], \"gamma\": [i",
"Returns: the altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list,",
"\"max_depth\": [i for i in range(3, 8)], } # Only includes selected parameters",
"( np.sin((venue_lat - house_lat) / 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) *",
"also indicating scraping date | venue_data (pd.Dataframe): the dataset including venues' information |",
"< 0.01), # longitude venue_data_list, ) ) ) score_list = np.array(0) for ven",
"11)], \"min_child_weight\": [i for i in range(3, 12)], \"gamma\": [i / 10.0 for",
"# approximate radius of earth in km R = 6373.0 house_lat = np.deg2rad(house[0])",
"(pd.Dataframe): airbnb dataset including house features especially latitude, longitude | venue_data (pd.Dataframe): dataset",
"\"\"\"Inside function for numba application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination",
"that house, calculates each venue's influential score on that house with dividing venue's",
"venue): \"\"\"Function for calculating the distance between a house and a venue while",
"taking world's shape into consideration. Args: | house (list): list including latitude and",
"and colsample_bytree can be included. Args: | data (pd.Dataframe): the dataset including house",
"with parameter search(True) or use default values(False) | param_list (list): the list of",
"= pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data )",
"list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data),",
"pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date = sys.argv[1]",
"in range(6, 11)], \"max_depth\": [i for i in range(3, 8)], } # Only",
"features and prices | g_data (pd.Dataframe): randomly generated house features for prediction purposes",
"in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise",
"not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the distance",
"/ cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return",
"house and venues within 1 km radius of that house, calculates each venue's",
"# Preparing data for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] )",
"check-in count with the distance. With that division, score is adjusted to popularity",
"the length is considered, similarly listed in src/specs/var_len.txt. Args: | date (str): a",
"exclusion, conversion and length generation. Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert)",
"(data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) #",
"txt file Returns: the list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword +",
"called location_score (pd.Dataframe) \"\"\" # coordinates should be tuples for geopy.distance function venue_data_list",
"excludes variable from the dataset. Conversion(convert) rule converts \"f\" and \"t\" values into",
"include apartments and exclude Shared rooms for simplicity data = ( data.loc[ (data[\"room_type\"]",
"'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset =",
"columns in case of differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data",
"if cal_dist < 1: # venues closer than 1 km np.append(score_list, red_venue_list[ven][2] /",
"reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date",
"pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction",
"* np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of a house.",
"data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset to train",
"/ 10.0 for i in range(6, 11)], \"max_depth\": [i for i in range(3,",
"np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data,",
"purposes | grid_search (bool): indicates whether model is trained with parameter search(True) or",
"applying data management rule on dataset with given variable names. Variable names should",
"rule excludes variable from the dataset. Conversion(convert) rule converts \"f\" and \"t\" values",
"date (str): a part of airbnb dataset's name also indicating scraping date |",
"# venues closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return",
"the approximate distance (float) \"\"\" # approximate radius of earth in km R",
"variable name and exclude variable from dataset. Args: | var_list (list): list of",
"for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data,",
"open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as",
"house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate):",
"parameter search(True) or use default values(False) | param_list (list): the list of parameters",
"predicting prices for a generated data. Parameter search is done using RandomizedSearchCV since",
"data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\",",
"/ 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) /",
"dummy variables Returns: the altered dataset with dummy variable columns (pd.Dataframe) \"\"\" for",
".copy() .reset_index() ) # Calculate the location score of each house data =",
"return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\")",
"house features for prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset |",
"prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list = np.array( list( filter( lambda",
"for i in range(3, 12)], \"gamma\": [i / 10.0 for i in range(3,",
"column names. Defined rules are exclusion, conversion and length generation. Exclusion(exclude) rule excludes",
"param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__",
"process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\"",
"np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] =",
"R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of a",
"apply | dataset (pd.Dataframe): dataset to implement the rule | rule (str): can",
"\"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\":",
"data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data, g_data):",
"name of source column as prefix and \"_\". Function drops the source column",
"selected parameters params = {key: params[key] for key in param_list} xgb_reg = RandomizedSearchCV(",
"information | g_data (pd.Dataframe): randomly generated house features for prediction Returns: | data",
"score is adjusted to popularity and distance. In the end, that house's score",
"names should match with dataset's column names. Defined rules are exclusion, conversion and",
"(str): a part of airbnb dataset's name also indicating scraping date | venue_data",
"\"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"),",
"especially latitude, longitude | venue_data (pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts",
"name and exclude variable from dataset. Args: | var_list (list): list of variables",
"whether model is trained with parameter search(True) or use default values(False) | param_list",
"loads the airbnb dataset and rearranges both airbnb and generated dataset for prediction.",
"the rule | rule (str): can take values 'exclude', 'convert' or 'lengthen' Returns:",
"venue_data_list, ) ) ) score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist =",
"= pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1)",
"\"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data",
"venue's influential score on that house with dividing venue's check-in count with the",
"house (list): list including latitude and longitude of a house | venue (list):",
"np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for house",
"def rule_func(var_list, dataset, rule): \"\"\"Function for applying data management rule on dataset with",
"should have values either \"f\" or \"t\". Length generator(lengthen) rule gets the string",
"distance between a house and a venue while taking world's shape into consideration.",
"including latitude and longitude of a house | venue (list): list including latitude",
"management. It loads the airbnb dataset and rearranges both airbnb and generated dataset",
"generated house features for prediction purposes | grid_search (bool): indicates whether model is",
"+ \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False) # Data clearing process",
"be included. Args: | data (pd.Dataframe): the dataset including house features and prices",
"data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"),",
"tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate =",
"rule=rule) # Only include apartments and exclude Shared rooms for simplicity data =",
"house data = score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data = dummy_func(",
"length is considered, similarly listed in src/specs/var_len.txt. Args: | date (str): a part",
"dataset to train a model and predicting prices for a generated data. Parameter",
"distance. With that division, score is adjusted to popularity and distance. In the",
"\"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column,",
"= data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search,",
"= data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data,",
"for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"]",
"__name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue",
"= dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\") return",
"to get dummy variables Returns: the altered dataset with dummy variable columns (pd.Dataframe)",
"with dummy variable columns (pd.Dataframe) \"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column",
"latitude, longitude | venue_data (pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts Returns:",
"room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) # Calculate the location",
"data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns in case of",
"airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [",
"var_list (list): list of variables to apply | dataset (pd.Dataframe): dataset to implement",
"of source column as prefix and \"_\". Function drops the source column from",
"numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy",
"altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as",
"= data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for",
"venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) )",
"generated data. Parameter search is done using RandomizedSearchCV since it is computationally more",
"filter( lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude &",
"/ 10.0 for i in range(7, 11)], \"colsample_bytree\": [i / 10.0 for i",
"rule_list: var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only",
"return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list):",
"pd import xgboost as xgb from numba import jit from numba import prange",
"values into 0 and 1 respectively. Thus variable should have values either \"f\"",
"return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying data management rule on",
"the dataset. Conversion(convert) rule converts \"f\" and \"t\" values into 0 and 1",
"(pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated data \"\"\"",
"\"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list",
"range(3, 8)], } # Only includes selected parameters params = {key: params[key] for",
"house features and prices | g_data (pd.Dataframe): randomly generated house features for prediction",
"\"\"\" # coordinates should be tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude,",
"\"\"\"Function for applying data management rule on dataset with given variable names. Variable",
"Args: | var_list (list): list of variables to apply | dataset (pd.Dataframe): dataset",
"\"\"\" # approximate radius of earth in km R = 6373.0 house_lat =",
"and longitude of a venue Returns: the approximate distance (float) \"\"\" # approximate",
"data (pd.Dataframe): dataset of interest contaning columns with categorical data | column_list (list):",
"for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist <",
"[\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data",
"calculating the distance between a house and a venue while taking world's shape",
"= dataset.drop(var_list, axis=1) elif rule == \"convert\": for c in var_list: dataset[c] =",
"\"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int)",
"train a model and predicting prices for a generated data. Parameter search is",
"in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item",
"dataset to implement the rule | rule (str): can take values 'exclude', 'convert'",
"& (x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) ) ) score_list",
"and 1 respectively. Thus variable should have values either \"f\" or \"t\". Length",
"data management. It loads the airbnb dataset and rearranges both airbnb and generated",
"open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\")) def",
"take values 'exclude', 'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if",
"columns to get dummy variables Returns: the altered dataset with dummy variable columns",
"for simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] ==",
"dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True)",
"as xgb from numba import jit from numba import prange from sklearn.model_selection import",
"0.01 ) # latitude & (x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list,",
"column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data = pd.concat([data,",
"list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\",",
"def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for house in prange(len(house_data_coordinate)):",
"in g_data (np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: #",
"data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] )",
"both airbnb and generated dataset for prediction. A certain amount of house features",
") g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary",
"\"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function",
"adjusted to popularity and distance. In the end, that house's score is the",
"numpy as np import pandas as pd import xgboost as xgb from numba",
"Returns: house_data with additional column called location_score (pd.Dataframe) \"\"\" # coordinates should be",
"longitude of a venue Returns: the approximate distance (float) \"\"\" # approximate radius",
"score on that house with dividing venue's check-in count with the distance. With",
"is the mean of relevant venues' influential scores. Args: | house_data (pd.Dataframe): airbnb",
"(x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) ) ) score_list =",
"import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def",
"a house and venues within 1 km radius of that house, calculates each",
"In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree can be included.",
"dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns in case",
"np.array( list( filter( lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01 ) #",
"into consideration. Args: | house (list): list including latitude and longitude of a",
"\"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop",
"from the dataset. Conversion(convert) rule converts \"f\" and \"t\" values into 0 and",
"colsample_bytree can be included. Args: | data (pd.Dataframe): the dataset including house features",
"for i in range(1, 11)], \"min_child_weight\": [i for i in range(3, 12)], \"gamma\":",
"8)], \"subsample\": [i / 10.0 for i in range(7, 11)], \"colsample_bytree\": [i /",
"Returns: the predicted prices for houses in g_data (np.array) \"\"\" # Base Model",
"rule | rule (str): can take values 'exclude', 'convert' or 'lengthen' Returns: the",
"10.0 for i in range(7, 11)], \"colsample_bytree\": [i / 10.0 for i in",
"(float) \"\"\" # approximate radius of earth in km R = 6373.0 house_lat",
"if __name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c:",
"def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset to train a model",
"rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\": for c",
"def list_generator(keyword): \"\"\"Function for getting the variable names from txt file and converting",
"from dataset. Args: | var_list (list): list of variables to apply | dataset",
"data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] =",
"house and a venue while taking world's shape into consideration. Args: | house",
"dataset.drop(var_list, axis=1) elif rule == \"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\":",
"venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) /",
"\"\"\"Function for creating dummy variable columns out of defined columns. Created dummy columns",
"range(3, 8)], \"subsample\": [i / 10.0 for i in range(7, 11)], \"colsample_bytree\": [i",
"** 2 ) return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function",
"(pd.Dataframe) \"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data =",
"min_child_weight, gamma and colsample_bytree can be included. Args: | data (pd.Dataframe): the dataset",
"data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data,",
"import pandas as pd import xgboost as xgb from numba import jit from",
"gets a house and venues within 1 km radius of that house, calculates",
"i in range(7, 11)], \"colsample_bytree\": [i / 10.0 for i in range(6, 11)],",
"data = ( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ]",
") xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data",
"sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data,",
"generated house features for prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset",
"data | column_list (list): list of columns to get dummy variables Returns: the",
"project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting the variable names from txt",
"grid_search (bool): indicates whether model is trained with parameter search(True) or use default",
"c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g)",
"g: generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue,",
"columns. Created dummy columns have the name of source column as prefix and",
"end, that house's score is the mean of relevant venues' influential scores. Args:",
"xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters in model params",
"from bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting the variable",
"= RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return",
"get dummy variables Returns: the altered dataset with dummy variable columns (pd.Dataframe) \"\"\"",
"\"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g:",
"name of txt file Returns: the list of variable names \"\"\" with open(ppj(\"IN_SPECS\",",
") return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating",
"Length generator(lengthen) rule gets the string lenght, adds \"_len\" to variable name and",
"for numba application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination based on",
") score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2]",
"venues' information | g_data (pd.Dataframe): randomly generated house features for prediction Returns: |",
"rule on dataset with given variable names. Variable names should match with dataset's",
"data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"),",
"generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data",
"dividing venue's check-in count with the distance. With that division, score is adjusted",
"shape into consideration. Args: | house (list): list including latitude and longitude of",
"can be found in src/specs/var_exclude.txt. In addition, for some features only the length",
"= dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\",",
"g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset to train a",
"conversion and length generation. Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert) rule",
"params = {key: params[key] for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params,",
"Args: | house (list): list including latitude and longitude of a house |",
"from txt file and converting into a list. Args: keyword (str): the name",
"dataset, rule): \"\"\"Function for applying data management rule on dataset with given variable",
"| dataset (pd.Dataframe): dataset to implement the rule | rule (str): can take",
"pandas as pd import xgboost as xgb from numba import jit from numba",
"# Only includes selected parameters params = {key: params[key] for key in param_list}",
"listed in src/specs/var_len.txt. Args: | date (str): a part of airbnb dataset's name",
"house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) ) ) score_list = np.array(0) for",
"house | venue (list): list including latitude and longitude of a venue Returns:",
"dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\": for c in var_list: dataset[c]",
"in src/specs/var_exclude.txt. In addition, for some features only the length is considered, similarly",
"longitude of a house | venue (list): list including latitude and longitude of",
"Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered",
"file and converting into a list. Args: keyword (str): the name of txt",
"of a house | venue (list): list including latitude and longitude of a",
"param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree can be included. Args:",
"search(True) or use default values(False) | param_list (list): the list of parameters to",
"In addition, for some features only the length is considered, similarly listed in",
"predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"), \"w\") as p:",
"with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date = sys.argv[1] data,",
"as f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for",
"it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and max_depth,",
"= np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside",
"= sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func(",
"\"f\" or \"t\". Length generator(lengthen) rule gets the string lenght, adds \"_len\" to",
"and longitude of a house | venue (list): list including latitude and longitude",
"for some features only the length is considered, similarly listed in src/specs/var_len.txt. Args:",
"data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data,",
"latitude and longitude of a house | venue (list): list including latitude and",
"= ( np.sin((venue_lat - house_lat) / 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat)",
"as pd import xgboost as xgb from numba import jit from numba import",
"in km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat =",
"the altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1)",
"venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) / 2) ** 2",
"mean of relevant venues' influential scores. Args: | house_data (pd.Dataframe): airbnb dataset including",
"(pd.Dataframe): dataset of interest contaning columns with categorical data | column_list (list): list",
"for getting the variable names from txt file and converting into a list.",
"exclude Shared rooms for simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared room\")",
"longitude and check_in_counts Returns: house_data with additional column called location_score (pd.Dataframe) \"\"\" #",
"should be tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) )",
"(str): can take values 'exclude', 'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe)",
"# Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with",
"keyword (str): the name of txt file Returns: the list of variable names",
"\"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False) # Data clearing process rule_list",
"Search for best parameters in model params = { \"learning_rate\": [i / 20",
"# Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters",
"prices | g_data (pd.Dataframe): randomly generated house features for prediction purposes | grid_search",
"prefix and \"_\". Function drops the source column from the dataset. Args: |",
"\"rb\") as d: data = pd.read_csv(d, low_memory=False) # Data clearing process rule_list =",
"g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns",
"features are excluded, the list can be found in src/specs/var_exclude.txt. In addition, for",
"\".txt\"), \"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule):",
"- house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1] - house_data_coordinate[0][1] < 0.01),",
"house features are excluded, the list can be found in src/specs/var_exclude.txt. In addition,",
"# Drop remaining unnecessary columns in case of differences in airbnb datasets col_list",
"venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1])",
"application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list",
"= np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat -",
"the string lenght, adds \"_len\" to variable name and exclude variable from dataset.",
"parameter search Returns: the predicted prices for houses in g_data (np.array) \"\"\" #",
"search Returns: the predicted prices for houses in g_data (np.array) \"\"\" # Base",
"** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) **",
"params[key] for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23,",
"with venues' latitude, longitude and check_in_counts Returns: house_data with additional column called location_score",
"columns have the name of source column as prefix and \"_\". Function drops",
"- house_lat) / 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng -",
"as np import pandas as pd import xgboost as xgb from numba import",
"on coordinates red_venue_list = np.array( list( filter( lambda x: ( x[0] - house_data_coordinate[0][0]",
"data = pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function for",
"list can be found in src/specs/var_exclude.txt. In addition, for some features only the",
"Preparing data for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data",
"numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for house in prange(len(house_data_coordinate)): #",
"\"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining",
"since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and",
"model is trained with parameter search(True) or use default values(False) | param_list (list):",
"parameters in model params = { \"learning_rate\": [i / 20 for i in",
"and venues within 1 km radius of that house, calculates each venue's influential",
"\"min_child_weight\": [i for i in range(3, 12)], \"gamma\": [i / 10.0 for i",
"model params = { \"learning_rate\": [i / 20 for i in range(1, 11)],",
"in range(3, 12)], \"gamma\": [i / 10.0 for i in range(3, 8)], \"subsample\":",
"in range(3, 8)], \"subsample\": [i / 10.0 for i in range(7, 11)], \"colsample_bytree\":",
"of variables to apply | dataset (pd.Dataframe): dataset to implement the rule |",
"to implement the rule | rule (str): can take values 'exclude', 'convert' or",
"prices for houses in g_data (np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1)",
"variable columns out of defined columns. Created dummy columns have the name of",
"for l in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1)",
"c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\":",
"should match with dataset's column names. Defined rules are exclusion, conversion and length",
"keyword + \".txt\"), \"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list,",
"rules are exclusion, conversion and length generation. Exclusion(exclude) rule excludes variable from the",
"== \"Apartment\"), ] .copy() .reset_index() ) # Calculate the location score of each",
"features especially latitude, longitude | venue_data (pd.Dataframe): dataset with venues' latitude, longitude and",
"for a generated data. Parameter search is done using RandomizedSearchCV since it is",
"as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data =",
"np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) ** 2 ) return 2 *",
"\"t\" values into 0 and 1 respectively. Thus variable should have values either",
"[i / 20 for i in range(1, 11)], \"min_child_weight\": [i for i in",
"axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\",",
"search is done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV.",
"'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\":",
"| data (pd.Dataframe): dataset of interest contaning columns with categorical data | column_list",
"open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False)",
"location score of each house data = score_func(house_data=data, venue_data=venue_data) # Preparing data for",
") prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df =",
"grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with",
"be tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate",
"differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list",
"that house with dividing venue's check-in count with the distance. With that division,",
"n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ ==",
") ) score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house],",
"trained with parameter search(True) or use default values(False) | param_list (list): the list",
"out of defined columns. Created dummy columns have the name of source column",
"axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function for data management. It loads",
"(list): the list of parameters to be included in parameter search Returns: the",
"- house_lng) / 2) ** 2 ) return 2 * R * np.arcsin(np.sqrt(dist))",
"house in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list = np.array( list(",
"\"_\")) data = data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return data def",
"latitude and longitude of a venue Returns: the approximate distance (float) \"\"\" #",
"11)], \"max_depth\": [i for i in range(3, 8)], } # Only includes selected",
"data = pd.read_csv(d, low_memory=False) # Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"]",
"g_data (pd.Dataframe): randomly generated house features for prediction Returns: | data (pd.Dataframe): the",
"np import pandas as pd import xgboost as xgb from numba import jit",
"dataset | g_data (pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" +",
"string lenght, adds \"_len\" to variable name and exclude variable from dataset. Args:",
"house. Function gets a house and venues within 1 km radius of that",
"pd.read_csv(d, low_memory=False) # Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule",
"sys import numpy as np import pandas as pd import xgboost as xgb",
"radius of earth in km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng =",
"altered dataset with dummy variable columns (pd.Dataframe) \"\"\" for column in column_list: temp_data",
"(pd.Dataframe) \"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule ==",
"location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function",
"is considered, similarly listed in src/specs/var_len.txt. Args: | date (str): a part of",
"(data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) # Calculate the location score of",
"# Search for best parameters in model params = { \"learning_rate\": [i /",
"\"colsample_bytree\": [i / 10.0 for i in range(6, 11)], \"max_depth\": [i for i",
"computationally more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma",
"\"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list,",
"management rule on dataset with given variable names. Variable names should match with",
"exclude variable from dataset. Args: | var_list (list): list of variables to apply",
"km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0])",
"var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule",
"cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\",",
"prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) #",
"currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data,",
"elif rule == \"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\":",
"venues within 1 km radius of that house, calculates each venue's influential score",
"\"cancellation_policy\"] ) # Drop remaining unnecessary columns in case of differences in airbnb",
"{ \"learning_rate\": [i / 20 for i in range(1, 11)], \"min_child_weight\": [i for",
"Defined rules are exclusion, conversion and length generation. Exclusion(exclude) rule excludes variable from",
"lenght, adds \"_len\" to variable name and exclude variable from dataset. Args: |",
"Conversion(convert) rule converts \"f\" and \"t\" values into 0 and 1 respectively. Thus",
"= dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def",
"world's shape into consideration. Args: | house (list): list including latitude and longitude",
"2 ) return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for",
"Args: keyword (str): the name of txt file Returns: the list of variable",
"of a house. Function gets a house and venues within 1 km radius",
"radius of that house, calculates each venue's influential score on that house with",
"and prices | g_data (pd.Dataframe): randomly generated house features for prediction purposes |",
"prediction purposes | grid_search (bool): indicates whether model is trained with parameter search(True)",
"\"\"\"Function for calculating the distance between a house and a venue while taking",
"\"t\". Length generator(lengthen) rule gets the string lenght, adds \"_len\" to variable name",
"scores. Args: | house_data (pd.Dataframe): airbnb dataset including house features especially latitude, longitude",
"< 1: # venues closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list,",
"column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data",
"+ \"_\")) data = data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return data",
"in src/specs/var_len.txt. Args: | date (str): a part of airbnb dataset's name also",
"= list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\",",
"features only the length is considered, similarly listed in src/specs/var_len.txt. Args: | date",
"prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction,",
"(list): list of columns to get dummy variables Returns: the altered dataset with",
"rule): \"\"\"Function for applying data management rule on dataset with given variable names.",
"{key: params[key] for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3,",
"relevant venues' influential scores. Args: | house_data (pd.Dataframe): airbnb dataset including house features",
"for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1)",
"house features for prediction purposes | grid_search (bool): indicates whether model is trained",
"source column as prefix and \"_\". Function drops the source column from the",
"list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f:",
"score is the mean of relevant venues' influential scores. Args: | house_data (pd.Dataframe):",
"score of each house data = score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling",
"\"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list =",
"and generated dataset for prediction. A certain amount of house features are excluded,",
"dataset of interest contaning columns with categorical data | column_list (list): list of",
"data. Parameter search is done using RandomizedSearchCV since it is computationally more efficientcompared",
"| house_data (pd.Dataframe): airbnb dataset including house features especially latitude, longitude | venue_data",
"the mean of relevant venues' influential scores. Args: | house_data (pd.Dataframe): airbnb dataset",
"excluded, the list can be found in src/specs/var_exclude.txt. In addition, for some features",
"dataset. Args: | var_list (list): list of variables to apply | dataset (pd.Dataframe):",
"\"learning_rate\": [i / 20 for i in range(1, 11)], \"min_child_weight\": [i for i",
"range(1, 11)], \"min_child_weight\": [i for i in range(3, 12)], \"gamma\": [i / 10.0",
"indicating scraping date | venue_data (pd.Dataframe): the dataset including venues' information | g_data",
"8)], } # Only includes selected parameters params = {key: params[key] for key",
"to apply | dataset (pd.Dataframe): dataset to implement the rule | rule (str):",
"| grid_search (bool): indicates whether model is trained with parameter search(True) or use",
"10.0 for i in range(6, 11)], \"max_depth\": [i for i in range(3, 8)],",
"(pd.Dataframe): dataset to implement the rule | rule (str): can take values 'exclude',",
"numba import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj",
") # Drop remaining unnecessary columns in case of differences in airbnb datasets",
"- house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) ) ) score_list = np.array(0)",
"on that house with dividing venue's check-in count with the distance. With that",
"(pd.Dataframe): randomly generated house features for prediction purposes | grid_search (bool): indicates whether",
"features for prediction purposes | grid_search (bool): indicates whether model is trained with",
"Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters in model",
"date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"],",
"else: raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function",
"of a venue Returns: the approximate distance (float) \"\"\" # approximate radius of",
"venues' influential scores. Args: | house_data (pd.Dataframe): airbnb dataset including house features especially",
"house features especially latitude, longitude | venue_data (pd.Dataframe): dataset with venues' latitude, longitude",
"a list. Args: keyword (str): the name of txt file Returns: the list",
"to GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree can",
"in range(3, 8)], } # Only includes selected parameters params = {key: params[key]",
"and exclude variable from dataset. Args: | var_list (list): list of variables to",
"= pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date =",
"np.sin((venue_lng - house_lng) / 2) ** 2 ) return 2 * R *",
"date + \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False) # Data clearing",
") # Calculate the location score of each house data = score_func(house_data=data, venue_data=venue_data)",
"var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying data",
"elif rule == \"lengthen\": for l in var_list: dataset[l + \"_len\"] = dataset[l].str.len()",
"of differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1)",
"!= \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) # Calculate",
"distance_calc(house, venue): \"\"\"Function for calculating the distance between a house and a venue",
"location_score (pd.Dataframe) \"\"\" # coordinates should be tuples for geopy.distance function venue_data_list =",
"temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data = pd.concat([data, temp_data],",
"variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read =",
"red_venue_list[ven][0:2] ) if cal_dist < 1: # venues closer than 1 km np.append(score_list,",
"list including latitude and longitude of a venue Returns: the approximate distance (float)",
"venue while taking world's shape into consideration. Args: | house (list): list including",
"for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array(",
"\"Apartment\"), ] .copy() .reset_index() ) # Calculate the location score of each house",
"\"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item] = data[item].fillna(0)",
"1 respectively. Thus variable should have values either \"f\" or \"t\". Length generator(lengthen)",
"= ( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy()",
"data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\",",
"that house's score is the mean of relevant venues' influential scores. Args: |",
"Args: | data (pd.Dataframe): the dataset including house features and prices | g_data",
"of house features are excluded, the list can be found in src/specs/var_exclude.txt. In",
"/ 20 for i in range(1, 11)], \"min_child_weight\": [i for i in range(3,",
"| column_list (list): list of columns to get dummy variables Returns: the altered",
"src/specs/var_exclude.txt. In addition, for some features only the length is considered, similarly listed",
"variable names from txt file and converting into a list. Args: keyword (str):",
"and distance. In the end, that house's score is the mean of relevant",
"data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using",
"venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], )",
"= score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data = dummy_func( data=data, column_list=[\"room_type\",",
"the source column from the dataset. Args: | data (pd.Dataframe): dataset of interest",
"Thus variable should have values either \"f\" or \"t\". Length generator(lengthen) rule gets",
"for using dataset to train a model and predicting prices for a generated",
"given variable names. Variable names should match with dataset's column names. Defined rules",
"= list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments",
"= rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and exclude Shared rooms for",
"\"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\",",
"= data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\",",
"2) ** 2 ) return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data):",
"case of differences in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list,",
"to variable name and exclude variable from dataset. Args: | var_list (list): list",
"is trained with parameter search(True) or use default values(False) | param_list (list): the",
"item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data",
"have the name of source column as prefix and \"_\". Function drops the",
"pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function for data management.",
"if grid_search: # Search for best parameters in model params = { \"learning_rate\":",
"RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample",
"is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight,",
"and check_in_counts Returns: house_data with additional column called location_score (pd.Dataframe) \"\"\" # coordinates",
"[i / 10.0 for i in range(7, 11)], \"colsample_bytree\": [i / 10.0 for",
"Args: | house_data (pd.Dataframe): airbnb dataset including house features especially latitude, longitude |",
"column_list): \"\"\"Function for creating dummy variable columns out of defined columns. Created dummy",
"popularity and distance. In the end, that house's score is the mean of",
"in range(7, 11)], \"colsample_bytree\": [i / 10.0 for i in range(6, 11)], \"max_depth\":",
"| var_list (list): list of variables to apply | dataset (pd.Dataframe): dataset to",
"the dataset including house features and prices | g_data (pd.Dataframe): randomly generated house",
"approximate radius of earth in km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng",
"location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns out",
"[i / 10.0 for i in range(3, 8)], \"subsample\": [i / 10.0 for",
"iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load",
"km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"]",
"= [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule)",
"Variable names should match with dataset's column names. Defined rules are exclusion, conversion",
"for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule ==",
"data = score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data = dummy_func( data=data,",
"dummy variable columns (pd.Dataframe) \"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column +",
"names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read = f.read()",
"included. Args: | data (pd.Dataframe): the dataset including house features and prices |",
"(bool): indicates whether model is trained with parameter search(True) or use default values(False)",
"(np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for",
"dataset including venues' information | g_data (pd.Dataframe): randomly generated house features for prediction",
"\"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"), \"w\")",
"the list can be found in src/specs/var_exclude.txt. In addition, for some features only",
"distance. In the end, that house's score is the mean of relevant venues'",
"\"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c)",
"ppj def list_generator(keyword): \"\"\"Function for getting the variable names from txt file and",
"between a house and a venue while taking world's shape into consideration. Args:",
"column_list (list): list of columns to get dummy variables Returns: the altered dataset",
"for data management. It loads the airbnb dataset and rearranges both airbnb and",
"= data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for",
"dataset=data, rule=rule) # Only include apartments and exclude Shared rooms for simplicity data",
") predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"), \"w\") as",
"adds \"_len\" to variable name and exclude variable from dataset. Args: | var_list",
"latitude & (x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) ) )",
"# longitude venue_data_list, ) ) ) score_list = np.array(0) for ven in prange(len(red_venue_list)):",
"in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\": for",
"import sys import numpy as np import pandas as pd import xgboost as",
"and exclude Shared rooms for simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared",
"nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in",
"as prefix and \"_\". Function drops the source column from the dataset. Args:",
"estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if",
"(pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"),",
"return house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns out of",
"randomly generated house features for prediction purposes | grid_search (bool): indicates whether model",
"numba application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates",
"in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data =",
"g_data (np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search",
"dummy columns have the name of source column as prefix and \"_\". Function",
"house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary",
"check_in_counts Returns: house_data with additional column called location_score (pd.Dataframe) \"\"\" # coordinates should",
"indicates whether model is trained with parameter search(True) or use default values(False) |",
"getting the variable names from txt file and converting into a list. Args:",
"[ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item] =",
"\"t\": 1}) elif rule == \"lengthen\": for l in var_list: dataset[l + \"_len\"]",
"and \"t\" values into 0 and 1 respectively. Thus variable should have values",
"default values(False) | param_list (list): the list of parameters to be included in",
"the dataset. Args: | data (pd.Dataframe): dataset of interest contaning columns with categorical",
"of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read",
"for i in range(7, 11)], \"colsample_bytree\": [i / 10.0 for i in range(6,",
"influential score on that house with dividing venue's check-in count with the distance.",
"house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1] - house_data_coordinate[0][1] < 0.01), #",
"dataset and rearranges both airbnb and generated dataset for prediction. A certain amount",
"the variable names from txt file and converting into a list. Args: keyword",
"def distance_calc(house, venue): \"\"\"Function for calculating the distance between a house and a",
"list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying data management rule on dataset",
"| venue (list): list including latitude and longitude of a venue Returns: the",
"generator(lengthen) rule gets the string lenght, adds \"_len\" to variable name and exclude",
"np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) ** 2 ) return",
"house with dividing venue's check-in count with the distance. With that division, score",
"x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1] - house_data_coordinate[0][1] <",
"column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns in case of differences",
"max_depth, min_child_weight, gamma and colsample_bytree can be included. Args: | data (pd.Dataframe): the",
"currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\")",
"earth in km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat",
"variables Returns: the altered dataset with dummy variable columns (pd.Dataframe) \"\"\" for column",
"the list of parameters to be included in parameter search Returns: the predicted",
"\"subsample\": [i / 10.0 for i in range(7, 11)], \"colsample_bytree\": [i / 10.0",
"the distance between a house and a venue while taking world's shape into",
"\"\"\"Function for using dataset to train a model and predicting prices for a",
"for house in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list = np.array(",
"with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\")",
"for prediction. A certain amount of house features are excluded, the list can",
"house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat",
"part of airbnb dataset's name also indicating scraping date | venue_data (pd.Dataframe): the",
"gets the string lenght, adds \"_len\" to variable name and exclude variable from",
"the dataset including venues' information | g_data (pd.Dataframe): randomly generated house features for",
"It loads the airbnb dataset and rearranges both airbnb and generated dataset for",
"g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df",
"prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def list_generator(keyword):",
"= 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng =",
"dataset. Args: | data (pd.Dataframe): dataset of interest contaning columns with categorical data",
"Shared rooms for simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared room\") &",
"values(False) | param_list (list): the list of parameters to be included in parameter",
"'exclude', 'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\" if rule ==",
"/ 2) ** 2 ) return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data,",
"# coordinates should be tuples for geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude,",
"\"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\")",
"variable from the dataset. Conversion(convert) rule converts \"f\" and \"t\" values into 0",
"of txt file Returns: the list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword",
"venue Returns: the approximate distance (float) \"\"\" # approximate radius of earth in",
"some features only the length is considered, similarly listed in src/specs/var_len.txt. Args: |",
"def data_management(date, venue_data, g_data): \"\"\"Function for data management. It loads the airbnb dataset",
"= xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters in model params =",
"return 2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based",
"is not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the",
"certain amount of house features are excluded, the list can be found in",
"\"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d: data =",
"g_data, grid_search, param_list): \"\"\"Function for using dataset to train a model and predicting",
"best parameters in model params = { \"learning_rate\": [i / 20 for i",
"date = sys.argv[1] data, generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction =",
"range(3, 12)], \"gamma\": [i / 10.0 for i in range(3, 8)], \"subsample\": [i",
"dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule",
"in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) #",
"that division, score is adjusted to popularity and distance. In the end, that",
"venues closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list",
"implement the rule | rule (str): can take values 'exclude', 'convert' or 'lengthen'",
"| house (list): list including latitude and longitude of a house | venue",
"the airbnb dataset and rearranges both airbnb and generated dataset for prediction. A",
"of parameters to be included in parameter search Returns: the predicted prices for",
"| venue_data (pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts Returns: house_data with",
"date | venue_data (pd.Dataframe): the dataset including venues' information | g_data (pd.Dataframe): randomly",
"| data (pd.Dataframe): the dataset including house features and prices | g_data (pd.Dataframe):",
"scraping date | venue_data (pd.Dataframe): the dataset including venues' information | g_data (pd.Dataframe):",
"= pd.read_csv(d, low_memory=False) # Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for",
"coordinates red_venue_list = np.array( list( filter( lambda x: ( x[0] - house_data_coordinate[0][0] <",
"each house data = score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data =",
"features for prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data",
"location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for",
"source column from the dataset. Args: | data (pd.Dataframe): dataset of interest contaning",
"\"\"\"Function for calculating location-based score of a house. Function gets a house and",
"0.01), # longitude venue_data_list, ) ) ) score_list = np.array(0) for ven in",
"= np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) / 2) ** 2 +",
"dataset's name also indicating scraping date | venue_data (pd.Dataframe): the dataset including venues'",
"of earth in km R = 6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1])",
"Args: | data (pd.Dataframe): dataset of interest contaning columns with categorical data |",
"data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d: data",
"houses in g_data (np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search:",
"item in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for",
"for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False,",
"axis=1) else: raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue):",
"range(7, 11)], \"colsample_bytree\": [i / 10.0 for i in range(6, 11)], \"max_depth\": [i",
"np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function",
"of columns to get dummy variables Returns: the altered dataset with dummy variable",
"for houses in g_data (np.array) \"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if",
"house_data (pd.Dataframe): airbnb dataset including house features especially latitude, longitude | venue_data (pd.Dataframe):",
"division, score is adjusted to popularity and distance. In the end, that house's",
"i in range(3, 8)], \"subsample\": [i / 10.0 for i in range(7, 11)],",
"i in range(3, 8)], } # Only includes selected parameters params = {key:",
"a venue Returns: the approximate distance (float) \"\"\" # approximate radius of earth",
") # latitude & (x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, )",
"# Only include apartments and exclude Shared rooms for simplicity data = (",
"Returns: the list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\")",
"Drop remaining unnecessary columns in case of differences in airbnb datasets col_list =",
"a house. Function gets a house and venues within 1 km radius of",
"= f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying data management",
"learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree can be included. Args: |",
"contaning columns with categorical data | column_list (list): list of columns to get",
"dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns out of defined columns. Created",
"] for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\",",
"and predicting prices for a generated data. Parameter search is done using RandomizedSearchCV",
"efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree",
"dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\": for l in",
"dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is",
"with dividing venue's check-in count with the distance. With that division, score is",
"venues' latitude, longitude and check_in_counts Returns: house_data with additional column called location_score (pd.Dataframe)",
"\"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read = f.read() return",
"the distance. With that division, score is adjusted to popularity and distance. In",
"list of variables to apply | dataset (pd.Dataframe): dataset to implement the rule",
"house_lng) / 2) ** 2 ) return 2 * R * np.arcsin(np.sqrt(dist)) def",
"for calculating location-based score of a house. Function gets a house and venues",
"km radius of that house, calculates each venue's influential score on that house",
"dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def distance_calc(house,",
"with additional column called location_score (pd.Dataframe) \"\"\" # coordinates should be tuples for",
"= location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns",
"house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns out of defined",
"\"\"\"Function for data management. It loads the airbnb dataset and rearranges both airbnb",
"subsample and max_depth, min_child_weight, gamma and colsample_bytree can be included. Args: | data",
"== \"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif",
"src/specs/var_len.txt. Args: | date (str): a part of airbnb dataset's name also indicating",
"red_venue_list = np.array( list( filter( lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01",
"dataset (pd.Dataframe): dataset to implement the rule | rule (str): can take values",
"\"convert\", \"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data =",
"list of parameters to be included in parameter search Returns: the predicted prices",
"clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list =",
"parameters to be included in parameter search Returns: the predicted prices for houses",
"i in range(3, 12)], \"gamma\": [i / 10.0 for i in range(3, 8)],",
"param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1),",
"house_data with additional column called location_score (pd.Dataframe) \"\"\" # coordinates should be tuples",
"for prediction purposes | grid_search (bool): indicates whether model is trained with parameter",
"@jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the distance between a house and",
"dummy variable columns out of defined columns. Created dummy columns have the name",
"list including latitude and longitude of a house | venue (list): list including",
"column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) #",
"column called location_score (pd.Dataframe) \"\"\" # coordinates should be tuples for geopy.distance function",
"into a list. Args: keyword (str): the name of txt file Returns: the",
"score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of a house. Function gets a",
"of interest contaning columns with categorical data | column_list (list): list of columns",
"# Calculate the location score of each house data = score_func(house_data=data, venue_data=venue_data) #",
"np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of a house. Function",
"airbnb dataset and rearranges both airbnb and generated dataset for prediction. A certain",
"np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def",
"columns with categorical data | column_list (list): list of columns to get dummy",
"is adjusted to popularity and distance. In the end, that house's score is",
"numba import jit from numba import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths",
"more efficientcompared to GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and",
"can take values 'exclude', 'convert' or 'lengthen' Returns: the altered dataset (pd.Dataframe) \"\"\"",
"consideration. Args: | house (list): list including latitude and longitude of a house",
"score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\",",
"including house features especially latitude, longitude | venue_data (pd.Dataframe): dataset with venues' latitude,",
"= {key: params[key] for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5,",
"list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for",
"amount of house features are excluded, the list can be found in src/specs/var_exclude.txt.",
"for best parameters in model params = { \"learning_rate\": [i / 20 for",
"venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list = np.empty([len(house_data), 1]) def",
"generated dataset for prediction. A certain amount of house features are excluded, the",
"rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and exclude Shared",
"of defined columns. Created dummy columns have the name of source column as",
"rule == \"lengthen\": for l in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset",
"\"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list =",
"xgb from numba import jit from numba import prange from sklearn.model_selection import RandomizedSearchCV",
"from the dataset. Args: | data (pd.Dataframe): dataset of interest contaning columns with",
"or \"t\". Length generator(lengthen) rule gets the string lenght, adds \"_len\" to variable",
"Only includes selected parameters params = {key: params[key] for key in param_list} xgb_reg",
"the end, that house's score is the mean of relevant venues' influential scores.",
"score of a house. Function gets a house and venues within 1 km",
"simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"),",
"rule_func(var_list, dataset, rule): \"\"\"Function for applying data management rule on dataset with given",
"names. Defined rules are exclusion, conversion and length generation. Exclusion(exclude) rule excludes variable",
"/ 10.0 for i in range(3, 8)], \"subsample\": [i / 10.0 for i",
"d: data = pd.read_csv(d, low_memory=False) # Data clearing process rule_list = [\"exclude\", \"convert\",",
"1}) elif rule == \"lengthen\": for l in var_list: dataset[l + \"_len\"] =",
"in model params = { \"learning_rate\": [i / 20 for i in range(1,",
"similarly listed in src/specs/var_len.txt. Args: | date (str): a part of airbnb dataset's",
"are exclusion, conversion and length generation. Exclusion(exclude) rule excludes variable from the dataset.",
"2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2)",
"if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\": for",
"Returns: the approximate distance (float) \"\"\" # approximate radius of earth in km",
"data (pd.Dataframe): the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated data",
"+ date + \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False) # Data",
"to be included in parameter search Returns: the predicted prices for houses in",
"variables to apply | dataset (pd.Dataframe): dataset to implement the rule | rule",
"a model and predicting prices for a generated data. Parameter search is done",
"be found in src/specs/var_exclude.txt. In addition, for some features only the length is",
"Preliminary elimination based on coordinates red_venue_list = np.array( list( filter( lambda x: (",
"approximate distance (float) \"\"\" # approximate radius of earth in km R =",
"the location score of each house data = score_func(house_data=data, venue_data=venue_data) # Preparing data",
"predicted prices for houses in g_data (np.array) \"\"\" # Base Model xgb_reg =",
"\"\"\" # Base Model xgb_reg = xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best",
"xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data with",
"low_memory=False) # Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in",
"import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting the variable names from",
"var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include",
"location-based score of a house. Function gets a house and venues within 1",
"included in parameter search Returns: the predicted prices for houses in g_data (np.array)",
"cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: # venues closer",
"data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function",
"\"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule",
"sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for",
"| venue_data (pd.Dataframe): the dataset including venues' information | g_data (pd.Dataframe): randomly generated",
"use default values(False) | param_list (list): the list of parameters to be included",
"grid_search: # Search for best parameters in model params = { \"learning_rate\": [i",
"function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude))",
"venue_data (pd.Dataframe): the dataset including venues' information | g_data (pd.Dataframe): randomly generated house",
"in parameter search Returns: the predicted prices for houses in g_data (np.array) \"\"\"",
"(pd.Dataframe): the dataset including house features and prices | g_data (pd.Dataframe): randomly generated",
"variable should have values either \"f\" or \"t\". Length generator(lengthen) rule gets the",
"== \"lengthen\": for l in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset =",
"found in src/specs/var_exclude.txt. In addition, for some features only the length is considered,",
"each venue's influential score on that house with dividing venue's check-in count with",
"parameters params = {key: params[key] for key in param_list} xgb_reg = RandomizedSearchCV( estimator=xgb_reg,",
"ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1:",
"\"rb\") as g: generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management(",
"\"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\": for c in var_list:",
"dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"]",
"Function gets a house and venues within 1 km radius of that house,",
"the list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as",
"* np.sin((venue_lng - house_lng) / 2) ** 2 ) return 2 * R",
"With that division, score is adjusted to popularity and distance. In the end,",
"influential scores. Args: | house_data (pd.Dataframe): airbnb dataset including house features especially latitude,",
"rule == \"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1})",
"data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ]",
"nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list:",
"calculating location-based score of a house. Function gets a house and venues within",
"return data def data_management(date, venue_data, g_data): \"\"\"Function for data management. It loads the",
"data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() )",
"red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list",
"dataset's column names. Defined rules are exclusion, conversion and length generation. Exclusion(exclude) rule",
"| rule (str): can take values 'exclude', 'convert' or 'lengthen' Returns: the altered",
"apartments and exclude Shared rooms for simplicity data = ( data.loc[ (data[\"room_type\"] !=",
"np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = (",
"(pd.Dataframe) \"\"\" # coordinates should be tuples for geopy.distance function venue_data_list = np.array(",
"prices for a generated data. Parameter search is done using RandomizedSearchCV since it",
"a house and a venue while taking world's shape into consideration. Args: |",
"within 1 km radius of that house, calculates each venue's influential score on",
"the name of txt file Returns: the list of variable names \"\"\" with",
"latitude, longitude and check_in_counts Returns: house_data with additional column called location_score (pd.Dataframe) \"\"\"",
"venue_data=venue_data) # Preparing data for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"]",
"in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def",
"= pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"), \"w\") as p: predicted_df.to_csv(p,",
"np.sin((venue_lat - house_lat) / 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng",
"dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the distance between a house",
"columns (pd.Dataframe) \"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data",
"generation. Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert) rule converts \"f\" and",
"including house features and prices | g_data (pd.Dataframe): randomly generated house features for",
"converting into a list. Args: keyword (str): the name of txt file Returns:",
"= np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\" for",
"list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and",
"generated_data = data_management( date=date, venue_data=reduced_venue, g_data=generated_data ) prediction = prediction_func( data=data, g_data=generated_data, grid_search=True,",
"(list): list including latitude and longitude of a venue Returns: the approximate distance",
"<reponame>burakbalaban/airbnb_project import sys import numpy as np import pandas as pd import xgboost",
"(pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts Returns: house_data with additional column",
"== \"exclude\": dataset = dataset.drop(var_list, axis=1) elif rule == \"convert\": for c in",
"including latitude and longitude of a venue Returns: the approximate distance (float) \"\"\"",
"longitude venue_data_list, ) ) ) score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist",
"6373.0 house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1])",
"A certain amount of house features are excluded, the list can be found",
"Calculate the location score of each house data = score_func(house_data=data, venue_data=venue_data) # Preparing",
"defined columns. Created dummy columns have the name of source column as prefix",
"of relevant venues' influential scores. Args: | house_data (pd.Dataframe): airbnb dataset including house",
"axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in",
"house_lat = np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist",
"on dataset with given variable names. Variable names should match with dataset's column",
") location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application.",
"10.0 for i in range(3, 8)], \"subsample\": [i / 10.0 for i in",
"additional column called location_score (pd.Dataframe) \"\"\" # coordinates should be tuples for geopy.distance",
"xgb.XGBRegressor(n_treads=-1) if grid_search: # Search for best parameters in model params = {",
"a house | venue (list): list including latitude and longitude of a venue",
"data (pd.Dataframe): the dataset including house features and prices | g_data (pd.Dataframe): randomly",
"altered dataset (pd.Dataframe) \"\"\" if rule == \"exclude\": dataset = dataset.drop(var_list, axis=1) elif",
"[\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] =",
"with dataset's column names. Defined rules are exclusion, conversion and length generation. Exclusion(exclude)",
"data management rule on dataset with given variable names. Variable names should match",
"length generation. Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert) rule converts \"f\"",
"(pd.Dataframe): the dataset including venues' information | g_data (pd.Dataframe): randomly generated house features",
"dist = ( np.sin((venue_lat - house_lat) / 2) ** 2 + np.cos(house_lat) *",
"np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist",
"open(ppj(\"OUT_DATA\", \"generated_house_data.csv\"), \"rb\") as g: generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data",
"(list): list of variables to apply | dataset (pd.Dataframe): dataset to implement the",
"with open(ppj(\"IN_SPECS\", keyword + \".txt\"), \"r\") as f: var_read = f.read() return list(var_read.split(\"\\n\"))",
"cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data",
"airbnb dataset's name also indicating scraping date | venue_data (pd.Dataframe): the dataset including",
"import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting",
"values either \"f\" or \"t\". Length generator(lengthen) rule gets the string lenght, adds",
"= distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: # venues closer than",
"for rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data,",
"using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list, learning_rate,",
"location_score_list = np.empty([len(house_data), 1]) def numba_func(venue_data_list, house_data_coordinate): \"\"\"Inside function for numba application. \"\"\"",
"= [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item in nan_fill_list: data[item]",
"import numpy as np import pandas as pd import xgboost as xgb from",
"gamma and colsample_bytree can be included. Args: | data (pd.Dataframe): the dataset including",
"with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d,",
"[i for i in range(3, 12)], \"gamma\": [i / 10.0 for i in",
"names. Variable names should match with dataset's column names. Defined rules are exclusion,",
"elimination based on coordinates red_venue_list = np.array( list( filter( lambda x: ( x[0]",
"np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list =",
"rule in rule_list: var_list = list_generator(keyword=\"var_\" + rule) data = rule_func(var_list=var_list, dataset=data, rule=rule)",
"data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\", ] for item",
"for i in range(3, 8)], } # Only includes selected parameters params =",
"dataset. Conversion(convert) rule converts \"f\" and \"t\" values into 0 and 1 respectively.",
"def dummy_func(data, column_list): \"\"\"Function for creating dummy variable columns out of defined columns.",
"Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list",
"= np.deg2rad(house[0]) house_lng = np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist =",
"Returns: the altered dataset with dummy variable columns (pd.Dataframe) \"\"\" for column in",
"model and predicting prices for a generated data. Parameter search is done using",
"done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In param_list,",
"defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the distance between",
"12)], \"gamma\": [i / 10.0 for i in range(3, 8)], \"subsample\": [i /",
"col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\", \"host_has_profile_pic\", \"host_identity_verified\", \"location_score\",",
"(list): list including latitude and longitude of a house | venue (list): list",
"column as prefix and \"_\". Function drops the source column from the dataset.",
"be included in parameter search Returns: the predicted prices for houses in g_data",
"in range(1, 11)], \"min_child_weight\": [i for i in range(3, 12)], \"gamma\": [i /",
"( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index()",
"distance (float) \"\"\" # approximate radius of earth in km R = 6373.0",
"= np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) / 2)",
"a generated data. Parameter search is done using RandomizedSearchCV since it is computationally",
"pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\", f\"{date}_prediction.csv\"), \"w\") as p: predicted_df.to_csv(p, index=False)",
"= numba_func(venue_data_list,house_data_coordinate) house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for creating",
"rule (str): can take values 'exclude', 'convert' or 'lengthen' Returns: the altered dataset",
"\"f\" and \"t\" values into 0 and 1 respectively. Thus variable should have",
"return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for calculating the distance between a",
"Created dummy columns have the name of source column as prefix and \"_\".",
"grid_search, param_list): \"\"\"Function for using dataset to train a model and predicting prices",
"and length generation. Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert) rule converts",
"+ \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not",
"house_data[\"location_score\"] = location_score_list return house_data def dummy_func(data, column_list): \"\"\"Function for creating dummy variable",
"for creating dummy variable columns out of defined columns. Created dummy columns have",
"data def data_management(date, venue_data, g_data): \"\"\"Function for data management. It loads the airbnb",
"names from txt file and converting into a list. Args: keyword (str): the",
"variable from dataset. Args: | var_list (list): list of variables to apply |",
"into 0 and 1 respectively. Thus variable should have values either \"f\" or",
"the cleared, ready-for-modelling, dataset | g_data (pd.Dataframe): the altered generated data \"\"\" with",
"a venue while taking world's shape into consideration. Args: | house (list): list",
"is done using RandomizedSearchCV since it is computationally more efficientcompared to GridSearchCV. In",
"g_data): \"\"\"Function for data management. It loads the airbnb dataset and rearranges both",
"Function drops the source column from the dataset. Args: | data (pd.Dataframe): dataset",
"the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\")",
"& (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) # Calculate the location score",
"data = data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return data def data_management(date,",
"function for numba application. \"\"\" for house in prange(len(house_data_coordinate)): # Preliminary elimination based",
"of each house data = score_func(house_data=data, venue_data=venue_data) # Preparing data for modelling data",
"venue (list): list including latitude and longitude of a venue Returns: the approximate",
"= dummy_func( data=g_data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns in",
"from numba import jit from numba import prange from sklearn.model_selection import RandomizedSearchCV from",
"considered, similarly listed in src/specs/var_len.txt. Args: | date (str): a part of airbnb",
"\"gamma\": [i / 10.0 for i in range(3, 8)], \"subsample\": [i / 10.0",
"import jit from numba import prange from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import",
"with given variable names. Variable names should match with dataset's column names. Defined",
"f: var_read = f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying",
"rearranges both airbnb and generated dataset for prediction. A certain amount of house",
"= np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if",
"closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list",
"range(6, 11)], \"max_depth\": [i for i in range(3, 8)], } # Only includes",
"converts \"f\" and \"t\" values into 0 and 1 respectively. Thus variable should",
"var_list: dataset[c] = dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\": for l",
"bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting the variable names",
"list. Args: keyword (str): the name of txt file Returns: the list of",
"rule gets the string lenght, adds \"_len\" to variable name and exclude variable",
"( x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1] - house_data_coordinate[0][1]",
"prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: # venues",
"(pd.Dataframe): randomly generated house features for prediction Returns: | data (pd.Dataframe): the cleared,",
"as d: data = pd.read_csv(d, low_memory=False) # Data clearing process rule_list = [\"exclude\",",
"np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) / 2) ** 2 + np.cos(house_lat)",
"axis=1) elif rule == \"convert\": for c in var_list: dataset[c] = dataset[c].replace({\"f\": 0,",
"RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function for getting the",
"list( filter( lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude",
") ) ) score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc(",
"dataset with dummy variable columns (pd.Dataframe) \"\"\" for column in column_list: temp_data =",
"2 * R * np.arcsin(np.sqrt(dist)) def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score",
"0 and 1 respectively. Thus variable should have values either \"f\" or \"t\".",
"def score_func(house_data, venue_data): \"\"\"Function for calculating location-based score of a house. Function gets",
"airbnb and generated dataset for prediction. A certain amount of house features are",
"of airbnb dataset's name also indicating scraping date | venue_data (pd.Dataframe): the dataset",
"rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and exclude Shared rooms for simplicity",
"| param_list (list): the list of parameters to be included in parameter search",
"Only include apartments and exclude Shared rooms for simplicity data = ( data.loc[",
"11)], \"colsample_bytree\": [i / 10.0 for i in range(6, 11)], \"max_depth\": [i for",
"data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out",
"rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list: var_list = list_generator(keyword=\"var_\" +",
"or use default values(False) | param_list (list): the list of parameters to be",
"pd.get_dummies(data[column]).add_prefix(str(column + \"_\")) data = data.drop(column, axis=1) data = pd.concat([data, temp_data], axis=1) return",
"param_list (list): the list of parameters to be included in parameter search Returns:",
"venue_data): \"\"\"Function for calculating location-based score of a house. Function gets a house",
"+ rule) data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and exclude",
"np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat) / 2) **",
"Parameter search is done using RandomizedSearchCV since it is computationally more efficientcompared to",
"[i / 10.0 for i in range(6, 11)], \"max_depth\": [i for i in",
"the altered dataset with dummy variable columns (pd.Dataframe) \"\"\" for column in column_list:",
"with the distance. With that division, score is adjusted to popularity and distance.",
"variable names. Variable names should match with dataset's column names. Defined rules are",
"dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\": for l in var_list: dataset[l",
"RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data)",
"\"_\". Function drops the source column from the dataset. Args: | data (pd.Dataframe):",
"x: ( x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1] -",
"col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\", \"host_listings_count\",",
"dataset including house features and prices | g_data (pd.Dataframe): randomly generated house features",
"with categorical data | column_list (list): list of columns to get dummy variables",
"In the end, that house's score is the mean of relevant venues' influential",
"import xgboost as xgb from numba import jit from numba import prange from",
"\"Shared room\") & (data[\"property_type\"] == \"Apartment\"), ] .copy() .reset_index() ) # Calculate the",
"rooms for simplicity data = ( data.loc[ (data[\"room_type\"] != \"Shared room\") & (data[\"property_type\"]",
"Exclusion(exclude) rule excludes variable from the dataset. Conversion(convert) rule converts \"f\" and \"t\"",
"for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func(",
"1 km radius of that house, calculates each venue's influential score on that",
"g_data (pd.Dataframe): randomly generated house features for prediction purposes | grid_search (bool): indicates",
"either \"f\" or \"t\". Length generator(lengthen) rule gets the string lenght, adds \"_len\"",
"list_generator(keyword): \"\"\"Function for getting the variable names from txt file and converting into",
"as ppj def list_generator(keyword): \"\"\"Function for getting the variable names from txt file",
"+ np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) ** 2 )",
"longitude | venue_data (pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts Returns: house_data",
"\"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\",",
"cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\":",
"= data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list: data[item]",
"for calculating the distance between a house and a venue while taking world's",
"cal_dist < 1: # venues closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist)",
"temp_data], axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function for data management. It",
"variable columns (pd.Dataframe) \"\"\" for column in column_list: temp_data = pd.get_dummies(data[column]).add_prefix(str(column + \"_\"))",
"prediction. A certain amount of house features are excluded, the list can be",
"| g_data (pd.Dataframe): randomly generated house features for prediction Returns: | data (pd.Dataframe):",
"axis=1) data = pd.concat([data, temp_data], axis=1) return data def data_management(date, venue_data, g_data): \"\"\"Function",
"\"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d: data = pd.read_csv(d, low_memory=False) #",
"including venues' information | g_data (pd.Dataframe): randomly generated house features for prediction Returns:",
"# Data clearing process rule_list = [\"exclude\", \"convert\", \"lengthen\"] for rule in rule_list:",
"data = rule_func(var_list=var_list, dataset=data, rule=rule) # Only include apartments and exclude Shared rooms",
"house_lat) / 2) ** 2 + np.cos(house_lat) * np.cos(venue_lat) * np.sin((venue_lng - house_lng)",
"< 0.01 ) # latitude & (x[1] - house_data_coordinate[0][1] < 0.01), # longitude",
"are excluded, the list can be found in src/specs/var_exclude.txt. In addition, for some",
"house_data_coordinate[house], red_venue_list[ven][0:2] ) if cal_dist < 1: # venues closer than 1 km",
"dataset for prediction. A certain amount of house features are excluded, the list",
"| g_data (pd.Dataframe): randomly generated house features for prediction purposes | grid_search (bool):",
"randomly generated house features for prediction Returns: | data (pd.Dataframe): the cleared, ready-for-modelling,",
"\"lengthen\": for l in var_list: dataset[l + \"_len\"] = dataset[l].str.len() dataset = dataset.drop(l,",
"venue_data (pd.Dataframe): dataset with venues' latitude, longitude and check_in_counts Returns: house_data with additional",
"Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue = pd.read_csv(c) with open(ppj(\"OUT_DATA\",",
"rule converts \"f\" and \"t\" values into 0 and 1 respectively. Thus variable",
"dataset with given variable names. Variable names should match with dataset's column names.",
"in prange(len(house_data_coordinate)): # Preliminary elimination based on coordinates red_venue_list = np.array( list( filter(",
"\"location_score\", ] for item in nan_fill_list: data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\",",
"params = { \"learning_rate\": [i / 20 for i in range(1, 11)], \"min_child_weight\":",
"datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list = [ \"host_is_superhost\",",
"lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01 ) # latitude & (x[1]",
"for applying data management rule on dataset with given variable names. Variable names",
"xgb_reg = RandomizedSearchCV( estimator=xgb_reg, param_distributions=params, n_iter=5, cv=3, random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price)",
"and converting into a list. Args: keyword (str): the name of txt file",
"to train a model and predicting prices for a generated data. Parameter search",
"\"\").str.extract(r\"(\\d+)\").astype(int) return data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset",
"\"extra_people\"] for item in currency_list: data[item] = data[item].fillna(\"$0.00\") data[item] = data[item].str.replace(\",\", \"\").str.extract(r\"(\\d+)\").astype(int) return",
"i in range(6, 11)], \"max_depth\": [i for i in range(3, 8)], } #",
"as g: generated_data = pd.read_csv(g) date = sys.argv[1] data, generated_data = data_management( date=date,",
"match with dataset's column names. Defined rules are exclusion, conversion and length generation.",
"* np.cos(venue_lat) * np.sin((venue_lng - house_lng) / 2) ** 2 ) return 2",
"have values either \"f\" or \"t\". Length generator(lengthen) rule gets the string lenght,",
"raise ValueError(\"Rule is not defined\") return dataset @jit(nopython=True) def distance_calc(house, venue): \"\"\"Function for",
") if cal_dist < 1: # venues closer than 1 km np.append(score_list, red_venue_list[ven][2]",
"\"bed_type\", \"cancellation_policy\"] ) # Drop remaining unnecessary columns in case of differences in",
"from sklearn.model_selection import RandomizedSearchCV from bld.project_paths import project_paths_join as ppj def list_generator(keyword): \"\"\"Function",
"random_state=23, iid=False, ) xgb_reg.fit(data.drop(\"price\", axis=1), data.price) return xgb_reg.predict(g_data) if __name__ == \"__main__\": #",
"1: # venues closer than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list))",
"xgb_reg.predict(g_data) if __name__ == \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as",
"= dataset[c].replace({\"f\": 0, \"t\": 1}) elif rule == \"lengthen\": for l in var_list:",
"data_management(date, venue_data, g_data): \"\"\"Function for data management. It loads the airbnb dataset and",
"list of columns to get dummy variables Returns: the altered dataset with dummy",
"= np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude, house_data.longitude)) ) location_score_list",
"data[item] = data[item].fillna(0) currency_list = [\"price\", \"security_deposit\", \"cleaning_fee\", \"extra_people\"] for item in currency_list:",
"(str): the name of txt file Returns: the list of variable names \"\"\"",
"while taking world's shape into consideration. Args: | house (list): list including latitude",
"return data, g_data def prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset to",
"than 1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list =",
"Args: | date (str): a part of airbnb dataset's name also indicating scraping",
"param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date]) # Out data with open(ppj(\"OUT_PREDICTION\",",
"geopy.distance function venue_data_list = np.array( list(zip(venue_data.latitude, venue_data.longitude, venue_data.check_in_counts)) ) house_data_coordinate = np.array( list(zip(house_data.latitude,",
"venue_data, g_data): \"\"\"Function for data management. It loads the airbnb dataset and rearranges",
"\"_len\" to variable name and exclude variable from dataset. Args: | var_list (list):",
"of that house, calculates each venue's influential score on that house with dividing",
"and a venue while taking world's shape into consideration. Args: | house (list):",
"in airbnb datasets col_list = list(g_data.columns) col_list.append(\"price\") data = data.filter(col_list, axis=1) nan_fill_list =",
"] .copy() .reset_index() ) # Calculate the location score of each house data",
"dataset[l].str.len() dataset = dataset.drop(l, axis=1) else: raise ValueError(\"Rule is not defined\") return dataset",
"1 km np.append(score_list, red_venue_list[ven][2] / cal_dist) np.append(location_score_list, np.mean(score_list)) return location_score_list location_score_list = numba_func(venue_data_list,house_data_coordinate)",
"and rearranges both airbnb and generated dataset for prediction. A certain amount of",
".reset_index() ) # Calculate the location score of each house data = score_func(house_data=data,",
"file Returns: the list of variable names \"\"\" with open(ppj(\"IN_SPECS\", keyword + \".txt\"),",
"data for modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data =",
"GridSearchCV. In param_list, learning_rate, subsample and max_depth, min_child_weight, gamma and colsample_bytree can be",
"= { \"learning_rate\": [i / 20 for i in range(1, 11)], \"min_child_weight\": [i",
"np.deg2rad(house[1]) venue_lat = np.deg2rad(venue[0]) venue_lng = np.deg2rad(venue[1]) dist = ( np.sin((venue_lat - house_lat)",
"score_list = np.array(0) for ven in prange(len(red_venue_list)): cal_dist = distance_calc( house_data_coordinate[house], red_venue_list[ven][0:2] )",
"= np.array( list( filter( lambda x: ( x[0] - house_data_coordinate[0][0] < 0.01 )",
"# latitude & (x[1] - house_data_coordinate[0][1] < 0.01), # longitude venue_data_list, ) )",
"f.read() return list(var_read.split(\"\\n\")) def rule_func(var_list, dataset, rule): \"\"\"Function for applying data management rule",
"and \"_\". Function drops the source column from the dataset. Args: | data",
"respectively. Thus variable should have values either \"f\" or \"t\". Length generator(lengthen) rule",
"interest contaning columns with categorical data | column_list (list): list of columns to",
"| date (str): a part of airbnb dataset's name also indicating scraping date",
"modelling data = dummy_func( data=data, column_list=[\"room_type\", \"bed_type\", \"cancellation_policy\"] ) g_data = dummy_func( data=g_data,",
"prediction_func(data, g_data, grid_search, param_list): \"\"\"Function for using dataset to train a model and",
"[i for i in range(3, 8)], } # Only includes selected parameters params",
"== \"__main__\": # Load data with open(ppj(\"OUT_DATA\", \"reduced_check_in_dataset.csv\"), \"rb\") as c: reduced_venue =",
"| g_data (pd.Dataframe): the altered generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date",
"for i in range(6, 11)], \"max_depth\": [i for i in range(3, 8)], }",
"generated data \"\"\" with open(ppj(\"IN_DATA\", \"Airbnb_data/\" + date + \"_listings.csv\"), \"rb\") as d:",
"creating dummy variable columns out of defined columns. Created dummy columns have the",
"= prediction_func( data=data, g_data=generated_data, grid_search=True, param_list=[\"learning_rate\", \"subsample\", \"max_depth\"], ) predicted_df = pd.DataFrame(prediction, columns=[date])"
] |
[
"# http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'),",
"path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/',",
"[ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3',",
"path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"),",
"这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图",
"# 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), #",
"from django.urls import path, re_path from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url",
"# 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2',",
"ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), #",
"views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m) # 调函数的时候传参数,采用正则的组,正则匹配加括号,然后传进去参数,按照顺序传 #",
"path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m)",
"= [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram),",
"path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/',",
"那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配",
"re_path from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ #",
". import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配",
"views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1),",
"path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m) # 调函数的时候传参数,采用正则的组,正则匹配加括号,然后传进去参数,按照顺序传 # 这里的地址最重要,代表了访问的url地址后面",
"urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/',",
"import path, re_path from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns =",
"views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m) #",
"views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/',",
"views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配",
"path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格",
"匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1),",
"path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m) # 调函数的时候传参数,采用正则的组,正则匹配加括号,然后传进去参数,按照顺序传",
"import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 #",
"正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2",
"views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh,",
"# 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 #",
"# 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/',",
"path, re_path from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [",
"django.urls import path, re_path from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns",
"# ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList),",
"如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2),",
"from . import views # 这是应用Book中的url具体配置,请求到这里才能调用该应用的视图,上一级首先是调用BookManager的url,如果没有匹配admin # 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/",
"# 那么进入应用的匹配Book.urls,之后才会进入这里应用的url urlpatterns = [ # http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 #",
"正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1', views.json1), # ex:/assetinfo/json2 path('json2', views.json2), path('ajax_add/', views.ajax_add),",
"views.json2), path('ajax_add/', views.ajax_add), path('ajax_demo1/', views.ajax_demo1), path('data_fresh/', views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$',",
"http://127.0.0.1:8000/admin/ 匹配 # 正则匹配,对请求地址进行正则匹配,如果路径中包含admin,就把后台站点中的url信息包含到这个项目中,指明下一集路径如何匹配 # 如果匹配成功,那么直接调用指定的视图 # 正则匹配,对请求地址进行正则匹配,如果路径中不包含admin,就把Book中的url信息包含到这个项目中,指明下一集路径如何匹配 path('stockplot/', views.showlinediagram), path('index3', views.index3,name='index3'), path('json1',",
"views.data_fresh, name=\"data_fresh\"), path('stocklist/', views.stockList), # 这里的^表示开始,$表示结束,因为是正则表达式,所以必须严格 re_path(r'^([1-9]\\d*)/$', views.dashBoard_m) # 调函数的时候传参数,采用正则的组,正则匹配加括号,然后传进去参数,按照顺序传 # 这里的地址最重要,代表了访问的url地址后面 ]"
] |
[
"import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError,",
"wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length from",
"SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la salle'), validators=[DataRequired()]) submit = SubmitField(_l('Enregistrer'))",
"from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as _l",
"StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import",
"flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import",
"from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length",
"Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class",
"FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired,",
"import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher')",
"from app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit",
"import _, lazy_gettext as _l from app.models import Room class SearchForm(FlaskForm): name =",
"app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit =",
"Length from flask_babel import _, lazy_gettext as _l from app.models import Room class",
"StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de",
"= SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la salle'), validators=[DataRequired()]) submit =",
"import request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField",
"lazy_gettext as _l from app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de",
"ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as _l from app.models import",
"= StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom",
"import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel",
"wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as _l from",
"_l from app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle'))",
"SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name",
"request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from",
"<filename>app/room/forms.py from flask import request from flask_wtf import FlaskForm from wtforms import StringField,",
"TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext",
"class SearchForm(FlaskForm): name = StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm):",
"de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la",
"_, lazy_gettext as _l from app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom",
"from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField from wtforms.validators",
"import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as _l from app.models",
"la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la salle'),",
"SelectField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as",
"as _l from app.models import Room class SearchForm(FlaskForm): name = StringField(_l('Nom de la",
"SubmitField, TextAreaField, SelectField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _,",
"from flask_babel import _, lazy_gettext as _l from app.models import Room class SearchForm(FlaskForm):",
"name = StringField(_l('Nom de la salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name =",
"salle')) submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la salle'), validators=[DataRequired()])",
"submit = SubmitField('Rechercher') class RoomForm(FlaskForm): name = StringField(_l('Nom de la salle'), validators=[DataRequired()]) submit",
"flask import request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField,",
"from flask import request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField,",
"flask_babel import _, lazy_gettext as _l from app.models import Room class SearchForm(FlaskForm): name",
"DataRequired, Length from flask_babel import _, lazy_gettext as _l from app.models import Room"
] |