id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
/oommftools-2.0.2.tar.gz/oommftools-2.0.2/oommftools/odtchomp.py
import os from wx import adv import wx import numpy as np from fnameutil import filterOnExtensions import _about as about ######### # About # ######### VERSION = about.__version__ NAME = "ODTChomp" LICENSE = about.__license__ COPYRIGHT = about.__copyright__ WEBSITE = about.__uri__ DESCRIPTION = """ODTChomp is an OOMMF postprocessing tool for extracting columns from and unifying delimitation of ODT table files. \nODTChomp is part of OOMMFTools.""" ######## # DECS # ######## #Readability magic below ALWAYS_CLEAR = ["Oxs_"] PROTECTED_NAMES = ["Exchange"] ####### # GUI # ####### class MainFrame(wx.Frame): """Main frame for odtchomp """ def __init__(self, manager=None): wx.Frame.__init__(self, None, -1, "ODT Chomper 0.9", size=(900, 500)) self.watching = [] self.delim = " " #Let's try to get a proto-digest from a file to memorize the ODT layout if os.path.exists("." + os.path.sep + "odt.layout"): f = open("." + os.path.sep + "odt.layout") lines = f.readlines() f.close() lines = [line.strip() for line in lines] self.digest = Interpreter({}, keys=lines) else: #No file at all! self.digest = None self.exportPath = os.getcwd() self.dt = ODTDropTarget(self) self.SetDropTarget(self.dt) self.manager = manager self.Bind(wx.EVT_CLOSE, self.onClose) #A very simple menubar menubar = wx.MenuBar() about = wx.Menu() about.Append(999, 'About', 'Program information and license') menubar.Append(about, "About") self.SetMenuBar(menubar) self.Bind(wx.EVT_MENU, self.showAbout, id=999) panel = wx.Panel(self, -1) self.panel = panel #OK, I do need a reference to this to send size events later #Point Zero: Major Box Sizer sizer = wx.BoxSizer(wx.VERTICAL) #Deal with import button self.importButton = wx.Button(panel, 1, "Import") sizer.Add(self.importButton, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10) self.Bind(wx.EVT_BUTTON, self.importFile, id=1) #Deal with active label self.fileLabel = wx.StaticText(panel, -1, "No File Loaded", style=wx.ALIGN_CENTER) sizer.Add(self.fileLabel, 0, wx.ALIGN_CENTER | wx.BOTTOM, 10) sizer.Add(wx.StaticLine(panel, -1), 0, wx.EXPAND | wx.BOTTOM, 15) #Listboxes! Prepare horizontal sizer tsizer = wx.BoxSizer() #Do left listbox llbsizer = wx.BoxSizer(wx.VERTICAL) lefttitle = wx.StaticText(panel, -1, "Available Data Fields", style=wx.ALIGN_CENTER) self.leftbox = wx.ListBox(panel, 10, choices=[], style=wx.LB_SINGLE) llbsizer.Add(lefttitle, 0, wx.ALIGN_CENTER) llbsizer.Add(self.leftbox, 1, wx.ALIGN_CENTER | wx.EXPAND | wx.TOP, 10) tsizer.Add(llbsizer, 1, wx.ALIGN_CENTER | wx.EXPAND | wx.LEFT | wx.RIGHT, 10) self.leftbox.Bind(wx.EVT_LEFT_DCLICK, self.takeData) midbsizer = wx.BoxSizer(wx.VERTICAL) #Add/Remove Buttons a = wx.Button(panel, 20, "-->") self.Bind(wx.EVT_BUTTON, self.takeData, id=20) b = wx.Button(panel, 21, "<--") self.Bind(wx.EVT_BUTTON, self.puntData, id=21) c = wx.Button(panel, 22, "+All") self.Bind(wx.EVT_BUTTON, self.takeAll, id=22) d = wx.Button(panel, 23, "-All") self.Bind(wx.EVT_BUTTON, self.puntAll, id=23) midbsizer.Add(a, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) midbsizer.Add(b, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) midbsizer.Add(c, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) midbsizer.Add(d, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM, 10) #Radio Controls label = wx.StaticText(panel, -1, "File Delimiter") self.spaceDelim = wx.RadioButton(panel, 30, "Space", style=wx.RB_GROUP) self.tabDelim = wx.RadioButton(panel, 31, "Tab") self.commaDelim = wx.RadioButton(panel, 32, "Comma") self.Bind(wx.EVT_RADIOBUTTON, self.setDelim, id=30) self.Bind(wx.EVT_RADIOBUTTON, self.setDelim, id=31) self.Bind(wx.EVT_RADIOBUTTON, self.setDelim, id=32) self.spaceDelim.SetValue(True) midbsizer.Add((-1, 10)) midbsizer.Add(label, 0, wx.ALIGN_CENTER | wx.BOTTOM | wx.TOP, 10) midbsizer.Add(self.spaceDelim, 0, wx.LEFT | wx.BOTTOM, 2) midbsizer.Add(self.tabDelim, 0, wx.LEFT | wx.BOTTOM, 2) midbsizer.Add(self.commaDelim, 0, wx.LEFT | wx.BOTTOM, 2) tsizer.Add(midbsizer, 0, wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, 10) #Final Listbox rlbsizer = wx.BoxSizer(wx.VERTICAL) righttitle = wx.StaticText(panel, -1, "Exported Data Fields", style=wx.ALIGN_CENTER) self.rightbox = wx.ListBox(panel, 11, choices=[], style=wx.LB_SINGLE) rlbsizer.Add(righttitle, 0, wx.ALIGN_CENTER) rlbsizer.Add(self.rightbox, 1, wx.ALIGN_CENTER | wx.EXPAND | wx.TOP, 10) tsizer.Add(rlbsizer, 1, wx.ALIGN_CENTER | wx.EXPAND | wx.LEFT | wx.RIGHT, 10) self.rightbox.Bind(wx.EVT_LEFT_DCLICK, self.puntData) #U/D buttons udbsizer = wx.BoxSizer(wx.VERTICAL) a = wx.Button(panel, 50, "Move Up") b = wx.Button(panel, 51, "Move Down") self.Bind(wx.EVT_BUTTON, self.bumpUp, id=50) self.Bind(wx.EVT_BUTTON, self.bumpDown, id=51) udbsizer.Add(a, 0, wx.CENTER | wx.BOTTOM, 10) udbsizer.Add(b, 0, wx.CENTER | wx.BOTTOM, 10) tsizer.Add(udbsizer, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, 10) #Clean up horizontal sizers sizer.Add(tsizer, 1, wx.EXPAND | wx.BOTTOM, 20) # Export! sizer.Add(wx.StaticLine(panel, -1), 0, wx.EXPAND | wx.BOTTOM, 15) self.batchModeCheckbox = wx.CheckBox(panel, 60, "Drag-Drop Batch Mode") self.batchModeCheckbox.SetValue(False) sizer.Add(self.batchModeCheckbox, 0, wx.ALIGN_CENTER | wx.TOP, 10) self.Bind(wx.EVT_CHECKBOX, self.fixBatchMode, id=60) self.exportButton = wx.Button(panel, 70, "Export") self.exportButton._secondLevelEnable = False sizer.Add(self.exportButton, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 10) self.Bind(wx.EVT_BUTTON, self.exportFile, id=70) self.exportButton.Disable() #Late-game setup if self.digest: self.leftbox.Set(self.digest.getNames()) #Cleanup panel.SetSizer(sizer) if self.manager: self.CenterOnParent() self.Show() def onClose(self, evt): """ """ if self.manager: self.manager.droppedWindow(self) self.Destroy() def setDelim(self, evt): """ """ if self.spaceDelim.GetValue(): self.delim = " " elif self.tabDelim.GetValue(): self.delim = "\t" elif self.commaDelim.GetValue(): self.delim = "," def fixBatchMode(self, evt): """ """ if self.batchModeCheckbox.GetValue(): print "Batch mode disable." self.importButton.Disable() self.exportButton.Disable() else: print "Batch mode enable." self.importButton.Enable() if self.exportButton._secondLevelEnable: self.exportButton.Enable() def importFile(self, evt): """ """ dlg = wx.FileDialog(self, "Import ODT File", os.getcwd(), "", "OOMMF ODT Data (*.odt)|*.odt", wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK and dlg.GetPath(): #self.fileLabel.SetLabel("Open: " + os.getcwd() + os.path.sep + dlg.GetFilename()) self._importFile(dlg.GetPath()) def _importFile(self, filename): """ """ print "Import enable." self.fileLabel.SetLabel("Open: " + filename) self.digest = chomp(filename) self.leftbox.Set(self.digest.getNames()) self.panel.SendSizeEvent() self.exportPath = os.path.dirname(filename) self.exportButton._secondLevelEnable = True self.exportButton.Enable() #Cache the autolayout f = open("." + os.path.sep + "odt.layout", "w") f.write("\n".join(self.digest.getNames())) f.close() def _lightImportFile(self, filename): """ """ #returns (Interpreter, exportPathname) return (chomp(filename), os.path.dirname(filename)) def exportFile(self, evt): """ """ dlg = wx.FileDialog(self, 'Export Translated File', self.exportPath, "", "Plaintext ODT Data (*.txt)|*.txt", wx.FD_SAVE) if dlg.ShowModal() == wx.ID_OK and dlg.GetPath(): filename = dlg.GetPath() self.exportPath = os.path.dirname(dlg.GetPath()) write(filename, self.digest, self.delim, self.watching) def takeData(self, evt): """ """ if self.digest and self.leftbox.GetSelections(): sel = self.leftbox.GetSelections()[0] keys = self.digest.getNames() if not keys[sel] in self.watching: self.watching.append(keys[sel]) self.rightbox.Set(self.watching) def takeAll(self, evt): """ """ if self.digest: self.watching = self.digest.getNames() self.rightbox.Set(self.watching) def puntData(self, evt): """ """ if self.digest and self.rightbox.GetSelections(): self.watching.pop(self.rightbox.GetSelections()[0]) self.rightbox.Set(self.watching) def puntAll(self, evt): """ """ if self.digest: self.watching = [] self.rightbox.Set(self.watching) #self.leftbox.Set(self.digest.getNames()) def bumpUp(self, evt): """ """ if self.digest and self.rightbox.GetSelections() and self.rightbox.GetSelections()[0] > 0: dex = self.rightbox.GetSelections()[0] pull = self.watching.pop(dex) self.watching.insert(dex-1, pull) self.rightbox.Set(self.watching) self.rightbox.SetSelection(dex-1) def bumpDown(self, evt): """ """ if self.digest and self.rightbox.GetSelections() and self.rightbox.GetSelections()[0] < len(self.watching)-1: dex = self.rightbox.GetSelections()[0] pull = self.watching.pop(dex) self.watching.insert(dex+1, pull) self.rightbox.Set(self.watching) self.rightbox.SetSelection(dex+1) def showAbout(self, evt): """ """ info = wx.adv.AboutDialogInfo() mydesc = DESCRIPTION mylicense = LICENSE info.SetName(NAME) info.SetVersion(VERSION) info.SetDescription("".join(mydesc)) info.SetLicense("".join(mylicense)) info.SetCopyright(COPYRIGHT) info.SetWebSite(WEBSITE) wx.adv.AboutBox(info) ########### # BACKEND # ########### class ODTDropTarget(wx.FileDropTarget): """ """ def __init__(self, parent): wx.FileDropTarget.__init__(self) self.parent = parent def OnDropFiles(self, x, y, filenames): """ """ namepotential = filterOnExtensions(["odt"], filenames) if not self.parent.batchModeCheckbox.GetValue() or not self.parent.digest: #normal mode if namepotential: self.parent._importFile(namepotential[0]) return 0 else: #batch mode for fname in namepotential: interp, outDir = self.parent._lightImportFile(fname) outfname = fname.rsplit(os.path.sep, 1)[1].split(".")[0] + ".txt" print outDir, outfname write(outDir + os.path.sep + outfname, interp, self.parent.delim, self.parent.watching) return 1 def write(filename, interpreter, delim, fields): """ """ print "Write out to:", filename refdelim = delim f = open(filename, "w") #Do keys if delim == ",": delim = ", " if refdelim == " ": log("Space delim override: Deleting spaces from field names.") reffields = [] for field in fields: reffields.append(field.replace(" ", "_")) else: reffields = fields line = delim.join(reffields) + "\n" f.write(line) #Do values i = 0 while i < interpreter.getDataLength()-1: line = "" for key in fields: line += str(interpreter.getData()[key][i]) + delim line = line.rstrip(delim) line += "\n" f.write(line) i += 1 #Cleanup f.close() def resolve(lst, keys): """ Return a list of values from a dictionary corresponding to keys provided """ out = [] for key in keys: out.append(lst[key]) return out def split_densify(a, delim=" "): """ """ rets = [] for p in a.split(delim): if p: rets.append(p.strip()) return rets def log(evt): """ """ print evt def chomp(odt, parent=None): """ """ retHeaders = [] retDict = {} log("Opening %s" % odt) f = open(odt, "r") data = f.readlines() log("File length: %d lines." % len(data)) InData = False if parent: parent.progstart(len(data)) for i, line in enumerate(data): if parent: parent.progreport(i) line = line.strip() #Look out for multiple table headers in the parse! if line[0] == "#": InData = False #Comment or table parse if "Columns" in line: log("Absorbing header data: Identifying coumns.") #Clobber header table retHeaders = [] #Begin slow parse line = line.split("Columns:")[1].strip() while line: grab = "" line = line.strip() if line[0] == "{": #Group match! grab, line = line.split("}", 1) line = line.strip() #Must clear trailing spaces grab = grab.strip("{}") log("Matching title field by symbol: %s" % grab) else: #Spacesplit match print "In spacesplit match:" check = line.split(" ", 1) if len(check) == 1: grab = check[0] line = "" else: grab, line = check grab = grab.strip() log("Matching title field by space: %s" % grab) if grab: log("Indexing %s at point %d" % (grab, len(retHeaders))) retHeaders.append(grab) if not grab in retDict: log("Identifying new header: %s" % grab) retDict[grab] = np.array([]) else: pass #Currently do nothing on other header lines else: if not InData: log("Processing data block.") InData = True #Chew actual data fields = split_densify(line) for i, v in enumerate(fields): fieldname = retHeaders[i] retDict[fieldname] = np.append(retDict[fieldname], float(v)) f.close() return Interpreter(headers_prettify(retDict), list_prettify(retHeaders)) class Interpreter(object): """ """ def __init__(self, idict, keys=None): self.keys = keys if not self.keys: self.keys = list(idict.keys()) self.dict = idict def getNames(self): return self.keys def getData(self): return self.dict def getDataLength(self): return len(self.dict[self.keys[0]]) def list_prettify(inList): """ """ out = [] uniquenessCheck = [] for key in inList: uniquenessCheck.append(key.split(":")) for key in inList: fixedkey = namepolish(key, uniquenessCheck) if fixedkey in out: log("Uh-oh, you might have caused a key collision! This should be impossible.") out.append(fixedkey) return out def headers_prettify(inDict): """ """ outDict = {} uniquenessCheck = [] for key in inDict.keys(): uniquenessCheck.append(key.split(":")) for key in inDict.keys(): fixedkey = namepolish(key, uniquenessCheck) if fixedkey in outDict: log("Uh-oh, you might have caused a key collision! This should be impossible.") outDict[fixedkey] = inDict[key] return outDict def namepolish(name, uniquenessCheck): """Uniquely identify quantity fields. This is pretty ugly, but the key point is this: it filters down to the minimum amount of information necessary to uniquely identify a quantity It makes things more human-readable Parameters ---------- name : str One particular 'key' from header output uniquenessCheck : list[[list]] A list of lists of strings where there are duplicates. Returns ------- str A string of simplified field headers. Examples -------- >>> namepolish('evolver:givenName:quantity', [['evolver', 'givenName', 'quantity'], ['evolver', 'givenName', 'quantity2']]) 'quantity' """ evolver, givenName, quantity = name.split(":") protectEvolver = False for item in PROTECTED_NAMES: if item in evolver: protectEvolver = True #This is pretty ugly, but the key point is this: it filters #down to the minimum amount of information necessary to uniquely identify a quantity #It makes things more human-readable # If the quantity is duplicated if len(_filterOnPos(uniquenessCheck, quantity, 2)) > 1: # If there is a givenName present if givenName: # Take the output from the quantity filter (which we know is > 1 now) # filter this output and check for duplicates of the givenName. if len(_filterOnPos(_filterOnPos(uniquenessCheck, quantity, 2), givenName, 1)) > 1: # Quantity and givenName are both duplicated. We need to keep # the evolver name to distinguish between fields. # If the evolver should be protected, put it second. # It's not clear why the evolver should be first or second # position. if protectEvolver: newname = givenName + " " + evolver + " " + quantity # if evolver should not be protected, put it first. else: newname = evolver + " " + givenName + " " + quantity # There is a given name present, but no duplicates found. # As there are no givenName duplicates, we should be able to # uniquely identify the fields without the evolver. # We may want to protect the evolver - in this case, include it # after the givenName elif protectEvolver: newname = givenName + " " + evolver + " " + quantity # If there are no duplicates in the givenName (the 'quantity' is # duplicated), and the evolver is not protected, drop the evolver. else: newname = givenName + " " + quantity # givenName not present. In this case just output evolver and quantity. else: newname = evolver + " " + quantity # Quantity is not duplicated. Each quantity label is unique, so can identify # the field usuing quantity alone. else: newname = quantity for item in ALWAYS_CLEAR: # Remove evolver prefixes to improve readability newname = newname.replace(item, "") log("Readability adaptation: %s to %s" % (name, newname)) return newname def _filterOnPos(inList, item, dex): """Return list (of lists) if a string is found in a particular position in that list. If the length of 'ret' is more than 1, it means that there is a duplicate of the target item in the indicated position. It seems to be called 'filter on pos' as it returns lists only if the target value is found in the position specified within the lists supplied. """ ret = [] for compare in inList: if compare[dex] == item: ret.append(compare) return ret def prefix_punt(data): """ """ # Drop prefix (with _ separator) return data.split("_")[-1] ######## # MAIN # ######## if __name__ == "__main__": app = wx.App(None) BigBoss = MainFrame() app.MainLoop()
PypiClean
/ESMValTool-2.9.0-py3-none-any.whl/esmvaltool/diag_scripts/autoassess/_plot_mo_metrics.py
import csv import errno import os import matplotlib.pyplot as plt import numpy as np from esmvaltool.diag_scripts.shared import save_figure # Define some colours BLACK = '#000000' RED = '#FF0000' AMBER = '#FF8C00' GREEN = '#7CFC00' OBS_GREY = '#000000' ACC_GREY = '#00FFFF' STD_GREY = '#EEEEEE' NOOBS_GREY = '#A9A9A9' # Set available markers # Those towards end of list are not really suitable but do extend list # - How about custom symbols? MARKERS = 'ops*dh^v<>+xDH.,' # Create fakelines for legend using MARKERS above FAKELINES = [ plt.Line2D([0, 0], [0, 1], marker=marker, color=BLACK, linestyle='') for marker in MARKERS ] def merge_obs_acc(obs, acc): """ Merge observation errors. Routine to merge observational uncertainty and acceptable range dictionaries into one dictionary. Returned dictionary will only contain metrics from the obs dictionary. :param dict obs: Dictonary of observational uncertainties :param dict acc: Dictonary of acceptable ranges :returns: A merge of the obs and acc dictionaries :rtype: dict. """ metrics = {} for metric in obs.keys(): values = list(obs[metric]) if metric in acc: values += list(acc[metric]) metrics[metric] = tuple(values) return metrics def write_order_metrics(csvfile, metrics): """ Write out ordered metrics. Routine to write out an ordered list of metrics csv file. Not really csv but easily written out by csv package. This is a line by line ordered list of the metrics that will be plotted on a NAC plot. It should be read in and out of a list object. :param str csvfile: CSV file name :param list metrics: Ordered list of metrics. """ if metrics: try: outf = open(csvfile, 'w') except IOError as ioerr: if ioerr.errno == errno.EACCES: pass # Raise Error else: with outf: writer = csv.writer(outf, delimiter=',', quotechar='"') for metric in metrics: writer.writerow([metric]) def write_model_metrics(csvfile, metrics): """ Write out ordered model metrics. Routine to write out model metrics csv file. An unordered list of metrics with a single value metric that are obtained from processing model output. Note that the model uncertainty also fits this description. This should be read in and out of a dictionary object with metric name as key and single float as value. :param str csvfile: CSV file name :param dict metrics: Dictionary containing metric values. """ if metrics: try: outf = open(csvfile, 'w') except IOError as ioerr: if ioerr.errno == errno.EACCES: pass # Raise Error else: with outf: writer = csv.writer(outf, delimiter=',', quotechar='"') for metric in metrics.items(): writer.writerow(metric) def write_obs_metrics(csvfile, obs, acc): """ Write obs. Routine to read in observation metrics csv file. An unordered list of metrics with either 2 or 4 values. The first 2 vals are the observation range and must exist for any entry. The second 2 vals, if they exist, are for the acceptable range of the metric. The observation metrics can either be generated through the same process as the model or set as fixed reference values. Note that if the metric is a relative metric (e.g. error) then the first value of a pair should always be zero. These should be read in and out of two dictionary objects (one for obs and one for acc) with metric name as key and a tuple of two floats as the val. :param str csvfile: CSV file name :param dict obs: Dictonary of observational uncertainties :param dict acc: Dictonary of acceptable ranges. """ metrics = merge_obs_acc(obs, acc) if metrics: try: outf = open(csvfile, 'w') except IOError as ioerr: if ioerr.errno == errno.EACCES: pass # Raise Error else: with outf: writer = csv.writer(outf, delimiter=',', quotechar='"') for (metric, values) in metrics.items(): writer.writerow([metric] + list(values)) def read_order_metrics(csvfile, required=False): """ Read oredred metrics. Routine to read in ordered list of metrics csv file. Not really csv but easily read in by csv package. This is a line by line ordered list of the metrics that will be plotted on a NAC plot. It should be read in and out of a list object. :param str csvfile: CSV file name containing an ordered list of metrics :param bool required: If True then raise error if file does not exist :returns: An ordered list containing metric names :rtype: list. """ metrics = [] if csvfile is not None: try: inf = open(csvfile, 'rb') except IOError as ioerr: if ioerr.errno == errno.EACCES: if required: pass # Raise Error else: pass # Raise Warning else: with inf: reader = csv.reader(inf, delimiter=',', quotechar='"') for row in reader: if len(row) == 1: metrics.append(row[0]) else: msg = "Ordered metrics file is not properly configured" raise ValueError(msg) return metrics def read_model_metrics(csvfile, required=False): """ Read model metrics. Routine to read in model metrics csv file. An unordered list of metrics with a single value metric that are obtained from processing model output. Note that the model uncertainty also fits this description. This should be read in and out of a dictionary object with metric name as key and single float as value. :param str csvfile: CSV file name containing model data :param bool required: If True then raise error if file does not exist :returns: Dictionary containing metric values :rtype: dict. """ metrics = {} if csvfile is not None: try: inf = open(csvfile, 'rt') except IOError as ioerr: if ioerr.errno == errno.EACCES: if required: pass # Raise Error else: pass # Raise Warning else: with inf: reader = csv.reader(inf, delimiter=',', quotechar='"') for row in reader: metric = row.pop(0) if len(row) == 1: metrics[metric] = float(row[0]) else: msg = "Model metrics file is not properly configured" raise ValueError(msg) return metrics def read_obs_metrics(csvfile, required=False): """ Routine to read in observation metrics csv file. An unordered list of metrics with either 2 or 4 values. The first 2 values are the observation range and must exist for any entry. The second 2 value if they exist, are for the acceptable range of the metric. The observation metrics can either be generated through the same process as the model or set as fixed reference values. Note that if the metric is a relative metri (e.g. error) then the first value of a pair should always be zero. These should be read in and out of two dictionary objects (one for obs and one for acc) with metric name as key and a tuple of two floats as the value. :param str csvfile: CSV file name containing observational data :param bool required: If True then raise error if file does not exist :returns: A pair of metric dictionaries containing observational uncertainties and acceptable ranges :rtype: tuple. """ obs = {} acc = {} if csvfile is not None: try: inf = open(csvfile, 'rt') except IOError as ioerr: if ioerr.errno == errno.EACCES: if required: pass # Raise Error else: pass # Raise Warning else: with inf: reader = csv.reader(inf, delimiter=',', quotechar='"') for row in reader: metric = row.pop(0) # Contrary to documentation, allowing a single entry when # there is only a single observation value. Will # ultimately want to remove this as all observations # should be uncertainty ranges (i.e. multiple obs sources) if len(row) == 1: obs[metric] = tuple( sorted([float(row[0]), float(row[0])])) elif len(row) == 2: obs[metric] = tuple( sorted([float(row[0]), float(row[1])])) elif len(row) == 4: obs[metric] = tuple( sorted([float(row[0]), float(row[1])])) acc[metric] = tuple( sorted([float(row[2]), float(row[3])])) else: msg = "Obs metrics file is not properly configured" raise ValueError(msg) return (obs, acc) def metric_colour(test, ref=1.0, var=None, obs=None, acc=None): """ Routine to determine whether to colour metric. GREEN = test within observational uncertainty or acceptable range AMBER = within model uncertainty, or better than reference but neither ref or test within observational bounds or acceptable range RED = worse than reference and outside model uncertainty GREY = no observational uncertainty or acceptable range In a lot of instances test/var/obs/acc will have been normalised by ref, so ref=1.0. obs and acc should be 2 element tuples that indicate the range of uncertainty that is acceptable. The model uncertainty is defined as (ref-var, ref+var) :param float test: Test metric value :param float ref: Reference metric value :param float var: Model uncertainty value :param tuple obs: Observational uncertainty as (min, max) :param tuple acc: Acceptable range as (min, max) :returns: Colour to use in plot indicating performance of metric :rtype: str. """ # Default colour to NOOBS_GREY indicating no observational uncertainty colour = NOOBS_GREY # If specified, find if test within model uncertainty is_test_in_var = False if var is not None: is_test_in_var = (ref - var <= test <= ref + var) # Get AMBER automatically if test within model uncertainty, or RED if # not within model uncertainty if is_test_in_var: colour = AMBER else: colour = RED # If using acceptable ranges, use as proxy for observational uncertainty if acc is not None: obs = acc # Only do the rest if observational uncertainty is specified if obs is not None: # Turn data into logicals: # Find if reference and test within observational uncertainty is_ref_in_obs = (obs[0] <= ref <= obs[1]) is_test_in_obs = (obs[0] <= test <= obs[1]) # Is test better than reference, judge by which is closer to # observational uncertainty. # NOTE: Don't worry here about whether reference or test are within # observational uncertainty as logic for colours precludes that # situation. ref_err = min(abs(ref - obs[0]), abs(ref - obs[1])) test_err = min(abs(test - obs[0]), abs(test - obs[1])) is_test_better = (test_err <= ref_err) # Now for colour logic: # Default to RED (if not already set) for if test definitely worse, # will try to turn it into a different colour if colour == NOOBS_GREY: colour = RED # Get GREEN automatically if test within observational uncertainty if is_test_in_obs: colour = GREEN else: # If test outside model uncertainty, but reference outside # observational uncertainty and test is better than reference # then get AMBER. if not is_test_in_var: if (not is_ref_in_obs) and is_test_better: colour = AMBER return colour def metric_colours(test, ref=None, var=None, obs=None, acc=None): """ Routine to loop over metrics and generate list of colours. :param dict test: Dictionary of test metrics :param dict ref: Dictionary of reference metrics :param dict var: Dictionary of model uncertainties as single values :param dict obs: Dictionary of observation uncertainties as (min, max) :param dict acc: Dictionary of acceptable ranges as (min, max) :returns: Dictionary of colours for test metrics :rtype: dict. """ # initialize if ref is None: ref = {} if var is None: var = {} if obs is None: obs = {} if acc is None: acc = {} colours = {} if ref: # Test to make sure if reference metrics dictionary not empty then it # contains the same metrics as test metrics dictionary assert sorted(test.keys()) == sorted(ref.keys()), \ "If supplying ref it must have same metrics as test" else: # Create reference metrics dictionary with values of 1.0 to match # test metrics dictionary ref = {metric: 1.0 for metric in test.keys()} for metric in test.keys(): colours[metric] = metric_colour( test[metric], ref=ref[metric], var=var.get(metric, None), obs=obs.get(metric, None), acc=acc.get(metric, None)) return colours def normalise(test, ref, strict=False): """ Routine to normalise contents of test by contents of ref. :param dict test: Dictionary of test metrics :param dict ref: Dictionary of reference metrics :param bool strict: if True then test and ref must have same metrics :returns: Dictionary of normalised test metrics :rtype: dict. """ if strict: # Test to make sure reference metrics dictionary contains the same # metrics as test metrics dictionary assert sorted(test.keys()) == sorted(ref.keys()), \ "ref and test must have same set of metrics" norm = {} for metric in test.keys(): if metric in ref: if_float = isinstance(test[metric], float) if_int = isinstance(test[metric], int) if if_float or if_int: if ref[metric] != 0: norm[metric] = test[metric] / ref[metric] else: ref[metric] = 1.e-20 norm[metric] = test[metric] / ref[metric] else: if ref[metric] != 0: norm[metric] = tuple(x / ref[metric] for x in test[metric]) else: ref[metric] = 1. norm[metric] = tuple(x * 0. / ref[metric] for x in test[metric]) return norm def plot_std(ax, metrics, data, color=STD_GREY, zorder=0): """ Plot model uncertainty as filled bars about nac=1 line. :param axes ax: ``matplotlib.axes`` to plot data in :param list metrics: List of metrics to plot in order :param dict data: Metrics dictionary :param str color: Colour to plot bars :param int zorder: Matplotlib plot layer. """ # Extract metric data and line up with requested metrics coord = [i + 1 for (i, metric) in enumerate(metrics) if metric in data] std = [data[metric] for metric in metrics if metric in data] # Convert to numpy arrays coord = np.array(coord) std = np.array(std) # Create plot ax.barh( coord, 2.0 * std, left=1.0 - std, height=1.0, align='center', color=color, linewidth=0, zorder=zorder) def plot_obs(ax, metrics, data, color=OBS_GREY, zorder=1): """ Plot obs range as error bars. :param axes ax: ``matplotlib.axes`` to plot data in :param list metrics: List of metrics to plot in order :param dict data: Metrics dictionary :param str color: Colour to plot error bars :param int zorder: Matplotlib plot layer. """ # Extract metric data and line up with requested metrics coord = [i + 1 for (i, metric) in enumerate(metrics) if metric in data] obsmin = [data[metric][0] for metric in metrics if metric in data] obsmax = [data[metric][1] for metric in metrics if metric in data] # Convert to numpy arrays coord = np.array(coord) obsmin = np.array(obsmin) obsmax = np.array(obsmax) # Calculate inputs for plotting orig = 0.5 * (obsmax + obsmin) err = 0.5 * (obsmax - obsmin) # Create plot ax.errorbar( orig, coord, xerr=err, fmt='none', ecolor=color, capsize=5, zorder=zorder) def plot_metrics(ax, metrics, data, cols, marker, zorder=3): """ Plot metrics using symbols. :param axes ax: ``matplotlib.axes`` to plot data in :param list metrics: List of metrics to plot in order :param dict data: Metrics dictionary :param dict cols: Metric colours dictionary :param str marker: Matplotlib symbol to use in plot :param int zorder: Matplotlib plot layer. """ # Extract metric data and line up with requested metrics coord = [i + 1 for (i, metric) in enumerate(metrics) if metric in data] pdata = [data[metric] for metric in metrics if metric in data] pcols = [cols[metric] for metric in metrics if metric in data] # Convert to numpy arrays coord = np.array(coord) pdata = np.array(pdata) pcols = np.array(pcols) # Create plot ax.scatter( pdata, coord, s=50, edgecolors=BLACK, c=pcols, marker=marker, zorder=zorder) def plot_get_limits(tests, obs, acc, extend_y=False): """ Determine data axis limits. :param list tests: Test experiment metrics dictionary list :param dict obs: Observational uncertainty metrics dictionary :param dict acc: Acceptable range metrics dictionary :param bool extend_y: Extend y-axis to include obs/acc ranges. """ # Calculate absmax/max/min for experiments minval = min([min(test.values()) for test in tests]) maxval = max([max(test.values()) for test in tests]) maxabs = max([np.abs(list(test.values()))[0] for test in tests]) # If want to extend beyond range of observations if extend_y: if obs: ominval = min([min(x, y) for (x, y) in obs.values()]) omaxval = max([max(x, y) for (x, y) in obs.values()]) omaxabs = max([max(abs(x), abs(y)) for (x, y) in obs.values()]) maxabs = max(maxabs, omaxabs) minval = min(minval, ominval) maxval = max(maxval, omaxval) if acc: aminval = min([min(x, y) for (x, y) in acc.values()]) amaxval = max([max(x, y) for (x, y) in acc.values()]) amaxabs = max([max(abs(x), abs(y)) for (x, y) in acc.values()]) maxabs = max(maxabs, amaxabs) minval = min(minval, aminval) maxval = max(maxval, amaxval) # Add/Subtract a little bit extra to fully contain plot extend = 0.05 extra = maxabs * extend minval -= extra maxval += extra # Make range no less than (0, 2) maxval = max(maxval, 2.0) minval = min(minval, 0.0) return (minval, maxval) def plot_nac(cref, ctests, ref, tests, metrics=None, var=None, obs=None, acc=None, extend_y=False, title=None, ofile=None, config=None): """ Routine to produce NAC plot. :param str cref: Reference experiment name :param list ctests: Test experiment names list :param dict ref: Reference experiment metric dictionary :param list tests: Test experiment metrics dictionary list :param list metrics: List of metrics to plot in order :param dict var: Model uncertainty metrics dictionary :param dict obs: Observational uncertainty metrics dictionary :param dict acc: Acceptable range metrics dictionary :param bool extend_y: Extend y-axis to include obs/acc ranges :param str title: Plot title :param str ofile: Plot file name :param dict config: ESMValTool configuration object """ # initialize if metrics is None: metrics = [] if var is None: var = {} if obs is None: obs = {} if acc is None: acc = {} # Create plot figure and axes (fig, ax) = plt.subplots() # If metrics haven't been supplied then generate from reference metrics if not metrics: metrics = sorted(ref.keys()) # Normalise obs/acc/var by ref n_var = normalise(var, ref) n_obs = normalise(obs, ref) n_acc = normalise(acc, ref) # Plot obs/acc/var plot_std(ax, metrics, n_var, color=STD_GREY, zorder=0) plot_obs(ax, metrics, n_acc, color=ACC_GREY, zorder=1) plot_obs(ax, metrics, n_obs, color=OBS_GREY, zorder=2) # Plot metric data n_tests = [] for (test, marker) in zip(tests, MARKERS): # Normalise test by ref n_test = normalise(test, ref, strict=True) # Check for green/amber/red/grey colours = metric_colours(n_test, var=n_var, obs=n_obs, acc=n_acc) # Plot test plot_metrics(ax, metrics, n_test, colours, marker, zorder=3) # Keep normalised test data to help configure plot n_tests.append(n_test) # Find plot limits limits = plot_get_limits(n_tests, n_obs, n_acc, extend_y=extend_y) # Set limits, label axes and add norm=0 & 1 lines ax.axvline(0.0, color=BLACK, linestyle='dotted') ax.axvline(1.0, color=BLACK) ax.set_yticks(np.arange(len(metrics)) + 1) ax.set_yticklabels(metrics, ha='right', fontsize='x-small') ax.set_ylim(len(metrics) + 0.5, 0.5) ax.set_xlim(limits) ax.set_xlabel('Normalised Assessment Criteria', fontsize='small') ax.tick_params(axis='x', labelsize='small') if title is not None: ax.set_title(title) # Add plot legend legend = ax.legend( FAKELINES[0:len(ctests)], ctests, bbox_to_anchor=(1, 1), loc=2, numpoints=1, fancybox=True, fontsize='small') legend.set_title('Vs %s' % cref, prop={'size': 'small'}) # Display or produce file if ofile and config: os.makedirs(config['plot_dir'], exist_ok=True) provenance = get_provenance_record(config) # Note that bbox_inches only works for png plots save_figure(ofile, provenance, config, fig, bbox_extra_artists=(legend, ), bbox_inches='tight') else: # Need the following to attempt to display legend in frame fig.subplots_adjust(right=0.85) plt.show() plt.close() def get_provenance_record(config): """Create a provenance record describing the diagnostic data and plot.""" filenames = [item["filename"] for item in config["input_data"].values()] record = { 'caption': 'Normalised assessment criteria plot', 'plot_type': 'metrics', 'authors': [ 'williams_keith', 'predoi_valeriu', 'sellar_alistair' ], "ancestors": filenames, } return record
PypiClean
/LiMiC-0.3.20.tar.gz/LiMiC-0.3.20/limic/serve_web.py
COUNTRIES = (("countries",),{'type':str,'nargs':'+','help':"countries to route on",'metavar':'COUNTRY'}) GRAPH = (("graph_file",),{'type':str,'help':"use graph file GRAPH",'metavar':'GRAPH'}) HTML = (("html_file",),{'type':str,'help':"use rendered HTML file",'metavar':'HTML'}) RHOST = (("--render-host",),{'type':str,'dest':'r_host','default':'127.0.0.1','help':"render hostname (default: 127.0.0.1)",'metavar':'HOST'}) RPORT = (("--render-port",),{'type':int,'dest':'r_port','default':5000, 'help':"render port number (default: 5000)",'metavar':'PORT'}) RPREFIX = (("--render-prefix",),{'type':str,'dest':'r_prefix','default':'','help':"render URI prefix (default: '')",'metavar':'PREFIX'}) HOST = (("--host",),{'type':str,'dest':'host','default':'0.0.0.0','help':"hostname (default: 0.0.0.0)",'metavar':'HOST'}) PORT = (("--port",),{'type':int,'dest':'port','default':5000, 'help':"port number (default: 5000)",'metavar':'PORT'}) PREFIX = (("--prefix",),{'type':str,'dest':'prefix','default':'','help':"URI prefix (default: '')",'metavar':'PREFIX'}) OSM = (("--osm",),{'action':'store_true','dest':'osm','default':False,'help':"process from OSM file (SLOW)"}) NOBROWSER = (("-n","--no-browser"),{'action':'store_true','dest':'no_browser','default':False,'help':"do not open html in browser (headless)"}) URL = (("-d","--download-url"),{'type':str,'dest':'url','help':"define url for download directory to be URL",'metavar':'URL'}) SHOW = (("-l","--list"),{'action':'store_true','dest':'show','default':False,'help':"list available countries (default: False)"}) CONSERVEMEM = (("-c","--conserve-memory"),{'action':'store_true','dest':'conserve_mem','default':False,'help':"lower memory usage but higher runtime"}) CONFIG = [ ("auto",{'help':"start HTTP server for given COUNTRY (default: Europe)",'args':[SHOW,URL,CONSERVEMEM,NOBROWSER,HOST,PORT,PREFIX,RHOST,RPORT,RPREFIX,OSM,COUNTRIES]}), ("nx",{'help':"start HTTP server for given GRAPH and rendered HTML file",'args':[SHOW,URL,NOBROWSER,HOST,PORT,PREFIX,RHOST,RPORT,RPREFIX,GRAPH,HTML]}), ("npz",{'help':"start HTTP server for given GRAPH and rendered HTML file",'args':[SHOW,URL,NOBROWSER,HOST,PORT,PREFIX,RHOST,RPORT,RPREFIX,GRAPH,HTML]}) ] def serve_auto(countries,host="localhost",port=5000,prefix="",osm=False,url=None,show=False,no_browser=False,r_host="localhost",r_port=5000,r_prefix="",conserve_mem=False): from limic.download import common, download_graph, download_merged, download_osm from limic.init import extract_osm_all, merge_all from limic.render import render_nx graph_file = None if osm: countries, url = common(countries=countries,url=url,show=show,osm=osm,join=False) download_osm(countries=countries,url=url) extract_osm_all(countries=countries,conserve_mem=conserve_mem) else: countries, url = common(countries=countries,url=url,show=show,osm=osm,join=True) download_graph(suffix="npz",countries=countries,url=url,show=show,join=True) if len(countries) > 1 : merge_all(countries) if len(countries) == 1: graph_file = "graph."+countries[0]+(".nx" if osm else ".npz") html_file = graph_file[:-2]+"html" if osm: serve_nx(graph_file,html_file,host=host,port=port,prefix=prefix,url=url,show=show,no_browser=no_browser,r_host=r_host,r_port=r_port,r_prefix=r_prefix) else: serve_npz(graph_file,html_file,host=host,port=port,prefix=prefix,url=url,show=show,no_browser=no_browser,r_host=r_host,r_port=r_port,r_prefix=r_prefix) def serve_nx(graph_file,html_file,host="localhost",port=5000,prefix="",url=None,show=False,no_browser=False,r_host="localhost",r_port=5000,r_prefix=""): from render import render_nx from route import astar_nx g,nodes = render_nx(graph_file,html_file,host=r_host,port=r_port,prefix=r_prefix) serve(g,nodes,astar_nx,html_file,host,port,prefix,url,show,no_browser,r_host,r_port,r_prefix) def serve_npz(graph_file,html_file,host="localhost",port=5000,prefix="",url=None,show=False,no_browser=False,r_host="localhost",r_port=5000,r_prefix=""): from limic.render import render_npz from limic.route import astar_npz g,nodes = render_npz(graph_file,html_file,host=r_host,port=r_port,prefix=r_prefix) serve(g,nodes,astar_npz,html_file,host,port,prefix,url,show,no_browser,r_host,r_port,r_prefix) def serve(g,nodes,astar,html_file,host="localhost",port=5000,prefix="",url=None,show=False,no_browser=False,r_host="localhost",r_port=5000,r_prefix=""): from flask import Flask, jsonify, request from limic.util import load_pickled, start, end, status from threading import Thread from time import sleep from webbrowser import open as wopen from scipy.spatial import cKDTree as KDTree from pyproj import CRS, Transformer start("Initializing KD-Tree") crs_4326 = CRS("WGS84") crs_proj = CRS("EPSG:28992") transformer = Transformer.from_crs(crs_4326, crs_proj) tree = KDTree(list(map(lambda x:transformer.transform(x[1],x[2]),nodes))) end() my_file="Test.html" start("Setting up the app.........") app = Flask("LiMiC") @app.route(prefix+"/") def hello(): return open(my_file).read() @app.route(prefix+"/tower") def tower(): lat = float(request.args.get('lat')) lng = float(request.args.get('lng')) start("Finding tower",lat,lng) tower = nodes[tree.query(transformer.transform(lat,lng))[1]] end('') res = jsonify(tower=tower) end() return res @app.route(prefix+"/web") def web(): return open(my_file).read() @app.route(prefix+"/route") def route(): source_lat = float(request.args.get('source[lat]')) source_lng = float(request.args.get('source[lng]')) target_lat = float(request.args.get('target[lat]')) target_lng = float(request.args.get('target[lng]')) start("Routing",source_lat,source_lng,target_lat,target_lng) source_index = tree.query(transformer.transform(source_lat,source_lng))[1] source = nodes[source_index] end('') target_index = tree.query(transformer.transform(target_lat,target_lng))[1] target = nodes[target_index] end('') path = astar(g,(source,source_index),(target,target_index)) end('') if path[1][-1][0] == float('inf'): path[1][-1] = (path[1][-1][1],)+path[1][-1][1:] res = jsonify(path=path) #print(len(path[1])) i=0 f= open("Data.txt","w+") while (i <len(path[1])): t=path[1][i] lat=print(t[4]) f.write(str(t[4])+","+str(t[5])+"\n") i=i+1 end() f.close() return res end() class OpenThread(Thread): def run(self): delay = 0.5 sleep(delay) url = "http://%s:%d%s/" % (r_host,r_port,r_prefix) start("Open",url,"in browser") wopen(url,new=2) status("DONE") if not no_browser: OpenThread().start() app.run(host=host,port=port) if __name__ == "__main__": import sys serve_nx(sys.argv[1],sys.argv[2])
PypiClean
/DataGridBWC-0.2.2.tar.gz/DataGridBWC-0.2.2/datagridbwc_ta/static/js/jquery.multiselect.min.js
(function(d){var j=0;d.widget("ech.multiselect",{options:{header:!0,height:175,minWidth:225,classes:"",checkAllText:"Check all",uncheckAllText:"Uncheck all",noneSelectedText:"Select options",selectedText:"# selected",selectedList:0,show:"",hide:"",autoOpen:!1,multiple:!0,position:{}},_create:function(){var a=this.element.hide(),b=this.options;this.speed=d.fx.speeds._default;this._isOpen=!1;a=(this.button=d('<button type="button"><span class="ui-icon ui-icon-triangle-2-n-s"></span></button>')).addClass("ui-multiselect ui-widget ui-state-default ui-corner-all").addClass(b.classes).attr({title:a.attr("title"), "aria-haspopup":!0,tabIndex:a.attr("tabIndex")}).insertAfter(a);(this.buttonlabel=d("<span />")).html(b.noneSelectedText).appendTo(a);var a=(this.menu=d("<div />")).addClass("ui-multiselect-menu ui-widget ui-widget-content ui-corner-all").addClass(b.classes).appendTo(document.body),c=(this.header=d("<div />")).addClass("ui-widget-header ui-corner-all ui-multiselect-header ui-helper-clearfix").appendTo(a);(this.headerLinkContainer=d("<ul />")).addClass("ui-helper-reset").html(function(){return!0=== b.header?'<li><a class="ui-multiselect-all" href="#"><span class="ui-icon ui-icon-check"></span><span>'+b.checkAllText+'</span></a></li><li><a class="ui-multiselect-none" href="#"><span class="ui-icon ui-icon-closethick"></span><span>'+b.uncheckAllText+"</span></a></li>":"string"===typeof b.header?"<li>"+b.header+"</li>":""}).append('<li class="ui-multiselect-close"><a href="#" class="ui-multiselect-close"><span class="ui-icon ui-icon-circle-close"></span></a></li>').appendTo(c);(this.checkboxContainer= d("<ul />")).addClass("ui-multiselect-checkboxes ui-helper-reset").appendTo(a);this._bindEvents();this.refresh(!0);b.multiple||a.addClass("ui-multiselect-single")},_init:function(){!1===this.options.header&&this.header.hide();this.options.multiple||this.headerLinkContainer.find(".ui-multiselect-all, .ui-multiselect-none").hide();this.options.autoOpen&&this.open();this.element.is(":disabled")&&this.disable()},refresh:function(a){var b=this.element,c=this.options,e=this.menu,h=this.checkboxContainer, g=[],f=[],i=b.attr("id")||j++;b.find("option").each(function(b){d(this);var a=this.parentNode,e=this.innerHTML,h=this.title,j=this.value,b=this.id||"ui-multiselect-"+i+"-option-"+b,k=this.disabled,m=this.selected,l=["ui-corner-all"];"optgroup"===a.tagName.toLowerCase()&&(a=a.getAttribute("label"),-1===d.inArray(a,g)&&(f.push('<li class="ui-multiselect-optgroup-label"><a href="#">'+a+"</a></li>"),g.push(a)));k&&l.push("ui-state-disabled");m&&!c.multiple&&l.push("ui-state-active");f.push('<li class="'+ (k?"ui-multiselect-disabled":"")+'">');f.push('<label for="'+b+'" title="'+h+'" class="'+l.join(" ")+'">');f.push('<input id="'+b+'" name="multiselect_'+i+'" type="'+(c.multiple?"checkbox":"radio")+'" value="'+j+'" title="'+e+'"');m&&(f.push(' checked="checked"'),f.push(' aria-selected="true"'));k&&(f.push(' disabled="disabled"'),f.push(' aria-disabled="true"'));f.push(" /><span>"+e+"</span></label></li>")});h.html(f.join(""));this.labels=e.find("label");this._setButtonWidth();this._setMenuWidth(); this.button[0].defaultValue=this.update();a||this._trigger("refresh")},update:function(){var a=this.options,b=this.labels.find("input"),c=b.filter("[checked]"),e=c.length,a=0===e?a.noneSelectedText:d.isFunction(a.selectedText)?a.selectedText.call(this,e,b.length,c.get()):/\d/.test(a.selectedList)&&0<a.selectedList&&e<=a.selectedList?c.map(function(){return d(this).next().text()}).get().join(", "):a.selectedText.replace("#",e).replace("#",b.length);this.buttonlabel.html(a);return a},_bindEvents:function(){function a(){b[b._isOpen? "close":"open"]();return!1}var b=this,c=this.button;c.find("span").bind("click.multiselect",a);c.bind({click:a,keypress:function(a){switch(a.which){case 27:case 38:case 37:b.close();break;case 39:case 40:b.open()}},mouseenter:function(){c.hasClass("ui-state-disabled")||d(this).addClass("ui-state-hover")},mouseleave:function(){d(this).removeClass("ui-state-hover")},focus:function(){c.hasClass("ui-state-disabled")||d(this).addClass("ui-state-focus")},blur:function(){d(this).removeClass("ui-state-focus")}}); this.header.delegate("a","click.multiselect",function(a){if(d(this).hasClass("ui-multiselect-close"))b.close();else b[d(this).hasClass("ui-multiselect-all")?"checkAll":"uncheckAll"]();a.preventDefault()});this.menu.delegate("li.ui-multiselect-optgroup-label a","click.multiselect",function(a){a.preventDefault();var c=d(this),g=c.parent().nextUntil("li.ui-multiselect-optgroup-label").find("input:visible:not(:disabled)"),f=g.get(),c=c.parent().text();!1!==b._trigger("beforeoptgrouptoggle",a,{inputs:f, label:c})&&(b._toggleChecked(g.filter("[checked]").length!==g.length,g),b._trigger("optgrouptoggle",a,{inputs:f,label:c,checked:f[0].checked}))}).delegate("label","mouseenter.multiselect",function(){d(this).hasClass("ui-state-disabled")||(b.labels.removeClass("ui-state-hover"),d(this).addClass("ui-state-hover").find("input").focus())}).delegate("label","keydown.multiselect",function(a){a.preventDefault();switch(a.which){case 9:case 27:b.close();break;case 38:case 40:case 37:case 39:b._traverse(a.which, this);break;case 13:d(this).find("input")[0].click()}}).delegate('input[type="checkbox"], input[type="radio"]',"click.multiselect",function(a){var c=d(this),g=this.value,f=this.checked,i=b.element.find("option");this.disabled||!1===b._trigger("click",a,{value:g,text:this.title,checked:f})?a.preventDefault():(c.focus(),c.attr("aria-selected",f),i.each(function(){if(this.value===g)this.selected=f;else if(!b.options.multiple)this.selected=!1}),b.options.multiple||(b.labels.removeClass("ui-state-active"), c.closest("label").toggleClass("ui-state-active",f),b.close()),b.element.trigger("change"),setTimeout(d.proxy(b.update,b),10))});d(document).bind("mousedown.multiselect",function(a){b._isOpen&&!d.contains(b.menu[0],a.target)&&!d.contains(b.button[0],a.target)&&a.target!==b.button[0]&&b.close()});d(this.element[0].form).bind("reset.multiselect",function(){setTimeout(d.proxy(b.refresh,b),10)})},_setButtonWidth:function(){var a=this.element.outerWidth(),b=this.options;if(/\d/.test(b.minWidth)&&a<b.minWidth)a= b.minWidth;this.button.width(a)},_setMenuWidth:function(){var a=this.menu,b=this.button.outerWidth()-parseInt(a.css("padding-left"),10)-parseInt(a.css("padding-right"),10)-parseInt(a.css("border-right-width"),10)-parseInt(a.css("border-left-width"),10);a.width(b||this.button.outerWidth())},_traverse:function(a,b){var c=d(b),e=38===a||37===a,c=c.parent()[e?"prevAll":"nextAll"]("li:not(.ui-multiselect-disabled, .ui-multiselect-optgroup-label)")[e?"last":"first"]();c.length?c.find("label").trigger("mouseover"): (c=this.menu.find("ul").last(),this.menu.find("label")[e?"last":"first"]().trigger("mouseover"),c.scrollTop(e?c.height():0))},_toggleState:function(a,b){return function(){this.disabled||(this[a]=b);b?this.setAttribute("aria-selected",!0):this.removeAttribute("aria-selected")}},_toggleChecked:function(a,b){var c=b&&b.length?b:this.labels.find("input"),e=this;c.each(this._toggleState("checked",a));c.eq(0).focus();this.update();var h=c.map(function(){return this.value}).get();this.element.find("option").each(function(){!this.disabled&& -1<d.inArray(this.value,h)&&e._toggleState("selected",a).call(this)});c.length&&this.element.trigger("change")},_toggleDisabled:function(a){this.button.attr({disabled:a,"aria-disabled":a})[a?"addClass":"removeClass"]("ui-state-disabled");this.menu.find("input").attr({disabled:a,"aria-disabled":a}).parent()[a?"addClass":"removeClass"]("ui-state-disabled");this.element.attr({disabled:a,"aria-disabled":a})},open:function(){var a=this.button,b=this.menu,c=this.speed,e=this.options;if(!(!1===this._trigger("beforeopen")|| a.hasClass("ui-state-disabled")||this._isOpen)){var h=b.find("ul").last(),g=e.show,f=a.offset();d.isArray(e.show)&&(g=e.show[0],c=e.show[1]||this.speed);h.scrollTop(0).height(e.height);d.ui.position&&!d.isEmptyObject(e.position)?(e.position.of=e.position.of||a,b.show().position(e.position).hide().show(g,c)):b.css({top:f.top+a.outerHeight(),left:f.left}).show(g,c);this.labels.eq(0).trigger("mouseover").trigger("mouseenter").find("input").trigger("focus");a.addClass("ui-state-active");this._isOpen= !0;this._trigger("open")}},close:function(){if(!1!==this._trigger("beforeclose")){var a=this.options,b=a.hide,c=this.speed;d.isArray(a.hide)&&(b=a.hide[0],c=a.hide[1]||this.speed);this.menu.hide(b,c);this.button.removeClass("ui-state-active").trigger("blur").trigger("mouseleave");this._isOpen=!1;this._trigger("close")}},enable:function(){this._toggleDisabled(!1)},disable:function(){this._toggleDisabled(!0)},checkAll:function(){this._toggleChecked(!0);this._trigger("checkAll")},uncheckAll:function(){this._toggleChecked(!1); this._trigger("uncheckAll")},getChecked:function(){return this.menu.find("input").filter("[checked]")},destroy:function(){d.Widget.prototype.destroy.call(this);this.button.remove();this.menu.remove();this.element.show();return this},isOpen:function(){return this._isOpen},widget:function(){return this.menu},_setOption:function(a,b){var c=this.menu;switch(a){case "header":c.find("div.ui-multiselect-header")[b?"show":"hide"]();break;case "checkAllText":c.find("a.ui-multiselect-all span").eq(-1).text(b); break;case "uncheckAllText":c.find("a.ui-multiselect-none span").eq(-1).text(b);break;case "height":c.find("ul").last().height(parseInt(b,10));break;case "minWidth":this.options[a]=parseInt(b,10);this._setButtonWidth();this._setMenuWidth();break;case "selectedText":case "selectedList":case "noneSelectedText":this.options[a]=b;this.update();break;case "classes":c.add(this.button).removeClass(this.options.classes).addClass(b)}d.Widget.prototype._setOption.apply(this,arguments)}})})(jQuery);
PypiClean
/ChatExchange-0.0.4-py3-none-any.whl/chatexchange/client.py
import sys if sys.version_info[0] == 2: import Queue as queue else: import queue import logging if sys.version_info[:2] <= (2, 6): logging.Logger.getChild = lambda self, suffix:\ self.manager.getLogger('.'.join((self.name, suffix)) if self.root is not self else suffix) import collections import re import time import threading import weakref import requests from . import browser, events, messages, rooms, users TOO_FAST_RE = r"You can perform this action again in (\d+) seconds" logger = logging.getLogger(__name__) class Client(object): """ A high-level interface for interacting with Stack Exchange chat. @ivar logged_in: Whether this client is currently logged-in. If False, attempting requests will result in errors. @type logged_in: L{bool} @ivar host: Hostname of associated Stack Exchange site. @type host: L{str} @cvar valid_hosts: Set of valid/real Stack Exchange hostnames with chat. @type valid_hosts: L{set} """ _max_recently_gotten_objects = 5000 def __init__(self, host='stackexchange.com', email=None, password=None): """ Initializes a client for a specific chat host. If email and password are provided, the client will L{login}. """ self.logger = logger.getChild('Client') if email or password: assert email and password, ( "must specify both email and password or neither") # any known instances self._messages = weakref.WeakValueDictionary() self._rooms = weakref.WeakValueDictionary() self._users = weakref.WeakValueDictionary() if host not in self.valid_hosts: raise ValueError("invalid host: %r" % (host,)) self.host = host self.logged_in = False self.on_message_sent = None self._request_queue = queue.Queue() self._br = browser.Browser() self._br.host = host self._previous = None self._recently_gotten_objects = collections.deque(maxlen=self._max_recently_gotten_objects) self._requests_served = 0 self._thread = threading.Thread(target=self._worker, name="message_sender") self._thread.setDaemon(True) if email or password: assert email and password self.login(email, password) def get_message(self, message_id, **attrs_to_set): """ Returns the Message instance with the given message_id. Any keyword arguments will be assigned as attributes of the Message. @rtype: L{chatexchange.messages.Message} """ return self._get_and_set_deduplicated( messages.Message, message_id, self._messages, attrs_to_set) def get_room(self, room_id, **attrs_to_set): """ Returns the Room instance with the given room_id. Any keyword arguments will be assigned as attributes of the Room. @rtype: L{rooms.Room} """ return self._get_and_set_deduplicated( rooms.Room, room_id, self._rooms, attrs_to_set) def get_user(self, user_id, **attrs_to_set): """ Returns the User instance with the given room_id. Any keyword arguments will be assigned as attributes of the Room. @rtype: L{users.User} """ return self._get_and_set_deduplicated( users.User, user_id, self._users, attrs_to_set) def _get_and_set_deduplicated(self, cls, id, instances, attrs): instance = instances.setdefault(id, cls(id, self)) for key, value in attrs.items(): setattr(instance, key, value) # we force a fixed number of recent objects to be cached self._recently_gotten_objects.appendleft(instance) return instance valid_hosts = ('stackexchange.com', 'meta.stackexchange.com', 'stackoverflow.com') def get_me(self): """ Returns the currently-logged-in User. @rtype: L{users.User} """ assert self._br.user_id is not None return self.get_user(self._br.user_id, name=self._br.user_name) def login(self, email, password): """ Authenticates using the provided Stack Exchange OpenID credentials. If successful, blocks until the instance is ready to use. """ assert not self.logged_in self.logger.info("Logging in.") self._br.login_site(self.host, email, password) self.logged_in = True self.logger.info("Logged in.") self._thread.start() def logout(self): """ Logs out this client once all queued requests are sent. The client cannot be logged back in/reused. """ assert self.logged_in for watcher in self._br.sockets.values(): watcher.killed = True for watcher in self._br.polls.values(): watcher.killed = True self._request_queue.put(SystemExit) self.logger.info("Logged out.") self.logged_in = False def set_websocket_recovery(self, on_ws_closed): self._br.set_websocket_recovery(on_ws_closed) def __del__(self): if self.logged_in: self._request_queue.put(SystemExit) assert False, "You forgot to log out." def _worker(self): assert self.logged_in self.logger.info("Worker thread reporting for duty.") while True: next_action = self._request_queue.get() # blocking if next_action == SystemExit: self.logger.info("Worker thread exits.") return else: self._requests_served += 1 self.logger.info( "Now serving customer %d, %r", self._requests_served, next_action) self._do_action_despite_throttling(next_action) self._request_queue.task_done() # Appeasing the rate limiter gods is hard. _BACKOFF_ADDER = 5 # When told to wait n seconds, wait n * BACKOFF_MULTIPLIER + BACKOFF_ADDER @staticmethod def _unpack_response(response): try: j = response.json() return j except ValueError: return response.text def _do_action_despite_throttling(self, action): action_type = action[0] if action_type == 'send': action_type, room_id, text = action else: assert action_type == 'edit' or action_type == 'delete' action_type, message_id, text = action sent = False attempt = 0 if text == self._previous: text = " " + text response = None unpacked = None while not sent: wait = 0 attempt += 1 self.logger.debug("Attempt %d: start.", attempt) try: if action_type == 'send': response = self._br.send_message(room_id, text) elif action_type == 'edit': response = self._br.edit_message(message_id, text) else: assert action_type == 'delete' response = self._br.delete_message(message_id) except requests.HTTPError as ex: if ex.response.status_code == 409: # this could be a throttling message we know how to handle response = ex.response else: raise unpacked = Client._unpack_response(response) ignored_messages = ["ok", "It is too late to delete this message", "It is too late to edit this message", "The message has been deleted and cannot be edited", "This message has already been deleted."] if isinstance(unpacked, str) and unpacked not in ignored_messages: match = re.match(TOO_FAST_RE, unpacked) if match: # Whoops, too fast. wait = int(match.group(1)) self.logger.debug( "Attempt %d: denied: throttled, must wait %.1f seconds", attempt, wait) # Wait more than that, though. wait += 1 else: # Something went wrong. I guess that happens. if attempt > 5: err = ChatActionError("5 failed attempts to do chat action. Unknown reason: %s" % unpacked) raise err wait = self._BACKOFF_ADDER logging.error( "Attempt %d: denied: unknown reason %r", attempt, unpacked) elif isinstance(unpacked, dict): if unpacked["id"] is None: # Duplicate message? text += " " # Append because markdown wait = self._BACKOFF_ADDER self.logger.debug( "Attempt %d: denied: duplicate, waiting %.1f seconds.", attempt, wait) if wait: self.logger.debug("Attempt %d: waiting %.1f seconds", attempt, wait) else: wait = self._BACKOFF_ADDER self.logger.debug("Attempt %d: success. Waiting %.1f seconds", attempt, wait) sent = True self._previous = text time.sleep(wait) if action_type == 'send' and isinstance(unpacked, dict) and self.on_message_sent is not None: self.on_message_sent(response.json()["id"], room_id) return response def _join_room(self, room_id): self._br.join_room(room_id) def _leave_room(self, room_id): self._br.leave_room(room_id) class ChatActionError(Exception): pass
PypiClean
/Mezzanine-6.0.0.tar.gz/Mezzanine-6.0.0/mezzanine/blog/templatetags/blog_tags.py
from datetime import datetime from django.contrib.auth import get_user_model from django.db.models import Count, Q from django.utils import timezone from mezzanine import template from mezzanine.blog.forms import BlogPostForm from mezzanine.blog.models import BlogCategory, BlogPost from mezzanine.generic.models import Keyword User = get_user_model() register = template.Library() @register.as_tag def blog_months(*args): """ Put a list of dates for blog posts into the template context. """ dates = BlogPost.objects.published().values_list("publish_date", flat=True) tz = timezone.get_current_timezone() dates = [d.astimezone(tz) for d in dates] date_dicts = [{"date": datetime(d.year, d.month, 1)} for d in dates] month_dicts = [] for date_dict in date_dicts: if date_dict not in month_dicts: month_dicts.append(date_dict) for date_dict in month_dicts: date_dict["post_count"] = date_dicts.count(date_dict) return month_dicts @register.as_tag def blog_categories(*args): """ Put a list of categories for blog posts into the template context. """ posts = BlogPost.objects.published() categories = BlogCategory.objects.filter(blogposts__in=posts) return list(categories.annotate(post_count=Count("blogposts"))) @register.as_tag def blog_authors(*args): """ Put a list of authors (users) for blog posts into the template context. """ blog_posts = BlogPost.objects.published() authors = User.objects.filter(blogposts__in=blog_posts) return list(authors.annotate(post_count=Count("blogposts"))) @register.as_tag def blog_recent_posts(limit=5, tag=None, username=None, category=None): """ Put a list of recently published blog posts into the template context. A tag title or slug, category title or slug or author's username can also be specified to filter the recent posts returned. Usage:: {% blog_recent_posts 5 as recent_posts %} {% blog_recent_posts limit=5 tag="django" as recent_posts %} {% blog_recent_posts limit=5 category="python" as recent_posts %} {% blog_recent_posts 5 username=admin as recent_posts %} """ blog_posts = BlogPost.objects.published().select_related("user") title_or_slug = lambda s: Q(title=s) | Q(slug=s) if tag is not None: try: tag = Keyword.objects.get(title_or_slug(tag)) blog_posts = blog_posts.filter(keywords__keyword=tag) except Keyword.DoesNotExist: return [] if category is not None: try: category = BlogCategory.objects.get(title_or_slug(category)) blog_posts = blog_posts.filter(categories=category) except BlogCategory.DoesNotExist: return [] if username is not None: try: author = User.objects.get(username=username) blog_posts = blog_posts.filter(user=author) except User.DoesNotExist: return [] return list(blog_posts[:limit]) @register.inclusion_tag("admin/includes/quick_blog.html", takes_context=True) def quick_blog(context): """ Admin dashboard tag for the quick blog form. """ context["form"] = BlogPostForm() return context.flatten()
PypiClean
/Jinja2-3.1.2-py3-none-any.whl/jinja2/utils.py
import enum import json import os import re import typing as t from collections import abc from collections import deque from random import choice from random import randrange from threading import Lock from types import CodeType from urllib.parse import quote_from_bytes import markupsafe if t.TYPE_CHECKING: import typing_extensions as te F = t.TypeVar("F", bound=t.Callable[..., t.Any]) # special singleton representing missing values for the runtime missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})() internal_code: t.MutableSet[CodeType] = set() concat = "".join def pass_context(f: F) -> F: """Pass the :class:`~jinja2.runtime.Context` as the first argument to the decorated function when called while rendering a template. Can be used on functions, filters, and tests. If only ``Context.eval_context`` is needed, use :func:`pass_eval_context`. If only ``Context.environment`` is needed, use :func:`pass_environment`. .. versionadded:: 3.0.0 Replaces ``contextfunction`` and ``contextfilter``. """ f.jinja_pass_arg = _PassArg.context # type: ignore return f def pass_eval_context(f: F) -> F: """Pass the :class:`~jinja2.nodes.EvalContext` as the first argument to the decorated function when called while rendering a template. See :ref:`eval-context`. Can be used on functions, filters, and tests. If only ``EvalContext.environment`` is needed, use :func:`pass_environment`. .. versionadded:: 3.0.0 Replaces ``evalcontextfunction`` and ``evalcontextfilter``. """ f.jinja_pass_arg = _PassArg.eval_context # type: ignore return f def pass_environment(f: F) -> F: """Pass the :class:`~jinja2.Environment` as the first argument to the decorated function when called while rendering a template. Can be used on functions, filters, and tests. .. versionadded:: 3.0.0 Replaces ``environmentfunction`` and ``environmentfilter``. """ f.jinja_pass_arg = _PassArg.environment # type: ignore return f class _PassArg(enum.Enum): context = enum.auto() eval_context = enum.auto() environment = enum.auto() @classmethod def from_obj(cls, obj: F) -> t.Optional["_PassArg"]: if hasattr(obj, "jinja_pass_arg"): return obj.jinja_pass_arg # type: ignore return None def internalcode(f: F) -> F: """Marks the function as internally used""" internal_code.add(f.__code__) return f def is_undefined(obj: t.Any) -> bool: """Check if the object passed is undefined. This does nothing more than performing an instance check against :class:`Undefined` but looks nicer. This can be used for custom filters or tests that want to react to undefined variables. For example a custom default filter can look like this:: def default(var, default=''): if is_undefined(var): return default return var """ from .runtime import Undefined return isinstance(obj, Undefined) def consume(iterable: t.Iterable[t.Any]) -> None: """Consumes an iterable without doing anything with it.""" for _ in iterable: pass def clear_caches() -> None: """Jinja keeps internal caches for environments and lexers. These are used so that Jinja doesn't have to recreate environments and lexers all the time. Normally you don't have to care about that but if you are measuring memory consumption you may want to clean the caches. """ from .environment import get_spontaneous_environment from .lexer import _lexer_cache get_spontaneous_environment.cache_clear() _lexer_cache.clear() def import_string(import_name: str, silent: bool = False) -> t.Any: """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If the `silent` is True the return value will be `None` if the import fails. :return: imported object """ try: if ":" in import_name: module, obj = import_name.split(":", 1) elif "." in import_name: module, _, obj = import_name.rpartition(".") else: return __import__(import_name) return getattr(__import__(module, None, None, [obj]), obj) except (ImportError, AttributeError): if not silent: raise def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]: """Returns a file descriptor for the filename if that file exists, otherwise ``None``. """ if not os.path.isfile(filename): return None return open(filename, mode) def object_type_repr(obj: t.Any) -> str: """Returns the name of the object's type. For some recognized singletons the name of the object is returned instead. (For example for `None` and `Ellipsis`). """ if obj is None: return "None" elif obj is Ellipsis: return "Ellipsis" cls = type(obj) if cls.__module__ == "builtins": return f"{cls.__name__} object" return f"{cls.__module__}.{cls.__name__} object" def pformat(obj: t.Any) -> str: """Format an object using :func:`pprint.pformat`.""" from pprint import pformat # type: ignore return pformat(obj) _http_re = re.compile( r""" ^ ( (https?://|www\.) # scheme or www (([\w%-]+\.)+)? # subdomain ( [a-z]{2,63} # basic tld | xn--[\w%]{2,59} # idna tld ) | ([\w%-]{2,63}\.)+ # basic domain (com|net|int|edu|gov|org|info|mil) # basic tld | (https?://) # scheme ( (([\d]{1,3})(\.[\d]{1,3}){3}) # IPv4 | (\[([\da-f]{0,4}:){2}([\da-f]{0,4}:?){1,6}]) # IPv6 ) ) (?::[\d]{1,5})? # port (?:[/?#]\S*)? # path, query, and fragment $ """, re.IGNORECASE | re.VERBOSE, ) _email_re = re.compile(r"^\S+@\w[\w.-]*\.\w+$") def urlize( text: str, trim_url_limit: t.Optional[int] = None, rel: t.Optional[str] = None, target: t.Optional[str] = None, extra_schemes: t.Optional[t.Iterable[str]] = None, ) -> str: """Convert URLs in text into clickable links. This may not recognize links in some situations. Usually, a more comprehensive formatter, such as a Markdown library, is a better choice. Works on ``http://``, ``https://``, ``www.``, ``mailto:``, and email addresses. Links with trailing punctuation (periods, commas, closing parentheses) and leading punctuation (opening parentheses) are recognized excluding the punctuation. Email addresses that include header fields are not recognized (for example, ``mailto:address@example.com?cc=copy@example.com``). :param text: Original text containing URLs to link. :param trim_url_limit: Shorten displayed URL values to this length. :param target: Add the ``target`` attribute to links. :param rel: Add the ``rel`` attribute to links. :param extra_schemes: Recognize URLs that start with these schemes in addition to the default behavior. .. versionchanged:: 3.0 The ``extra_schemes`` parameter was added. .. versionchanged:: 3.0 Generate ``https://`` links for URLs without a scheme. .. versionchanged:: 3.0 The parsing rules were updated. Recognize email addresses with or without the ``mailto:`` scheme. Validate IP addresses. Ignore parentheses and brackets in more cases. """ if trim_url_limit is not None: def trim_url(x: str) -> str: if len(x) > trim_url_limit: # type: ignore return f"{x[:trim_url_limit]}..." return x else: def trim_url(x: str) -> str: return x words = re.split(r"(\s+)", str(markupsafe.escape(text))) rel_attr = f' rel="{markupsafe.escape(rel)}"' if rel else "" target_attr = f' target="{markupsafe.escape(target)}"' if target else "" for i, word in enumerate(words): head, middle, tail = "", word, "" match = re.match(r"^([(<]|&lt;)+", middle) if match: head = match.group() middle = middle[match.end() :] # Unlike lead, which is anchored to the start of the string, # need to check that the string ends with any of the characters # before trying to match all of them, to avoid backtracking. if middle.endswith((")", ">", ".", ",", "\n", "&gt;")): match = re.search(r"([)>.,\n]|&gt;)+$", middle) if match: tail = match.group() middle = middle[: match.start()] # Prefer balancing parentheses in URLs instead of ignoring a # trailing character. for start_char, end_char in ("(", ")"), ("<", ">"), ("&lt;", "&gt;"): start_count = middle.count(start_char) if start_count <= middle.count(end_char): # Balanced, or lighter on the left continue # Move as many as possible from the tail to balance for _ in range(min(start_count, tail.count(end_char))): end_index = tail.index(end_char) + len(end_char) # Move anything in the tail before the end char too middle += tail[:end_index] tail = tail[end_index:] if _http_re.match(middle): if middle.startswith("https://") or middle.startswith("http://"): middle = ( f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>' ) else: middle = ( f'<a href="https://{middle}"{rel_attr}{target_attr}>' f"{trim_url(middle)}</a>" ) elif middle.startswith("mailto:") and _email_re.match(middle[7:]): middle = f'<a href="{middle}">{middle[7:]}</a>' elif ( "@" in middle and not middle.startswith("www.") and ":" not in middle and _email_re.match(middle) ): middle = f'<a href="mailto:{middle}">{middle}</a>' elif extra_schemes is not None: for scheme in extra_schemes: if middle != scheme and middle.startswith(scheme): middle = f'<a href="{middle}"{rel_attr}{target_attr}>{middle}</a>' words[i] = f"{head}{middle}{tail}" return "".join(words) def generate_lorem_ipsum( n: int = 5, html: bool = True, min: int = 20, max: int = 100 ) -> str: """Generate some lorem ipsum for the template.""" from .constants import LOREM_IPSUM_WORDS words = LOREM_IPSUM_WORDS.split() result = [] for _ in range(n): next_capitalized = True last_comma = last_fullstop = 0 word = None last = None p = [] # each paragraph contains out of 20 to 100 words. for idx, _ in enumerate(range(randrange(min, max))): while True: word = choice(words) if word != last: last = word break if next_capitalized: word = word.capitalize() next_capitalized = False # add commas if idx - randrange(3, 8) > last_comma: last_comma = idx last_fullstop += 2 word += "," # add end of sentences if idx - randrange(10, 20) > last_fullstop: last_comma = last_fullstop = idx word += "." next_capitalized = True p.append(word) # ensure that the paragraph ends with a dot. p_str = " ".join(p) if p_str.endswith(","): p_str = p_str[:-1] + "." elif not p_str.endswith("."): p_str += "." result.append(p_str) if not html: return "\n\n".join(result) return markupsafe.Markup( "\n".join(f"<p>{markupsafe.escape(x)}</p>" for x in result) ) def url_quote(obj: t.Any, charset: str = "utf-8", for_qs: bool = False) -> str: """Quote a string for use in a URL using the given charset. :param obj: String or bytes to quote. Other types are converted to string then encoded to bytes using the given charset. :param charset: Encode text to bytes using this charset. :param for_qs: Quote "/" and use "+" for spaces. """ if not isinstance(obj, bytes): if not isinstance(obj, str): obj = str(obj) obj = obj.encode(charset) safe = b"" if for_qs else b"/" rv = quote_from_bytes(obj, safe) if for_qs: rv = rv.replace("%20", "+") return rv @abc.MutableMapping.register class LRUCache: """A simple LRU Cache implementation.""" # this is fast for small capacities (something below 1000) but doesn't # scale. But as long as it's only used as storage for templates this # won't do any harm. def __init__(self, capacity: int) -> None: self.capacity = capacity self._mapping: t.Dict[t.Any, t.Any] = {} self._queue: "te.Deque[t.Any]" = deque() self._postinit() def _postinit(self) -> None: # alias all queue methods for faster lookup self._popleft = self._queue.popleft self._pop = self._queue.pop self._remove = self._queue.remove self._wlock = Lock() self._append = self._queue.append def __getstate__(self) -> t.Mapping[str, t.Any]: return { "capacity": self.capacity, "_mapping": self._mapping, "_queue": self._queue, } def __setstate__(self, d: t.Mapping[str, t.Any]) -> None: self.__dict__.update(d) self._postinit() def __getnewargs__(self) -> t.Tuple: return (self.capacity,) def copy(self) -> "LRUCache": """Return a shallow copy of the instance.""" rv = self.__class__(self.capacity) rv._mapping.update(self._mapping) rv._queue.extend(self._queue) return rv def get(self, key: t.Any, default: t.Any = None) -> t.Any: """Return an item from the cache dict or `default`""" try: return self[key] except KeyError: return default def setdefault(self, key: t.Any, default: t.Any = None) -> t.Any: """Set `default` if the key is not in the cache otherwise leave unchanged. Return the value of this key. """ try: return self[key] except KeyError: self[key] = default return default def clear(self) -> None: """Clear the cache.""" with self._wlock: self._mapping.clear() self._queue.clear() def __contains__(self, key: t.Any) -> bool: """Check if a key exists in this cache.""" return key in self._mapping def __len__(self) -> int: """Return the current size of the cache.""" return len(self._mapping) def __repr__(self) -> str: return f"<{type(self).__name__} {self._mapping!r}>" def __getitem__(self, key: t.Any) -> t.Any: """Get an item from the cache. Moves the item up so that it has the highest priority then. Raise a `KeyError` if it does not exist. """ with self._wlock: rv = self._mapping[key] if self._queue[-1] != key: try: self._remove(key) except ValueError: # if something removed the key from the container # when we read, ignore the ValueError that we would # get otherwise. pass self._append(key) return rv def __setitem__(self, key: t.Any, value: t.Any) -> None: """Sets the value for an item. Moves the item up so that it has the highest priority then. """ with self._wlock: if key in self._mapping: self._remove(key) elif len(self._mapping) == self.capacity: del self._mapping[self._popleft()] self._append(key) self._mapping[key] = value def __delitem__(self, key: t.Any) -> None: """Remove an item from the cache dict. Raise a `KeyError` if it does not exist. """ with self._wlock: del self._mapping[key] try: self._remove(key) except ValueError: pass def items(self) -> t.Iterable[t.Tuple[t.Any, t.Any]]: """Return a list of items.""" result = [(key, self._mapping[key]) for key in list(self._queue)] result.reverse() return result def values(self) -> t.Iterable[t.Any]: """Return a list of all values.""" return [x[1] for x in self.items()] def keys(self) -> t.Iterable[t.Any]: """Return a list of all keys ordered by most recent usage.""" return list(self) def __iter__(self) -> t.Iterator[t.Any]: return reversed(tuple(self._queue)) def __reversed__(self) -> t.Iterator[t.Any]: """Iterate over the keys in the cache dict, oldest items coming first. """ return iter(tuple(self._queue)) __copy__ = copy def select_autoescape( enabled_extensions: t.Collection[str] = ("html", "htm", "xml"), disabled_extensions: t.Collection[str] = (), default_for_string: bool = True, default: bool = False, ) -> t.Callable[[t.Optional[str]], bool]: """Intelligently sets the initial value of autoescaping based on the filename of the template. This is the recommended way to configure autoescaping if you do not want to write a custom function yourself. If you want to enable it for all templates created from strings or for all templates with `.html` and `.xml` extensions:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( enabled_extensions=('html', 'xml'), default_for_string=True, )) Example configuration to turn it on at all times except if the template ends with `.txt`:: from jinja2 import Environment, select_autoescape env = Environment(autoescape=select_autoescape( disabled_extensions=('txt',), default_for_string=True, default=True, )) The `enabled_extensions` is an iterable of all the extensions that autoescaping should be enabled for. Likewise `disabled_extensions` is a list of all templates it should be disabled for. If a template is loaded from a string then the default from `default_for_string` is used. If nothing matches then the initial value of autoescaping is set to the value of `default`. For security reasons this function operates case insensitive. .. versionadded:: 2.9 """ enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions) disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions) def autoescape(template_name: t.Optional[str]) -> bool: if template_name is None: return default_for_string template_name = template_name.lower() if template_name.endswith(enabled_patterns): return True if template_name.endswith(disabled_patterns): return False return default return autoescape def htmlsafe_json_dumps( obj: t.Any, dumps: t.Optional[t.Callable[..., str]] = None, **kwargs: t.Any ) -> markupsafe.Markup: """Serialize an object to a string of JSON with :func:`json.dumps`, then replace HTML-unsafe characters with Unicode escapes and mark the result safe with :class:`~markupsafe.Markup`. This is available in templates as the ``|tojson`` filter. The following characters are escaped: ``<``, ``>``, ``&``, ``'``. The returned string is safe to render in HTML documents and ``<script>`` tags. The exception is in HTML attributes that are double quoted; either use single quotes or the ``|forceescape`` filter. :param obj: The object to serialize to JSON. :param dumps: The ``dumps`` function to use. Defaults to ``env.policies["json.dumps_function"]``, which defaults to :func:`json.dumps`. :param kwargs: Extra arguments to pass to ``dumps``. Merged onto ``env.policies["json.dumps_kwargs"]``. .. versionchanged:: 3.0 The ``dumper`` parameter is renamed to ``dumps``. .. versionadded:: 2.9 """ if dumps is None: dumps = json.dumps return markupsafe.Markup( dumps(obj, **kwargs) .replace("<", "\\u003c") .replace(">", "\\u003e") .replace("&", "\\u0026") .replace("'", "\\u0027") ) class Cycler: """Cycle through values by yield them one at a time, then restarting once the end is reached. Available as ``cycler`` in templates. Similar to ``loop.cycle``, but can be used outside loops or across multiple loops. For example, render a list of folders and files in a list, alternating giving them "odd" and "even" classes. .. code-block:: html+jinja {% set row_class = cycler("odd", "even") %} <ul class="browser"> {% for folder in folders %} <li class="folder {{ row_class.next() }}">{{ folder }} {% endfor %} {% for file in files %} <li class="file {{ row_class.next() }}">{{ file }} {% endfor %} </ul> :param items: Each positional argument will be yielded in the order given for each cycle. .. versionadded:: 2.1 """ def __init__(self, *items: t.Any) -> None: if not items: raise RuntimeError("at least one item has to be provided") self.items = items self.pos = 0 def reset(self) -> None: """Resets the current item to the first item.""" self.pos = 0 @property def current(self) -> t.Any: """Return the current item. Equivalent to the item that will be returned next time :meth:`next` is called. """ return self.items[self.pos] def next(self) -> t.Any: """Return the current item, then advance :attr:`current` to the next item. """ rv = self.current self.pos = (self.pos + 1) % len(self.items) return rv __next__ = next class Joiner: """A joining helper for templates.""" def __init__(self, sep: str = ", ") -> None: self.sep = sep self.used = False def __call__(self) -> str: if not self.used: self.used = True return "" return self.sep class Namespace: """A namespace object that can hold arbitrary attributes. It may be initialized from a dictionary or with keyword arguments.""" def __init__(*args: t.Any, **kwargs: t.Any) -> None: # noqa: B902 self, args = args[0], args[1:] self.__attrs = dict(*args, **kwargs) def __getattribute__(self, name: str) -> t.Any: # __class__ is needed for the awaitable check in async mode if name in {"_Namespace__attrs", "__class__"}: return object.__getattribute__(self, name) try: return self.__attrs[name] except KeyError: raise AttributeError(name) from None def __setitem__(self, name: str, value: t.Any) -> None: self.__attrs[name] = value def __repr__(self) -> str: return f"<Namespace {self.__attrs!r}>"
PypiClean
/GeoBases3K-5.0.16.zip/GeoBases3K-5.0.16/GeoBases/DataSources/CheckDataUpdates.sh
# Moving to the script directory # We could move to the installation directory if we knew it cd `dirname $0` TMP_DIR='/tmp' TMP_VIEW_1='/tmp/fsdlkghiueevlr_02.csv' TMP_VIEW_2='/tmp/fsdlkghiueevlr_03.csv' # By default, we will ask the user permission to replace # the old file, unless -f option is triggered FORCE=0 while getopts ":f" opt; do case $opt in f) echo "Forced update! All files will be replaced..." >&2 FORCE=1 ;; \?) echo "Invalid option: -$OPTARG" >&2 exit 1 ;; esac done view() { if [ -f $1 ] ; then case $1 in *.tar.bz2) tar xvjf $1 ;; *.tar.gz) tar xvzf $1 ;; *.bz2) bunzip2 $1 ;; *.rar) unrar x $1 ;; *.gz) gunzip $1 ;; *.tar) tar xvf $1 ;; *.tbz2) tar xvjf $1 ;; *.tgz) tar xvzf $1 ;; *.zip) unzip -qca $1 ;; *.Z) uncompress $1 ;; *.7z) 7z x $1 ;; *) cat $1 ;; esac else echo "'$1' is not a valid file" fi } extract_one() { unzip -q $1 $2 mv $2 $1 } comment_head() { sed -i '1s/^/#/g' $1 } split_fcodes() { sed -i 's/^\(.\)\./\1\t/g' $1 } do_a_file() { local TMP_CSV local REF_URL="$1" local LOC_CSV="$2" local SPECIAL="$3" echo -e "\n* Comparing local and source:" echo -e "1. $PWD/$LOC_CSV" echo -e "2. $REF_URL" # Downloading TMP_CSV="$TMP_DIR"/`basename $REF_URL` wget $REF_URL -O $TMP_CSV -o /dev/null # Special process if [ "$SPECIAL" = "1" ]; then split_fcodes $TMP_CSV fi if [ ! -f "$LOC_CSV" ]; then echo -e "\n* $LOC_CSV does not exist!" touch "$LOC_CSV" fi # Computing diff view $LOC_CSV > $TMP_VIEW_1 view $TMP_CSV > $TMP_VIEW_2 DIFF=`diff -u $TMP_VIEW_1 $TMP_VIEW_2` if [ "$DIFF" = "" ]; then echo "* Nothing to do." rm -f $TMP_CSV return 0 fi echo -e "\n* Unified diff:" diff -u $TMP_VIEW_1 $TMP_VIEW_2 if [ "$FORCE" = "0" ]; then echo -n "Replace? [Y/N]: " read RESPONSE else RESPONSE="Y" fi if [ "$RESPONSE" = "Y" ]; then echo "You chose to replace." mv $TMP_CSV $LOC_CSV else echo "You chose not to replace." rm -f $TMP_CSV fi } # Files REF_URL_01='https://github.com/opentraveldata/optd/raw/trunk/refdata/ORI/ori_por_public.csv' REF_URL_02='https://github.com/opentraveldata/optd/raw/trunk/refdata/ORI/ori_por_non_iata.csv' REF_URL_03='http://redmine.orinet.nce.amadeus.net/projects/oripor/repository/revisions/trunk/raw/admin/ori_por.csv' REF_URL_04='https://github.com/opentraveldata/optd/raw/trunk/refdata/ORI/ori_airlines.csv' REF_URL_05='http://download.geonames.org/export/dump/countryInfo.txt' REF_URL_06='http://download.geonames.org/export/dump/timeZones.txt' REF_URL_07='http://download.geonames.org/export/dump/iso-languagecodes.txt' REF_URL_08='http://download.geonames.org/export/dump/featureCodes_en.txt' REF_URL_09='http://download.geonames.org/export/dump/cities15000.zip' REF_URL_10='http://download.geonames.org/export/dump/FR.zip' REF_URL_11='http://download.geonames.org/export/dump/MC.zip' REF_URL_12='http://download.geonames.org/export/zip/FR.zip' REF_URL_13='http://download.geonames.org/export/zip/MC.zip' LOC_CSV_01='Por/Ori/ori_por_public.csv' LOC_CSV_02='Por/Ori/ori_por_non_iata.csv' LOC_CSV_03='Por/Ori/ori_por.csv' LOC_CSV_04='Airlines/ori_airlines.csv' LOC_CSV_05='Countries/countryInfo.txt' LOC_CSV_06='TimeZones/timeZones.txt' LOC_CSV_07='Languages/iso-languagecodes.txt' LOC_CSV_08='FeatureCodes/featureCodes_en.txt' LOC_CSV_09='Cities/cities15000.zip' LOC_CSV_10='Por/GeoNames/FR.zip' LOC_CSV_11='Por/GeoNames/MC.zip' LOC_CSV_12='PostalCodes/GeoNames/FR.zip' LOC_CSV_13='PostalCodes/GeoNames/MC.zip' #do_a_file REF_URL LOC_CSV do_a_file "$REF_URL_04" "$LOC_CSV_04" do_a_file "$REF_URL_05" "$LOC_CSV_05" do_a_file "$REF_URL_06" "$LOC_CSV_06" do_a_file "$REF_URL_07" "$LOC_CSV_07" do_a_file "$REF_URL_08" "$LOC_CSV_08" 1 do_a_file "$REF_URL_09" "$LOC_CSV_09" do_a_file "$REF_URL_10" "$LOC_CSV_10" do_a_file "$REF_URL_11" "$LOC_CSV_11" do_a_file "$REF_URL_12" "$LOC_CSV_12" do_a_file "$REF_URL_13" "$LOC_CSV_13" # The longest at the end do_a_file "$REF_URL_03" "$LOC_CSV_03" do_a_file "$REF_URL_02" "$LOC_CSV_02" do_a_file "$REF_URL_01" "$LOC_CSV_01"
PypiClean
/Cubane-1.0.11.tar.gz/Cubane-1.0.11/cubane/ishop/views.py
from __future__ import unicode_literals from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseRedirect, HttpResponsePermanentRedirect from django.db.models import Q, Max, Min, Prefetch, Case, When from django.core.urlresolvers import reverse from django.contrib import messages from django.contrib.auth import login as auth_login, logout as auth_logout from django.contrib.auth import update_session_auth_hash from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from django.template.defaultfilters import slugify from cubane.backend.views import BackendSection from cubane.cms.views import get_cms_settings, CMSGenericSitemap from cubane.ishop import get_category_model, get_product_model, get_customer_model, get_order_model from cubane.ishop.models import ProductBase, ShopEntity, VarietyAssignment, FinanceOption, ProductCategory, RelatedProducts, OrderBase, DeliveryAddress from cubane.ishop.apps.merchant.orders.views import ProcessingOrderBackendSection, OrderBackendSection from cubane.ishop.apps.merchant.customers.views import CustomerBackendSection from cubane.ishop.apps.merchant.categories.views import CategoryBackendSection from cubane.ishop.apps.merchant.products.views import ProductBackendSection from cubane.ishop.apps.merchant.varieties.views import VarietyBackendSection from cubane.ishop.apps.merchant.varieties.views import VarietyOptionBackendSection from cubane.ishop.apps.merchant.delivery.views import DeliveryBackendSection from cubane.ishop.apps.merchant.vouchers.views import VoucherBackendSection from cubane.ishop.apps.merchant.inventory.views import InventoryBackendSection from cubane.ishop.apps.shop.account.forms import BillingAddressForm, DeliveryAddressForm, ChangePasswordForm, ChangeDetailsForm from cubane.ishop.apps.shop.forms import CustomerLoginForm, NewCustomerForm, SignupForm, PasswordForgottenForm, ProductOrderByForm from cubane.ishop.basket import Basket from cubane.ishop.templatetags.shop_tags import get_shop_price from cubane.enquiry.views import validate_captcha from cubane.lib.auth import login_user_without_password from cubane.lib.module import get_class_from_string from cubane.lib.parse import parse_int_list from cubane.lib.paginator import create_paginator from cubane.lib.fts import fts_query from cubane.lib.range import get_ranges_for_min_max from cubane.lib.libjson import to_json from cubane.lib.app import get_models from cubane.views import View, ModelView from mailsnake import MailSnake, ListNotSubscribedException, EmailNotExistsException, ListAlreadySubscribedException import math import collections import random import datetime import hashlib SHOP_CLASS = None def get_shop_content_backend_sections(backend_section): return [ CategoryBackendSection(), ProductBackendSection(), InventoryBackendSection(), VarietyBackendSection(), VarietyOptionBackendSection(), ] class ShopContentView(ModelView): """ Edit CMS entity. """ template_path = 'cubane/cms/pages/' def __init__(self, model, *args, **kwargs): self.model = model self.namespace = 'cubane.cms.%s' % \ slugify(model._meta.verbose_name_plural) super(ShopContentView, self).__init__(*args, **kwargs) def _get_objects(self, request): return self.model.objects.all() class ShopContentEntitySection(BackendSection): def __init__(self, model, group, *args, **kwargs): super(ShopContentEntitySection, self).__init__(*args, **kwargs) self.view = ShopContentView(model) self.title = model._meta.verbose_name_plural self.slug = slugify(self.title) self.group = group class ShopSalesBackendSection(BackendSection): """ Backend section for editing sales-related content, such as customer and orders. """ title = 'Sales' priority = 5 sections = [ ProcessingOrderBackendSection(), OrderBackendSection(), CustomerBackendSection(), ] class ShopBackendSection(BackendSection): """ Backend section for editing shop content, such as categories and products. """ title = 'Shop' sections = [ DeliveryBackendSection(), VoucherBackendSection(), ] def __init__(self, *args, **kwargs): super(ShopBackendSection, self).__init__(*args, **kwargs) # finance options if settings.SHOP_LOAN_ENABLED: from cubane.ishop.apps.merchant.finance.views import FinanceOptionBackendSection self.sections.append(FinanceOptionBackendSection()) # append all known shop entities entity_models = [] for model in get_models(): if issubclass(model, ShopEntity): entity_models.append(model) # sort by name entity_models = sorted(entity_models, key=lambda m: m.__name__) # create sections self.sections.extend([ShopContentEntitySection(model, model.get_backend_section_group()) for model in entity_models]) def get_shop(): """ Return the custom CMS implementation that is used to render CMS content. A site may implement its own CMS by deriving from the CMS base class. The custom class needs to be setup via settings.CMS, for example CMS = 'myproject.views.MyCMS'. """ global SHOP_CLASS if not SHOP_CLASS: if hasattr(settings, 'SHOP') and settings.SHOP: SHOP_CLASS = get_class_from_string(settings.SHOP) else: raise ValueError( "cubane.cms requires the settings variable 'SHOP' " + "to be set to the full path of the shop class that represents " + "the cms system (derived from cubane.ishop.views.Shop), " + "for example myproject.views.MyProjectShop" ) # creates a new instance every time... return SHOP_CLASS() class Shop(View): """ Shop base class. This may be overridden in order to hook custom things into the pipeline. """ @property def settings(self): """ Return the CMS/Shop settings object (cached). """ return get_cms_settings() def get_category_model(self): """ Return the model for a shop category. """ return get_category_model() def get_product_model(self): """ Return the model for a shop product. """ return get_product_model() def get_customer_model(self): """ Return the model for a shop customer. """ return get_customer_model() def get_products(self): """ Base queryset for returning products (listing). """ products = self.get_product_model().objects.select_related('image', 'category').filter(draft=False) # select related categories if settings.SHOP_MULTIPLE_CATEGORIES: products = products.prefetch_related( Prefetch('categories', queryset=ProductCategory.objects.select_related('category').order_by('seq')) ) # category must be enabled if settings.SHOP_MULTIPLE_CATEGORIES: # multiple categories -> at least one category must be enabled products = products.filter(categories__enabled=True).distinct() else: # single category -> category must be enabled products = products.filter(category__enabled=True) return products def get_related_products(self): """ Return a queryset on which basis related products are fetched. """ if settings.SHOP_MULTIPLE_CATEGORIES: return RelatedProducts.objects.select_related('to_product', 'to_product__image') else: return RelatedProducts.objects.select_related('to_product', 'to_product__image', 'to_product__category') def get_categories(self): """ Base queryset for returning all categories. """ return self.get_category_model().objects.filter(enabled=True) def search_products(self, q): """ Search for products based on given query q. """ products = self.get_products().filter(draft=False) if settings.SHOP_MULTIPLE_CATEGORIES: products = products.filter( categories__enabled=True ).exclude( categories=None ).distinct() else: products = products.filter( category_id__isnull=False, category__enabled=True ) return fts_query(products, 'fts_index', q) def get_payment_config(self, identifier): """ Return the payment configuration details. """ if hasattr(settings, 'SHOP_PAYMENT_CONFIG'): for config in settings.SHOP_PAYMENT_CONFIG: if config['payment_gateway'] == identifier: return config else: return {} def get_payment_gateway_by_identifier(self, identifier): """ Return the payment gateway based on the given identifier. """ # get payment config config = self.get_payment_config(identifier) # determine payment system or error if identifier == settings.GATEWAY_TEST: from cubane.payment.test_gateway import TestPaymentGateway return TestPaymentGateway(config, settings.GATEWAY_TEST) elif identifier == settings.GATEWAY_SAGEPAY: from cubane.payment.sagepay import SagepayPaymentGateway return SagepayPaymentGateway(config, settings.GATEWAY_SAGEPAY) elif identifier == settings.GATEWAY_PAYPAL: from cubane.payment.paypal import PaypalPaymentGateway return PaypalPaymentGateway(config, settings.GATEWAY_PAYPAL) elif identifier == settings.GATEWAY_OMNIPORT: from cubane.payment.omniport import OmniPortPaymentGateway return OmniPortPaymentGateway(config, settings.GATEWAY_OMNIPORT) elif identifier == settings.GATEWAY_STRIPE: from cubane.payment.stripe_gateway import StripePaymentGateway return StripePaymentGateway(config, settings.GATEWAY_STRIPE) elif identifier == settings.GATEWAY_DEKO: from cubane.payment.deko import DekoPaymentGateway return DekoPaymentGateway(config, settings.GATEWAY_DEKO) # TODO: Add payment gateways here raise ValueError( 'Unknown or unsupported payment gateway %s.' % ( identifier ) ) def get_default_payment_gateway(self): """ Return the default payment gateway. """ if settings.SHOP_TEST_MODE: return settings.GATEWAY_TEST else: return settings.SHOP_DEFAULT_PAYMENT_GATEWAY def get_payment_gateway_for_basket(self, basket): """ Return the payment gateway identifier of the payment gateway that shall be used for a new order that is created from the given basket. """ # pay by invoice does not have a payment gateway! if basket.is_invoice(): return None if settings.SHOP_TEST_MODE: return settings.GATEWAY_TEST if basket.finance_option and settings.SHOP_LOAN_ENABLED: return settings.SHOP_LOAN_PAYMENT_GATEWAY else: return settings.SHOP_DEFAULT_PAYMENT_GATEWAY def get_products_for_category(self, category): """ Return all products of the given category (including all products from any sub-category and sub-sub category etc). """ if settings.SHOP_MULTIPLE_CATEGORIES: # multiple categories per product return self.get_products().filter( Q(categories=category) | Q(categories__parent=category) | Q(categories__parent__parent=category) | Q(categories__parent__parent__parent=category) | Q(categories__parent__parent__parent__parent=category), draft=False ) else: # single category per product return self.get_products().filter( Q(category=category) | Q(category__parent=category) | Q(category__parent__parent=category) | Q(category__parent__parent__parent=category) | Q(category__parent__parent__parent__parent=category), draft=False ) def categories_with_products(self, categories): """ Filters out empty categories given a list of categories. """ # valid products products = get_product_model().objects.filter(draft=False) # filter out categories without products if settings.SHOP_MULTIPLE_CATEGORIES: # multiple categories per product product_categories = ProductCategory.objects.filter(product__in=products) return categories.filter( Q(pk__in=product_categories) | Q(siblings__pk__in=products) | Q(siblings__siblings__pk__in=products) | Q(siblings__siblings__siblings__pk__in=products) | Q(siblings__siblings__siblings__siblings__pk__in=products) ).distinct() else: # single category per product return categories.filter( Q(products__in=products) | Q(siblings__products__in=products) | Q(siblings__siblings__products__in=products) | Q(siblings__siblings__siblings__products__in=products) | Q(siblings__siblings__siblings__siblings__products__in=products) ).distinct() def get_varieties_for_products(self, request, products, current_options, min_max_price): """ Return all varieties that apply for the given set of products. """ # price filter comes first price_filter_options = self.get_price_filter_options(products) prices = self.get_price_filter(min_max_price, price_filter_options) varieties = collections.OrderedDict([('price', prices['price'])]) # append product varieties and attributes current = parse_int_list(current_options) varieties = VarietyAssignment.objects.get_variety_filters_for_products(products, current, varieties) return varieties def get_price_filter_options(self, products): """ Return list of options for price filtering. """ max_price = products.aggregate(Max('price')).get('price__max') min_price = products.aggregate(Min('price')).get('price__min') new_options = get_ranges_for_min_max((min_price, max_price), settings.SHOP_PRICE_FILTER_NUMBER_OF_DIVIDERS, settings.SHOP_PRICE_FILTER_DIVDERS) return new_options def get_price_filter(self, current_price_options, price_filter_options): """ Return a price filter that is used for the filter panel. """ price_filter = collections.OrderedDict() price_filter['price'] = { 'id': 'price', 'display_title': 'Price', 'checked': 0, 'options': [], 'arg': 'min_max_price' } # get options for price filtering for i, option in enumerate(price_filter_options): title = '%s - %s' % ( get_shop_price(option[0], decimal=False), get_shop_price(option[1], decimal=False) ) price_filter['price']['options'].append({ 'id': 'min_max_price_%s' % i, 'title': title, 'value': '-'.join(map(str, option)) }) # split current_price_options to check values against current_price_options = current_price_options.split(',') # determine which variety group has at least one option checked for v in price_filter['price']['options']: if v['value'] in current_price_options: v['checked'] = 1 else: v['checked'] = 0 return price_filter def get_current_variety_filter_url(self, varieties): """ Return current_variety_filter as url. """ args = {} for _, v in varieties.items(): for o in v.get('options'): if o.get('checked'): arg = v.get('arg') args.setdefault(arg, []) args[arg].append(unicode(o.get('id'))) return '&'.join(['%s=%s' % (arg, ','.join(options)) for arg, options in args.items()]) def get_default_order_by(self, request, category=None): """ Return the default order for a set of products, optionally for the given category. """ default_order_by = None if category is not None: default_order_by = category.ordering_default if default_order_by is None: default_order_by = request.settings.ordering_default return default_order_by def order_product_listing_by_relavance(self, request, products): """ Order given queryset of products based on relevance (seq). """ if settings.SHOP_MULTIPLE_CATEGORIES: # multiple categories per product pks = [x.get('id') for x in products.order_by( 'category_assignments__category__parent__parent__parent__parent__seq', 'category_assignments__category__parent__parent__parent__seq', 'category_assignments__category__parent__parent__seq', 'category_assignments__category__parent__seq', 'category_assignments__category__seq', 'category_assignments__seq', 'title' ).values('id')] preserved_order = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pks)]) products = products.order_by(preserved_order) else: # single category per product products = products.order_by( 'category__parent__parent__parent__parent__seq', 'category__parent__parent__parent__seq', 'category__parent__parent__seq', 'category__parent__seq', 'category__seq', 'seq', 'title' ) return products def order_product_listing(self, request, products, order_by): """ Order given queryset of products based on the given order criterium. """ if order_by == ProductBase.ORDER_BY_DATE_ADDED: products = products.order_by('-created_on') elif order_by == ProductBase.ORDER_BY_PRICE_HIGH_TO_LOW: products = products.order_by('-price') elif order_by == ProductBase.ORDER_BY_PRICE_LOW_TO_HIGH: products = products.order_by('price') elif order_by == ProductBase.ORDER_BY_RELEVANCE: products = self.order_product_listing_by_relavance(request, products) return products def product_listing(self, request, products, context={}, category=None, has_subcategories=False): """ Return a template context for presenting a list of products including filter varieties. """ # current page try: page_number = int(request.GET.get('page', '1')) except ValueError: page_number = 1 # varieties and variety filter (optional) if settings.SHOP_VARIETY_FILTER_ENABLED: products, varieties, has_variety_filtered, variety_filter, active_varieties = \ self.load_listing_varieties_and_filter(request, products) else: varieties = None has_variety_filtered = False variety_filter = None active_varieties = None # determine default order. If we are presenting a category with # sub-categories, we are looking at an aggregated result and order # by relevance would not work. default_order_by = self.get_default_order_by(request, category) # order by order_by = request.GET.get('o', default_order_by) if not order_by and not request.settings.ordering_default and request.settings.ordering_options: order_by = request.settings.ordering_options[0] # order products products = self.order_product_listing(request, products, order_by) # paginator products = create_paginator( request, products, page_size=request.settings.products_per_page, min_page_size=request.settings.products_per_page, max_page_size=request.settings.max_products_per_page ) # order by form order_by_form = ProductOrderByForm(initial={ 'sort_by': order_by }) order_by_form.configure(request, has_subcategories) # load varieties preview if settings.SHOP_LOAD_VARIETY_PREVIEW: has_variety_preview = self.load_variety_preview(products) else: has_variety_preview = False # update context context.update({ 'products': products, 'varieties': varieties, 'has_variety_preview': has_variety_preview, 'has_variety_filtered': has_variety_filtered, 'variety_filter': variety_filter, 'active_varieties': active_varieties, 'order_by_form': order_by_form, 'order_by': order_by, }) return context def load_variety_preview(self, products): """ Load variety preview information for the given products. """ if products.count() > 0: # load varieties for all products that are configured to be # previewed in listing... return VarietyAssignment.objects.inject_product_variety_preview( products.object_list ) else: return False def load_listing_varieties_and_filter(self, request, products): """ Load varieties and listing. """ varieties = None has_variety_filtered = 'v' in request.GET current_options = request.GET.get('v', '') min_max_price = request.GET.get('min_max_price', '') varieties = self.get_varieties_for_products(request, products, current_options, min_max_price) products = self.get_filtered_products(varieties, products) variety_filter = self.get_current_variety_filter_url(varieties) active_varieties = self.get_active_varieties(varieties, self.get_current_variety_filter(varieties)) return products, varieties, has_variety_filtered, variety_filter, active_varieties def get_filtered_products(self, varieties, products): """ Return products based on the given set of products and varieties, where the list of products is filtered according to given variety filter options. """ for vid, v in varieties.items(): q = Q() min_max_price_parts = [] for o in v.get('options'): if o.get('checked'): if v.get('arg') == 'min_max_price': for p in o.get('value').split('-'): min_max_price_parts.append(int(p)) elif v.get('arg') == 'v': q |= Q(varieties__id=o.get('value')) if len(min_max_price_parts) > 0: q &= Q(price__gte=min(min_max_price_parts)) q &= Q(price__lte=max(min_max_price_parts)) products = products.filter(q) return products def get_current_variety_filter(self, varieties): """ Return the current variety filter based on the given set of varieties. """ variety_filter = [] for _, v in varieties.items(): for o in v.get('options'): if o.get('checked'): variety_filter.append(unicode(o.get('id'))) return variety_filter def get_active_varieties(self, varieties, active_options): """ Return active varieties based on the given set of varieties. """ active_varieties = [] for _, v in varieties.items(): for o in v.get('options'): if o.get('checked'): active_varieties.append({ 'id': o.get('id'), 'group_title': v.get('display_title'), 'title': o.get('title'), }) return active_varieties def get_category_base(self, category_model): """ Return the base queryset for fetching categories based on the given model. """ return category_model.objects.select_related('parent') def get_category_by_pk(self, category_model, pk): """ Return category with given pk or throw exception. """ return self.get_category_base(category_model).get(enabled=True, pk=pk) def get_category_or_404(self, pk, slug): """ Return the shop category matching given slug/pk or raise 404. If the slug does not match, return a redirect response to the correct url. """ category_model = self.get_category_model() try: category = self.get_category_by_pk(category_model, pk) if category.slug != slug: return HttpResponsePermanentRedirect(reverse('shop.category', args=[category.slug, category.pk])) except category_model.DoesNotExist: raise Http404('Category matching id %s does not exist or category has been disabled.' % pk) return category def get_product_base(self, product_model): """ Return the base queryset for loading a product. """ return product_model.objects.all() def get_product_or_404(self, pk, slug): """ Return the shop product matching given slug/pk or raise 404. If the slug does not match, return a redirect response to the correct url. """ try: products = self.get_product_base(get_product_model()).filter(draft=False) if settings.SHOP_MULTIPLE_CATEGORIES: # multiple categories -> at least one category must be enabled products = products.filter(categories__enabled=True).prefetch_related( Prefetch('categories', queryset=ProductCategory.objects.select_related('category').order_by('seq')) ).distinct() else: # single category -> category must be enabled products = products.filter(category__enabled=True) product = products.get(pk=pk) if product.slug != slug: return HttpResponsePermanentRedirect(reverse('shop.product', args=[product.slug, product.pk])) except get_product_model().DoesNotExist: raise Http404('Product matching id %s does not exist or product is a draft.' % pk) # if not connected to category if settings.SHOP_MULTIPLE_CATEGORIES: if product.categories.count() == 0: raise Http404('Product has not been assigned to any category.') else: if not product.category: raise Http404('Product has not been assigned to a category.') return product def on_basket_context(self, request, basket, template_context): """ Allow for the basket context to be updated before rendering the basket. """ return template_context def on_basket_added(self, request, basket, product, variety_options, quantity): """ Called whenever a product has been added to the basket. """ pass def on_customer_login(self, request, basket, user): """ Called whenever a customer logged in (either as part of the checkout process or otherwise)... """ pass def on_customer_logout(self, request, basket): """ Called whenever a customer is logged out manually by clicking the logout button. """ pass def category_page(self, request, category): """ Category page. """ # get products matching category (or any sub-category) products = self.get_products_for_category(category).distinct() subcategories = self.categories_with_products( category.get_children_queryset().select_related('image').filter(enabled=True) ) if category.get_parent(): sibling_categories_query = category.get_parent().get_children_queryset() sibling_categories = self.categories_with_products(sibling_categories_query) else: sibling_categories = False return self.product_listing(request, products, { 'page': category, 'category': category, 'subcategories': subcategories, 'sibling_categories': sibling_categories, 'category_page': True }, category, subcategories.count() > 0) def product_page(self, request, product): """ Product page. """ finance_options = [] if settings.SHOP_LOAN_ENABLED: # get all finance_options for this product rates = FinanceOption.objects.filter(enabled=True).order_by('seq') per_product_finance_option_ids = [] for finance_option in product.finance_options.all(): per_product_finance_option_ids.append(finance_option.pk) # exclude not assigned finances rates = list(rates) for rate in rates: if rate.per_product: if rate.pk not in per_product_finance_option_ids: continue finance_options.append(rate) return { 'page': product, 'product': product, 'request_url': request.build_absolute_uri(), 'product_page': True, 'finance_options': finance_options } def search_page(self, request): """ Search Page. """ q = request.GET.get('q', '') q = q[:40] products = self.search_products(q) return self.product_listing(request, products, { 'search': True, 'q': q, 'meta_title': 'Search Result for %s' % q }) def get_variety_display_title(self, request, option_label, assignment): """ Construct variety drop down display title. """ price = assignment.price if price > 0: option_label = '%s (+%s)' % ( option_label, get_shop_price(price) ) return option_label def account_index(self, request): profile = get_customer_model().objects.get(user=request.user) orders = get_order_model().objects.get_processing_orders(user=request.user)[:3] try: address = request.user.delivery_addresses.all()[0] except IndexError: address = None return { 'account_section': True, 'profile': profile, 'orders': orders, 'address': address } def account_login(self, request): basket = Basket(request) checkout = request.GET.get('checkout', False) == '1' initial = { 'checkout': checkout } login_form = CustomerLoginForm(request=request, prefix='customer', initial=initial) guest_form = NewCustomerForm(prefix='guest', initial=initial) guest_form.configure(request) form = None if request.method == 'POST': if request.POST.get('password_forgotten', None) != None: login_form = PasswordForgottenForm(request.POST, prefix='customer') form = login_form elif request.POST.get('customer', None) != None: login_form = CustomerLoginForm(request.POST, request=request, prefix='customer') form = login_form else: guest_form = NewCustomerForm(request.POST, prefix='guest') guest_form.configure(request) form = guest_form if form != None and form.is_valid(): if isinstance(form, PasswordForgottenForm): email = form.cleaned_data.get('email') checkout = form.cleaned_data.get('checkout', '0') if request.context.password_forgotten(request, email): messages.success(request, 'Your new password has been sent to \'%s\'.' % email) else: messages.error(request, 'We were not able to recognise the email address \'%s\'. Please make sure that you entered your email address correctly.' % email) return HttpResponseRedirect(reverse('shop.account.login') + '?checkout=%s' % checkout) elif isinstance(form, CustomerLoginForm): user = form.get_user() checkout = form.cleaned_data.get('checkout', '0') if user.is_authenticated(): auth_login(request, user) if checkout: response = HttpResponseRedirect(reverse('shop.order.delivery')) else: response = HttpResponseRedirect(reverse('shop.account.index')) response.set_cookie('cubaneShopLogin', '1') # hook shop = get_shop() shop.on_customer_login(request, basket, user) return response else: checkout = form.cleaned_data.get('checkout', '0') if request.user.is_authenticated(): auth_logout(request) # hook shop = get_shop() shop.on_customer_logout(request, basket) basket.save() request.session[settings.SIGNUP_EMAIL_SESSION_VAR] = form.cleaned_data['email'] return HttpResponseRedirect(reverse('shop.account.signup') + '?checkout=%s' % checkout) request.session.set_test_cookie() return { 'account_section': True, 'login_form': login_form, 'guest_form': guest_form, } def account_orders(self, request, status): order_model = get_order_model() if status == 'processing': orders = order_model.objects.get_processing_orders(user=request.user) else: orders = order_model.objects.get_complete_orders(user=request.user) return { 'account_section': True, 'orders': orders, 'status': status, } def account_details(self, request): if request.method == 'POST': form = ChangeDetailsForm(request.POST) else: form = ChangeDetailsForm() form.configure(request) if form.is_valid(): data = form.cleaned_data u = request.user p = get_customer_model().objects.get(user=u) if request.settings.mailchimp_enabled: # subscription details ms = MailSnake(request.settings.mailchimp_api) person_name = [data.get('first_name'), data.get('last_name')] merge_vars = {'FNAME': ' '.join(person_name)} # unsubscribe if email changed or we no longer want to be subscribed if 'email_address' in form.changed_data or ('newsletter' in form.changed_data and not data.get('newsletter')): try: ms.listUnsubscribe(id=request.settings.mailchimp_list_id, email_address=u.email) except: pass # subscribe if newsletter subscription changed or email was changed if ('email_address' in form.changed_data or 'newsletter' in form.changed_data) and data.get('newsletter'): try: ms.listSubscribe(id=request.settings.mailchimp_list_id, email_address=data.get('email_address'), merge_vars=merge_vars) except: pass # update newletter state in profile p.newsletter = data.get('newsletter') # update personal details on user record u.first_name = data.get('first_name') u.last_name = data.get('last_name') u.email = data.get('email_address') u.save() # update personal details on profile record p.title = data.get('title') p.first_name = data.get('first_name') p.last_name = data.get('last_name') p.telephone = data.get('phone') p.email = data.get('email_address') p.save() # success message and redirect to dashboard messages.success(request, 'Your details have been changed.') return HttpResponseRedirect(reverse('shop.account.index')) return { 'account_section': True, 'form': form } def account_billing(self, request): if request.method == 'POST': form = BillingAddressForm(request.POST) else: form = BillingAddressForm() form.configure(request) if form.is_valid(): data = form.cleaned_data request.user.first_name = data.get('first_name') request.user.last_name = data.get('last_name') request.user.save() profile = get_customer_model().objects.get(user=request.user) profile.title = data.get('title') profile.company = data.get('company') profile.address1 = data.get('address1') profile.address2 = data.get('address2') profile.address3 = data.get('address3') profile.city = data.get('city') profile.county = data.get('county') profile.postcode = data.get('postcode') profile.country = data.get('country') profile.save() messages.success(request, 'Your delivery address has been changed.') return HttpResponseRedirect(reverse('shop.account.index')) return { 'account_section': True, 'form': form } def account_delivery(self, request): addresses = request.user.delivery_addresses.all() return { 'account_section': True, 'addresses': addresses } def account_delivery_address(self, request, pk=None): if pk: address = get_object_or_404(DeliveryAddress, pk=pk, user=request.user) initial = { 'name': address.name, 'company': address.company, 'address1': address.address1, 'address2': address.address2, 'address3': address.address3, 'city': address.city, 'county': address.county, 'postcode': address.postcode, 'country': address.country } else: address = DeliveryAddress() initial = {} if request.method == 'POST': form = DeliveryAddressForm(request.POST) else: form = DeliveryAddressForm(initial=initial) form.configure(request) if form.is_valid(): d = form.cleaned_data address.user = request.user address.name = d.get('name') address.title = d.get('title') address.company = d.get('company') address.address1 = d.get('address1') address.address2 = d.get('address2') address.address3 = d.get('address3') address.city = d.get('city') address.county = d.get('county') address.postcode = d.get('postcode') address.country = d.get('country') address.save() if pk: messages.success(request, 'Your delivery address has been changed.') else: messages.success(request, 'A new delivery address has been created.') return HttpResponseRedirect(reverse('shop.account.delivery')) return { 'account_section': True, 'form': form, 'address': address, 'edit': pk != None } def account_delete_delivery_address(self, request, pk): address = get_object_or_404(DeliveryAddress, pk=pk, user=request.user) title = unicode(address) address.delete() messages.success(request, "Your delivery address '%s' has been deleted." % title) return HttpResponseRedirect(reverse('shop.account.delivery')) def account_password(self, request): if request.method == 'POST': form = ChangePasswordForm(request.POST) else: form = ChangePasswordForm() form.configure(request) if form.is_valid(): request.user.set_password(form.cleaned_data.get('password')) request.user.save() update_session_auth_hash(request, request.user) messages.success(request, 'Your password has been changed.') return HttpResponseRedirect(reverse('shop.account.index')) return { 'account_section': True, 'form': form } def account_logout(self, request): basket = Basket(request) auth_logout(request) # hook shop = get_shop() shop.on_customer_logout(request, basket) basket.save() response = HttpResponseRedirect(reverse('shop.account.index')) response.set_cookie('cubaneShopLogin', '0') return response def get_account_signup_form(self): return SignupForm def account_signup(self, request): email = request.session.get(settings.SIGNUP_EMAIL_SESSION_VAR, None) if email == '': raise Http404('Missing email address.') checkout = request.GET.get('checkout', False) == '1' form_class = self.get_account_signup_form() if request.method == 'POST': form = form_class(request.POST, initial={'checkout': checkout}) else: form = form_class(initial={ 'email': email, 'checkout': checkout }) form.configure(request) if request.method == 'POST': captcha = validate_captcha(request) if not captcha: messages.add_message(request, messages.ERROR, 'Please tick the checkbox at the bottom of the form to prevent SPAM.' ) if form.is_valid() and captcha: d = form.cleaned_data # create user account md5 = hashlib.md5() md5.update(d['email']) user = User.objects.create( username = md5.hexdigest()[:30], first_name = d['first_name'], last_name = d['last_name'], email = d['email'] ) # replace username with user id, set password and add user to list of customers user.username = unicode(user.id) user.set_password(d['password']) user.save() # create customer newsletter = 0 if request.settings.mailchimp_enabled: if d['newsletter']: person_name = (d['first_name'],d['last_name']) merge_vars = {'FNAME': " ".join(person_name)} ms = MailSnake(request.settings.mailchimp_api) try: ms.listSubscribe(id=request.settings.mailchimp_list_id, email_address=d['email'], merge_vars=merge_vars) except: pass newsletter = d['newsletter'] customer = get_customer_model().objects.create( user=user, first_name = d['first_name'], last_name = d['last_name'], email=d['email'], title=d['title'], address1='', city='', county='', postcode='', country=d['country'], telephone='', newsletter=newsletter ) # log customer in login_user_without_password(request, user) # go to dashboard or deliver page messages.success(request, 'Thank you for signing up with us.') if d['checkout']: response = HttpResponseRedirect(reverse('shop.order.delivery')) else: response = HttpResponseRedirect(reverse('shop.account.index')) response.set_cookie('cubaneShopLogin', '1') return response return { 'account_section': True, 'is_signup_page': True, 'form': form } class ShopCategoriesSitemap(CMSGenericSitemap): """ Shop category pages sitemap. """ def items(self): return get_category_model().objects.exclude(enabled=False) class ShopProductsSitemap(CMSGenericSitemap): """ Shop product pages sitemap. """ def items(self): return get_product_model().objects.exclude(category__enabled=False).exclude(draft=True).exclude(category_id__isnull=True) class CMSExtensions(object): """ Extends the CMS class with shop-specific operations and extending other aspects, such as sitemaps. """ def get_sitemaps(self): """ Add shop-specific content to sitemap. """ _sitemaps = super(CMSExtensions, self).get_sitemaps() # shop categories and products _sitemaps[slugify(get_category_model()._meta.verbose_name)] = ShopCategoriesSitemap(self) _sitemaps[slugify(get_product_model()._meta.verbose_name)] = ShopProductsSitemap(self) return _sitemaps def on_generate_cache(self, generator, verbose=False): """ Override: Add shop content to cache system. """ super(CMSExtensions, self).on_generate_cache(generator, verbose) shop = get_shop() for category in shop.get_categories(): if generator.quit: break generator.process_page_by_url('shop.category', args=[category.slug, category.pk], verbose=verbose) for product in shop.get_products(): if generator.quit: break generator.process_page_by_url('shop.product', args=[product.slug, product.pk], verbose=verbose) def on_object_links(self, links): """ Override: Support for link-able categories and products. """ shop = get_shop() links.add(get_category_model(), shop.get_categories()) links.add(get_product_model(), shop.get_products())
PypiClean
/HavNegpy-1.2.tar.gz/HavNegpy-1.2/docs/_build/html/_build/doctrees/nbsphinx/hn_module_tutorial.ipynb
# Tutorial for the HN module of HavNegpy package ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import os import HavNegpy as dd %matplotlib qt os.chdir(r'M:\Marshall_Data\mohamed_data\mohamed_data\n44') def create_dataframe(f): col_names = ['Freq', 'T', 'Eps1', 'Eps2'] #f = input(str("Enter the filename:")) df = pd.read_csv(f, sep=r"\s+",index_col=False,usecols = [0,1,2,3],names=col_names,header=None,skiprows=4,encoding='unicode_escape',engine='python') col1 = ['log f'] for start in range(0, len(df), 63): name = df['T'][start] #print(name) col1.append(name) df2 = pd.DataFrame() f1 = df['Freq'][0:63].values x1 = np.log10((f1)) e = pd.DataFrame(x1) df2['log f'] = pd.concat([e],axis=1,ignore_index=True) global Cooling,Heating for start in range(0, len(df), 63): f = df['Eps2'][start:start+63].values ep = np.log10(f) d = pd.DataFrame(ep) df2[start] = pd.concat([d],axis=1,ignore_index=True) df2.columns = col1 ''' a = int(len(col1)/3) b = 2*a c = int(len(col1)) - b Heating1 = df2.iloc[8:,0:a+1] Cooling = df2.iloc[8:,a+1:b+1] Heating2 = df2.iloc[8:,b+1:] heat1_col = col1[0:a+1] cool_col = col1[a+1:b+1] heat2_col = col1[b+1:] Cooling.columns = cool_col Heating1.columns = heat1_col Heating2.columns = heat2_col f2 = df['Freq'][8:59].values x2 = np.log10((f2)) Cooling['Freq'] = x2 Heating1['Freq'] = x2 Heating2['Freq'] = x2 ''' Cooling = df2.iloc[:,0:25] Heating = df2.iloc[:,25:] return df,df2,Cooling,Heating #Heating2 df,df2,cool,heat = create_dataframe('EPS.TXT') x,y = df2['log f'][9:], heat[40][9:] plt.figure() plt.scatter(x,y,label='data for fitting') plt.xlabel('log f [Hz]') plt.ylabel('log $\epsilon$"') plt.legend() plt.title('Example for HN fitting') ``` image of the plot we are using in this tutorial ![diel_loss_plot.png](attachment:diel_loss_plot.png) ``` ''' instantiate the HN module from HavgNegpy''' hn = dd.HN() ''' select range to perform hn fitting''' ''' the select range functions pops in a separate window and allows you two clicks to select the region of interest (ROI)''' ''' In this tutorial, I'll plot the ROI and append as an image in the next cell''' x1,y1 = hn.select_range(x,y) ''' view the data from select range''' plt.scatter(x1,y1,label = 'Data for fitting') plt.xlabel('log f [Hz]') plt.ylabel('log $\epsilon$"') plt.legend() plt.title('ROI selected from HN module') ``` image of the ROI from HN module![ROI.png](attachment:ROI.png) ``` ''' dump the initial guess parameters using dump parameters method (varies for each fn), which dumps the parameters in a json file''' ''' this is required before performing the first fitting as it takes the initial guess from the json file created''' hn.dump_parameters_hn() ''' view the initial guess for the ROI using initial_view method''' ''' I'll append the image in the next cell''' hn.initial_view_hn(x1,y1) ``` image of the initial guess![initial_guess.png](attachment:initial_guess.png) ``` ''' pefrorm least squares fitting''' ''' The image of the curve fit is added in the next cell ''' hn.fit(x1,y1) ``` Example of the fit performed using single HN function the procedure is similar for double HN and HN with conductivity ![fit_example.png](attachment:fit_example.png) ``` '''create a file to save fit results using create_analysis file method''' ''' before saving fit results an analysis file has to be created ''' hn.create_analysis_file() ''' save the fit results using save_fit method of the corresponding fit function''' ''' takes one argument, read more on the documentation''' hn.save_fit_hn(1) ```
PypiClean
/Flask-Cache2-0.13.1.tar.gz/Flask-Cache2-0.13.1/flask_cache/__init__.py
__version__ = '0.13' __versionfull__ = __version__ import base64 import functools import hashlib import inspect import logging import string import uuid import warnings from werkzeug import import_string from flask import request, current_app from ._compat import PY2 logger = logging.getLogger(__name__) TEMPLATE_FRAGMENT_KEY_TEMPLATE = '_template_fragment_cache_%s%s' # Used to remove control characters and whitespace from cache keys. valid_chars = set(string.ascii_letters + string.digits + '_.') delchars = ''.join(c for c in map(chr, range(256)) if c not in valid_chars) if PY2: null_control = (None, delchars) else: null_control = (dict((k,None) for k in delchars),) def function_namespace(f, args=None): """ Attempts to returns unique namespace for function """ m_args = inspect.getargspec(f)[0] instance_token = None instance_self = getattr(f, '__self__', None) if instance_self \ and not inspect.isclass(instance_self): instance_token = repr(f.__self__) elif m_args \ and m_args[0] == 'self' \ and args: instance_token = repr(args[0]) module = f.__module__ if hasattr(f, '__qualname__'): name = f.__qualname__ else: klass = getattr(f, '__self__', None) if klass \ and not inspect.isclass(klass): klass = klass.__class__ if not klass: klass = getattr(f, 'im_class', None) if not klass: if m_args and args: if m_args[0] == 'self': klass = args[0].__class__ elif m_args[0] == 'cls': klass = args[0] if klass: name = klass.__name__ + '.' + f.__name__ else: name = f.__name__ ns = '.'.join((module, name)) ns = ns.translate(*null_control) if instance_token: ins = '.'.join((module, name, instance_token)) ins = ins.translate(*null_control) else: ins = None return ns, ins def make_template_fragment_key(fragment_name, vary_on=[]): """ Make a cache key for a specific fragment name """ if vary_on: fragment_name = "%s_" % fragment_name return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, "_".join(vary_on)) #: Cache Object ################ class Cache(object): """ This class is used to control the cache objects. """ def __init__(self, app=None, with_jinja2_ext=True, config=None): if not (config is None or isinstance(config, dict)): raise ValueError("`config` must be an instance of dict or None") self.with_jinja2_ext = with_jinja2_ext self.config = config self.app = app if app is not None: self.init_app(app, config) def init_app(self, app, config=None): "This is used to initialize cache with your app object" if not (config is None or isinstance(config, dict)): raise ValueError("`config` must be an instance of dict or None") #: Ref PR #44. #: Do not set self.app in the case a single instance of the Cache #: object is being used for multiple app instances. #: Example use case would be Cache shipped as part of a blueprint #: or utility library. base_config = app.config.copy() if self.config: base_config.update(self.config) if config: base_config.update(config) config = base_config config.setdefault('CACHE_DEFAULT_TIMEOUT', 300) config.setdefault('CACHE_THRESHOLD', 500) config.setdefault('CACHE_KEY_PREFIX', 'flask_cache_') config.setdefault('CACHE_MEMCACHED_SERVERS', None) config.setdefault('CACHE_DIR', None) config.setdefault('CACHE_OPTIONS', None) config.setdefault('CACHE_ARGS', []) config.setdefault('CACHE_TYPE', 'null') config.setdefault('CACHE_NO_NULL_WARNING', False) if config['CACHE_TYPE'] == 'null' and not config['CACHE_NO_NULL_WARNING']: warnings.warn("Flask-Cache: CACHE_TYPE is set to null, " "caching is effectively disabled.") if self.with_jinja2_ext: from .jinja2ext import CacheExtension, JINJA_CACHE_ATTR_NAME setattr(app.jinja_env, JINJA_CACHE_ATTR_NAME, self) app.jinja_env.add_extension(CacheExtension) self._set_cache(app, config) def _set_cache(self, app, config): import_me = config['CACHE_TYPE'] if '.' not in import_me: from . import backends try: cache_obj = getattr(backends, import_me) except AttributeError: raise ImportError("%s is not a valid FlaskCache backend" % ( import_me)) else: cache_obj = import_string(import_me) cache_args = config['CACHE_ARGS'][:] cache_options = {'default_timeout': config['CACHE_DEFAULT_TIMEOUT']} if config['CACHE_OPTIONS']: cache_options.update(config['CACHE_OPTIONS']) if not hasattr(app, 'extensions'): app.extensions = {} app.extensions.setdefault('cache', {}) app.extensions['cache'][self] = cache_obj( app, config, cache_args, cache_options) @property def cache(self): app = self.app or current_app return app.extensions['cache'][self] def get(self, *args, **kwargs): "Proxy function for internal cache object." return self.cache.get(*args, **kwargs) def set(self, *args, **kwargs): "Proxy function for internal cache object." self.cache.set(*args, **kwargs) def add(self, *args, **kwargs): "Proxy function for internal cache object." self.cache.add(*args, **kwargs) def delete(self, *args, **kwargs): "Proxy function for internal cache object." self.cache.delete(*args, **kwargs) def delete_many(self, *args, **kwargs): "Proxy function for internal cache object." self.cache.delete_many(*args, **kwargs) def clear(self): "Proxy function for internal cache object." self.cache.clear() def get_many(self, *args, **kwargs): "Proxy function for internal cache object." return self.cache.get_many(*args, **kwargs) def set_many(self, *args, **kwargs): "Proxy function for internal cache object." self.cache.set_many(*args, **kwargs) def cached(self, timeout=None, key_prefix='view/%s', unless=None): """ Decorator. Use this to cache a function. By default the cache key is `view/request.path`. You are able to use this decorator with any function by changing the `key_prefix`. If the token `%s` is located within the `key_prefix` then it will replace that with `request.path` Example:: # An example view function @cache.cached(timeout=50) def big_foo(): return big_bar_calc() # An example misc function to cache. @cache.cached(key_prefix='MyCachedList') def get_list(): return [random.randrange(0, 1) for i in range(50000)] my_list = get_list() .. note:: You MUST have a request context to actually called any functions that are cached. .. versionadded:: 0.4 The returned decorated function now has three function attributes assigned to it. These attributes are readable/writable. **uncached** The original undecorated function **cache_timeout** The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called. **make_cache_key** A function used in generating the cache_key used. :param timeout: Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds. :param key_prefix: Default 'view/%(request.path)s'. Beginning key to . use for the cache key. .. versionadded:: 0.3.4 Can optionally be a callable which takes no arguments but returns a string that will be used as the cache_key. :param unless: Default None. Cache will *always* execute the caching facilities unless this callable is true. This will bypass the caching entirely. """ def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): #: Bypass the cache entirely. if callable(unless) and unless() is True: return f(*args, **kwargs) try: cache_key = decorated_function.make_cache_key(*args, **kwargs) rv = self.cache.get(cache_key) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.") return f(*args, **kwargs) if rv is None: rv = f(*args, **kwargs) try: self.cache.set(cache_key, rv, timeout=decorated_function.cache_timeout) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.") return f(*args, **kwargs) return rv def make_cache_key(*args, **kwargs): if callable(key_prefix): cache_key = key_prefix() elif '%s' in key_prefix: cache_key = key_prefix % request.path else: cache_key = key_prefix return cache_key decorated_function.uncached = f decorated_function.cache_timeout = timeout decorated_function.make_cache_key = make_cache_key return decorated_function return decorator def _memvname(self, funcname): return funcname + '_memver' def _memoize_make_version_hash(self): return base64.b64encode(uuid.uuid4().bytes)[:6].decode('utf-8') def _memoize_version(self, f, args=None, reset=False, delete=False, timeout=None): """ Updates the hash version associated with a memoized function or method. """ fname, instance_fname = function_namespace(f, args=args) version_key = self._memvname(fname) fetch_keys = [version_key] if instance_fname: instance_version_key = self._memvname(instance_fname) fetch_keys.append(instance_version_key) # Only delete the per-instance version key or per-function version # key but not both. if delete: self.cache.delete_many(fetch_keys[-1]) return fname, None version_data_list = list(self.cache.get_many(*fetch_keys)) dirty = False if version_data_list[0] is None: version_data_list[0] = self._memoize_make_version_hash() dirty = True if instance_fname and version_data_list[1] is None: version_data_list[1] = self._memoize_make_version_hash() dirty = True # Only reset the per-instance version or the per-function version # but not both. if reset: fetch_keys = fetch_keys[-1:] version_data_list = [self._memoize_make_version_hash()] dirty = True if dirty: self.cache.set_many(dict(zip(fetch_keys, version_data_list)), timeout=timeout) return fname, ''.join(version_data_list) def _memoize_make_cache_key(self, make_name=None, timeout=None): """ Function used to create the cache_key for memoized functions. """ def make_cache_key(f, *args, **kwargs): _timeout = getattr(timeout, 'cache_timeout', timeout) fname, version_data = self._memoize_version(f, args=args, timeout=_timeout) #: this should have to be after version_data, so that it #: does not break the delete_memoized functionality. if callable(make_name): altfname = make_name(fname) else: altfname = fname if callable(f): keyargs, keykwargs = self._memoize_kwargs_to_args(f, *args, **kwargs) else: keyargs, keykwargs = args, kwargs try: updated = "{0}{1}{2}".format(altfname, keyargs, keykwargs) except AttributeError: updated = "%s%s%s" % (altfname, keyargs, keykwargs) cache_key = hashlib.md5() cache_key.update(updated.encode('utf-8')) cache_key = base64.b64encode(cache_key.digest())[:16] cache_key = cache_key.decode('utf-8') cache_key += version_data return cache_key return make_cache_key def _memoize_kwargs_to_args(self, f, *args, **kwargs): #: Inspect the arguments to the function #: This allows the memoization to be the same #: whether the function was called with #: 1, b=2 is equivilant to a=1, b=2, etc. new_args = [] arg_num = 0 argspec = inspect.getargspec(f) args_len = len(argspec.args) for i in range(args_len): if i == 0 and argspec.args[i] in ('self', 'cls'): #: use the repr of the class instance #: this supports instance methods for #: the memoized functions, giving more #: flexibility to developers arg = repr(args[0]) arg_num += 1 elif argspec.args[i] in kwargs: arg = kwargs[argspec.args[i]] elif arg_num < len(args): arg = args[arg_num] arg_num += 1 elif abs(i-args_len) <= len(argspec.defaults): arg = argspec.defaults[i-args_len] arg_num += 1 else: arg = None arg_num += 1 #: Attempt to convert all arguments to a #: hash/id or a representation? #: Not sure if this is necessary, since #: using objects as keys gets tricky quickly. # if hasattr(arg, '__class__'): # try: # arg = hash(arg) # except: # arg = repr(arg) #: Or what about a special __cacherepr__ function #: on an object, this allows objects to act normal #: upon inspection, yet they can define a representation #: that can be used to make the object unique in the #: cache key. Given that a case comes across that #: an object "must" be used as a cache key # if hasattr(arg, '__cacherepr__'): # arg = arg.__cacherepr__ new_args.append(arg) return tuple(new_args), {} def memoize(self, timeout=None, make_name=None, unless=None): """ Use this to cache the result of a function, taking its arguments into account in the cache key. Information on `Memoization <http://en.wikipedia.org/wiki/Memoization>`_. Example:: @cache.memoize(timeout=50) def big_foo(a, b): return a + b + random.randrange(0, 1000) .. code-block:: pycon >>> big_foo(5, 2) 753 >>> big_foo(5, 3) 234 >>> big_foo(5, 2) 753 .. versionadded:: 0.4 The returned decorated function now has three function attributes assigned to it. **uncached** The original undecorated function. readable only **cache_timeout** The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called. readable and writable **make_cache_key** A function used in generating the cache_key used. readable and writable :param timeout: Default None. If set to an integer, will cache for that amount of time. Unit of time is in seconds. :param make_name: Default None. If set this is a function that accepts a single argument, the function name, and returns a new string to be used as the function name. If not set then the function name is used. :param unless: Default None. Cache will *always* execute the caching facilities unelss this callable is true. This will bypass the caching entirely. .. versionadded:: 0.5 params ``make_name``, ``unless`` """ def memoize(f): @functools.wraps(f) def decorated_function(*args, **kwargs): #: bypass cache if callable(unless) and unless() is True: return f(*args, **kwargs) try: cache_key = decorated_function.make_cache_key(f, *args, **kwargs) rv = self.cache.get(cache_key) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.") return f(*args, **kwargs) if rv is None: rv = f(*args, **kwargs) try: self.cache.set(cache_key, rv, timeout=decorated_function.cache_timeout) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.") return rv decorated_function.uncached = f decorated_function.cache_timeout = timeout decorated_function.make_cache_key = self._memoize_make_cache_key( make_name, decorated_function) decorated_function.delete_memoized = lambda: self.delete_memoized(f) return decorated_function return memoize def delete_memoized(self, f, *args, **kwargs): """ Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten. Example:: @cache.memoize(50) def random_func(): return random.randrange(1, 50) @cache.memoize() def param_func(a, b): return a+b+random.randrange(1, 50) .. code-block:: pycon >>> random_func() 43 >>> random_func() 43 >>> cache.delete_memoized('random_func') >>> random_func() 16 >>> param_func(1, 2) 32 >>> param_func(1, 2) 32 >>> param_func(2, 2) 47 >>> cache.delete_memoized('param_func', 1, 2) >>> param_func(1, 2) 13 >>> param_func(2, 2) 47 Delete memoized is also smart about instance methods vs class methods. When passing a instancemethod, it will only clear the cache related to that instance of that object. (object uniqueness can be overridden by defining the __repr__ method, such as user id). When passing a classmethod, it will clear all caches related across all instances of that class. Example:: class Adder(object): @cache.memoize() def add(self, b): return b + random.random() .. code-block:: pycon >>> adder1 = Adder() >>> adder2 = Adder() >>> adder1.add(3) 3.23214234 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(adder.add) >>> adder1.add(3) 3.01348673 >>> adder2.add(3) 3.60898509 >>> cache.delete_memoized(Adder.add) >>> adder1.add(3) 3.53235667 >>> adder2.add(3) 3.72341788 :param fname: Name of the memoized function, or a reference to the function. :param \*args: A list of positional parameters used with memoized function. :param \**kwargs: A dict of named parameters used with memoized function. .. note:: Flask-Cache uses inspect to order kwargs into positional args when the function is memoized. If you pass a function reference into ``fname`` instead of the function name, Flask-Cache will be able to place the args/kwargs in the proper order, and delete the positional cache. However, if ``delete_memoized`` is just called with the name of the function, be sure to pass in potential arguments in the same order as defined in your function as args only, otherwise Flask-Cache will not be able to compute the same cache key. .. note:: Flask-Cache maintains an internal random version hash for the function. Using delete_memoized will only swap out the version hash, causing the memoize function to recompute results and put them into another key. This leaves any computed caches for this memoized function within the caching backend. It is recommended to use a very high timeout with memoize if using this function, so that when the version has is swapped, the old cached results would eventually be reclaimed by the caching backend. """ if not callable(f): raise DeprecationWarning("Deleting messages by relative name is no longer" " reliable, please switch to a function reference") try: if not args and not kwargs: self._memoize_version(f, reset=True) else: cache_key = f.make_cache_key(f.uncached, *args, **kwargs) self.cache.delete(cache_key) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.") def delete_memoized_verhash(self, f, *args): """ Delete the version hash associated with the function. ..warning:: Performing this operation could leave keys behind that have been created with this version hash. It is up to the application to make sure that all keys that may have been created with this version hash at least have timeouts so they will not sit orphaned in the cache backend. """ if not callable(f): raise DeprecationWarning("Deleting messages by relative name is no longer" " reliable, please use a function reference") try: self._memoize_version(f, delete=True) except Exception: if current_app.debug: raise logger.exception("Exception possibly due to cache backend.")
PypiClean
/MergePythonSDK.ticketing-2.2.2-py3-none-any.whl/MergePythonSDK.ticketing-2.2.2.dist-info/LICENSE.md
_Last updated: April 21, 2022_ **Merge SDK &amp; Code Snippets License** Merge makes available to Customers various software development kits (&quot;**SDKs**&quot;) and code snippets (&quot;**Snippets**&quot;) (together, the &quot;**Merge Assets**&quot;) to assist with Merge Integrations and making connections to their Customer Application. Merge Assets are deemed Software under the MSA (defined below). All terms applicable to Software under the MSA apply with equal force and effect to the Merge Assets under this Merge SDK and Code Snippets License (&quot;**License**&quot;). &quot;**Customer**&quot; means a person or entity that uses any of the Merge Assets. By using any Merge Asset, Customer agrees to the terms of this License. &quot;**MSA**&quot; for the purpose of this License means: (a) for Merge &quot;Launch&quot; Customers, the Subscriber Agreement (available at: [https://merge.dev/subscriber-agreement](https://merge.dev/subscriber-agreement)); and (b) for Merge &quot;Growth&quot; and/or &quot;Expand&quot; Customers, Merge&#39;s Master Services Agreement (available at [https://merge.dev/msa](https://merge.dev/msa)), unless Merge and Customer have entered into a separate written agreement governing the Customer&#39;s use of the Service. Customer&#39;s use of any Merge Asset will be governed by the applicable MSA as well as the additional terms of this License. Capitalized terms used but not defined herein shall have the meaning as set forth in the MSA. In the event of any inconsistency between the terms of the MSA and this License, the terms of the MSA will prevail. Merge reserves the right to modify or update this License in its sole discretion, the effective date of such updates and/or modifications will be the earlier of: (i) 30 days from the date of such update or modification; or (ii) Customer&#39;s continued use of any Merge Asset. 1. **SDK and Snippets License**. Customer&#39;s right to access and use the Service under Section 1 of the MSA is extended to include use of the Merge Assets but solely during the Term and subject to the terms of the MSA. 2. **Use with the Service Only**. Customer may use the Merge Assets but only in connections with the Service and Merge Integrations. Any other use of the Merge Assets requires Merge&#39;s prior written consent. 3. **Limitations**. Customer&#39;s use of the Merge Assets may be subject to bandwidth limitations that Merge may impose from time to time during the Subscription. Merge will make commercially reasonable efforts to notify Customer of such limitations in advance via the location where Customer gained access to the applicable Merge Asset(s). 4. **Merge Assets &amp; Intellectual Property Rights**. Any modifications or derivatives (together, &quot;**Asset Derivatives**&quot;) made by Customer to the Merge Assets are deemed &quot;works made for hire&quot; as that term is defined in the United States Copyright Act and are the sole property of Merge. To the extent that ownership of any Asset Derivative does not by operation of law vest in Merge, Customer hereby assigns to Merge all right, title and interest in and to the Asset Derivative, including all related intellectual property rights. Asset Derivatives will be governed by the terms of this License.
PypiClean
/HDDM-0.9.9.tar.gz/HDDM-0.9.9/hddm/models/hddm_transformed.py
from collections import OrderedDict import inspect import pymc as pm import kabuki.step_methods as steps from hddm.models import HDDMBase class HDDMTransformed(HDDMBase): # AF-comment: Don't understand the purpose of this class ! def __init__(self, *args, **kwargs): self.use_gibbs_for_mean = kwargs.pop("use_gibbs_for_mean", True) self.use_reject_for_std = kwargs.pop("use_reject_for_std", True) if hasattr(self, "nn"): pass else: self.nn = False super(HDDMTransformed, self).__init__(*args, **kwargs) def pre_sample(self): if not self.is_group_model: return # apply gibbs sampler to normal group nodes for name, node_descr in self.iter_group_nodes(): node = node_descr["node"] knode_name = node_descr["knode_name"].replace("_trans", "") if ( self.use_gibbs_for_mean and isinstance(node, pm.Normal) and knode_name not in self.group_only_nodes ): self.mc.use_step_method(steps.kNormalNormal, node) if ( self.use_reject_for_std and isinstance(node, pm.Uniform) and knode_name not in self.group_only_nodes ): self.mc.use_step_method(steps.UniformPriorNormalstd, node) def _create_stochastic_knodes(self, include): knodes = OrderedDict() if "a" in include: knodes.update(self._create_family_exp("a", value=1)) if "v" in include: knodes.update(self._create_family_normal("v", value=0)) if "t" in include: knodes.update(self._create_family_exp("t", value=0.01)) if "sv" in include: # TW: Use kabuki.utils.HalfCauchy, S=10, value=1 instead? knodes.update( self._create_family_trunc_normal("sv", lower=0, upper=1e3, value=1) ) # knodes.update(self._create_family_exp('sv', value=1)) if "sz" in include: knodes.update(self._create_family_invlogit("sz", value=0.1)) if "st" in include: knodes.update(self._create_family_exp("st", value=0.01)) if "z" in include: knodes.update(self._create_family_invlogit("z", value=0.5)) if "p_outlier" in include: knodes.update(self._create_family_invlogit("p_outlier", value=0.05)) return knodes def _create_an_average_model(self): """ create an average model for group model quantiles optimization. """ # this code only check that the arguments are as expected, i.e. the constructor was not change # since we wrote this function super_init_function = super(self.__class__, self).__init__ init_args = set(inspect.getargspec(super_init_function).args) known_args = set(["wiener_params", "include", "self", "bias", "data"]) assert ( known_args == init_args ), "Arguments of the constructor are not as expected" # create the avg model avg_model = self.__class__( self.data, include=self.include, is_group_model=False, **self._kwargs ) return avg_model
PypiClean
/Kook-0.7.2.tar.gz/Kook-0.7.2/lib/kook/books/concatenate.py
### ### $Release: 0.7.2 $ ### $Copyright: copyright(c) 2008-2012 kuwata-lab.com all rights reserved. $ ### $License: MIT License $ ### ### ### 'concatenate' recipe which concatenates cookbook and pyKook libraries into a file. ### ### Using 'concatenate' recipe, your cookbook can be a stand-alone script ### and user doesn't need to install pyKook. ### ### Example (Kookbook.py):: ### ### ## load cookbook ### ## ('@kook' is equivarent to 'os.path.dirname(kook.__file__)') ### kookbook.load("@kook/books/concatenate.py") ### #CONCATENATE_MODULES.append(foo.bar.module) # if you want ### #CONCATENATE_BOOKS.append('foo/bar/book.py') # if you want ### ### Example (command-line):: ### ### bash> kk concatenate -o script.rb Kookbook.py ### bash> python script.rb -h ### import kook import kook.utils import kook.config import kook.misc import kook.commands import kook.decorators import kook.cookbook import kook.kitchen import kook.main from kook.utils import resolve_filepath CONCATENATE_MODULES = [ kook, kook.utils, kook.config, kook.misc, kook.commands, kook.decorators, kook.cookbook, kook.kitchen, kook.main, ] CONCATENATE_BOOKS = [ 'kook/books/clean.py', 'kook/books/all.py', 'kook/books/concatenate.py', ] __export__ = ('CONCATENATE_MODULES', 'CONCATENATE_BOOKS') def _escape(content): s = "'''" return content.replace("'''", '%s + "%s" + r%s' % (s, s, s)) @recipe @spices("-o outfile: output filename", "[bookname..]") def concatenate(c, *args, **kwargs): """concatenate cookbook and library files into a file""" pairs = [ (mod.__name__, mod.__file__.replace('.pyc', '.py')) for mod in CONCATENATE_MODULES ] buf = []; add = buf.append add(r'''#!/usr/bin/env python ### ### concatenated pykook ### ''') if args: add("_BOOK_CONTENT = r'''") for fname in args: s = read_file(fname) add(_escape(s)) add("\n") add("'''\n") add("\n") add("\n") add("import sys\n") add("\n") for name, fpath in pairs: s = read_file(fpath) add("#" * 20 + " " + fpath + "\n") add("\n") add("%s = type(sys)('%s')\n" % (name, name)) add("exec(compile(r'''"); add(_escape(s)); add("''', '%s', 'exec'), %s.__dict__, %s.__dict__)\n" % (name, name, name)) add("sys.modules['%s'] = %s\n" % (name, name)) add("\n") for bookname in CONCATENATE_BOOKS: fpath = resolve_filepath(bookname) s = read_file(fpath) add("#" * 20 + " " + fpath + "\n") add("\n") add("kook.__dict__.setdefault('_BOOK_LIBRARY', {})\n") add("kook._BOOK_LIBRARY['%s'] = r'''" % bookname) add(_escape(s)) add("'''\n") add("#" * 70 + "\n") if args: add("\n") add("kook._BOOK_CONTENT = _BOOK_CONTENT\n") add("\n") add(r''' ## dict to store 'kook/books/{clean,all}.py' in memory kook.__dict__.setdefault('_BOOK_LIBRARY', {}) if __name__ == '__main__': import re ## monkey patch to load '@kook/books/{clean,all}.py' from memory def load(self, filename, context_shared=False): m = re.match(r'^@(\w+)', filename) if m: content = kook._BOOK_LIBRARY.get(filename[1:]) if content: return self._book._load_content_with_check(content, filename, filename, context_shared) #return self._orig_load(filename, context_shared) filepath = kook.utils.resolve_filepath(filename, 1) return self._book.load_book(filepath, context_shared) cls = kook.cookbook.KookbookProxy cls._orig_load = cls.load cls.load = load ## use this filename instead of Kookbook.py argv = list(sys.argv) if getattr(kook, '_BOOK_CONTENT', None): argv[1:1] = ['-f', __file__] ## start command status = kook.main.MainCommand(argv).main() sys.exit(status) ''') s = "".join(buf) if kwargs.get('o'): write_file(kwargs.get('o'), s) else: sys.stdout.write(s)
PypiClean
/a_fmm-0.1.0.tar.gz/a_fmm-0.1.0/README.md
[![Documentation Status](https://readthedocs.org/projects/a-fmm/badge/?version=latest)](https://a-fmm.readthedocs.io/en/latest/?badge=latest) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) [![MIT](https://img.shields.io/github/license/gdsfactory/gdsfactory)](https://choosealicense.com/licenses/mit/) # A-FMM This is a Python implementation the Aperiodic-Fourier Modal Method, a fully vectorial method for solving Maxwell equations that combines a Fourier-based mode solver and a scattering matrix recursion algorithm to model full 3D structures. This approach is well suited to calculate modes, transmission, reflection, scattering and absorption of multi-layered structures. Moreover, support for Bloch modes of periodic structures allows for the simulation of photonic crystals or waveguide Bragg gratings. ## Installation You can install A_FMM directly from pypi by running: pip install A_FMM ## Documentation Full documentation is available on [Read the Docs](https://a-fmm.readthedocs.io)
PypiClean
/DJModels-0.0.6-py3-none-any.whl/djmodels/db/migrations/operations/models.py
from djmodels.db import models from djmodels.db.migrations.operations.base import Operation from djmodels.db.migrations.state import ModelState from djmodels.db.models.options import normalize_together from djmodels.utils.functional import cached_property from .fields import ( AddField, AlterField, FieldOperation, RemoveField, RenameField, ) from .utils import ModelTuple, field_references_model def _check_for_duplicates(arg_name, objs): used_vals = set() for val in objs: if val in used_vals: raise ValueError( "Found duplicate value %s in CreateModel %s argument." % (val, arg_name) ) used_vals.add(val) class ModelOperation(Operation): def __init__(self, name): self.name = name @cached_property def name_lower(self): return self.name.lower() def references_model(self, name, app_label=None): return name.lower() == self.name_lower def reduce(self, operation, app_label=None): return ( super().reduce(operation, app_label=app_label) or not operation.references_model(self.name, app_label) ) class CreateModel(ModelOperation): """Create a model's table.""" serialization_expand_args = ['fields', 'options', 'managers'] def __init__(self, name, fields, options=None, bases=None, managers=None): self.fields = fields self.options = options or {} self.bases = bases or (models.Model,) self.managers = managers or [] super().__init__(name) # Sanity-check that there are no duplicated field names, bases, or # manager names _check_for_duplicates('fields', (name for name, _ in self.fields)) _check_for_duplicates('bases', ( base._meta.label_lower if hasattr(base, '_meta') else base.lower() if isinstance(base, str) else base for base in self.bases )) _check_for_duplicates('managers', (name for name, _ in self.managers)) def deconstruct(self): kwargs = { 'name': self.name, 'fields': self.fields, } if self.options: kwargs['options'] = self.options if self.bases and self.bases != (models.Model,): kwargs['bases'] = self.bases if self.managers and self.managers != [('objects', models.Manager())]: kwargs['managers'] = self.managers return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): state.add_model(ModelState( app_label, self.name, list(self.fields), dict(self.options), tuple(self.bases), list(self.managers), )) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def describe(self): return "Create %smodel %s" % ("proxy " if self.options.get("proxy", False) else "", self.name) def references_model(self, name, app_label=None): name_lower = name.lower() if name_lower == self.name_lower: return True # Check we didn't inherit from the model model_tuple = ModelTuple(app_label, name_lower) for base in self.bases: if (base is not models.Model and isinstance(base, (models.base.ModelBase, str)) and ModelTuple.from_model(base) == model_tuple): return True # Check we have no FKs/M2Ms with it for _name, field in self.fields: if field_references_model(field, model_tuple): return True return False def reduce(self, operation, app_label=None): if (isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False)): return [] elif isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower: return [ CreateModel( operation.new_name, fields=self.fields, options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower: return [ CreateModel( self.name, fields=self.fields, options={**self.options, **operation.options}, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterTogetherOptionOperation) and self.name_lower == operation.name_lower: return [ CreateModel( self.name, fields=self.fields, options={**self.options, **{operation.option_name: operation.option_value}}, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterOrderWithRespectTo) and self.name_lower == operation.name_lower: return [ CreateModel( self.name, fields=self.fields, options={**self.options, 'order_with_respect_to': operation.order_with_respect_to}, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower: if isinstance(operation, AddField): return [ CreateModel( self.name, fields=self.fields + [(operation.name, operation.field)], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterField): return [ CreateModel( self.name, fields=[ (n, operation.field if n == operation.name else v) for n, v in self.fields ], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveField): options = self.options.copy() for option_name in ('unique_together', 'index_together'): option = options.pop(option_name, None) if option: option = set(filter(bool, ( tuple(f for f in fields if f != operation.name_lower) for fields in option ))) if option: options[option_name] = option order_with_respect_to = options.get('order_with_respect_to') if order_with_respect_to == operation.name_lower: del options['order_with_respect_to'] return [ CreateModel( self.name, fields=[ (n, v) for n, v in self.fields if n.lower() != operation.name_lower ], options=options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameField): options = self.options.copy() for option_name in ('unique_together', 'index_together'): option = options.get(option_name) if option: options[option_name] = { tuple(operation.new_name if f == operation.old_name else f for f in fields) for fields in option } order_with_respect_to = options.get('order_with_respect_to') if order_with_respect_to == operation.old_name: options['order_with_respect_to'] = operation.new_name return [ CreateModel( self.name, fields=[ (operation.new_name if n == operation.old_name else n, v) for n, v in self.fields ], options=options, bases=self.bases, managers=self.managers, ), ] return super().reduce(operation, app_label=app_label) class DeleteModel(ModelOperation): """Drop a model's table.""" def deconstruct(self): kwargs = { 'name': self.name, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): state.remove_model(app_label, self.name_lower) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def references_model(self, name, app_label=None): # The deleted model could be referencing the specified model through # related fields. return True def describe(self): return "Delete model %s" % self.name class RenameModel(ModelOperation): """Rename a model.""" def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name super().__init__(old_name) @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { 'old_name': self.old_name, 'new_name': self.new_name, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): # Add a new model. renamed_model = state.models[app_label, self.old_name_lower].clone() renamed_model.name = self.new_name state.models[app_label, self.new_name_lower] = renamed_model # Repoint all fields pointing to the old model to the new one. old_model_tuple = ModelTuple(app_label, self.old_name_lower) new_remote_model = '%s.%s' % (app_label, self.new_name) to_reload = [] for (model_app_label, model_name), model_state in state.models.items(): model_changed = False for index, (name, field) in enumerate(model_state.fields): changed_field = None remote_field = field.remote_field if remote_field: remote_model_tuple = ModelTuple.from_model( remote_field.model, model_app_label, model_name ) if remote_model_tuple == old_model_tuple: changed_field = field.clone() changed_field.remote_field.model = new_remote_model through_model = getattr(remote_field, 'through', None) if through_model: through_model_tuple = ModelTuple.from_model( through_model, model_app_label, model_name ) if through_model_tuple == old_model_tuple: if changed_field is None: changed_field = field.clone() changed_field.remote_field.through = new_remote_model if changed_field: model_state.fields[index] = name, changed_field model_changed = True if model_changed: to_reload.append((model_app_label, model_name)) # Reload models related to old model before removing the old model. state.reload_models(to_reload, delay=True) # Remove the old model. state.remove_model(app_label, self.old_name_lower) state.reload_model(app_label, self.new_name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) # Move the main table schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model: model = new_model related_key = (app_label, self.new_name_lower) else: model = related_object.related_model related_key = ( related_object.related_model._meta.app_label, related_object.related_model._meta.model_name, ) to_field = to_state.apps.get_model( *related_key )._meta.get_field(related_object.field.name) schema_editor.alter_field( model, related_object.field, to_field, ) # Rename M2M fields whose name is based on this model's name. fields = zip(old_model._meta.local_many_to_many, new_model._meta.local_many_to_many) for (old_field, new_field) in fields: # Skip self-referential fields as these are renamed above. if new_field.model == new_field.related_model or not new_field.remote_field.through._meta.auto_created: continue # Rename the M2M table that's based on this model's name. old_m2m_model = old_field.remote_field.through new_m2m_model = new_field.remote_field.through schema_editor.alter_db_table( new_m2m_model, old_m2m_model._meta.db_table, new_m2m_model._meta.db_table, ) # Rename the column in the M2M table that's based on this # model's name. schema_editor.alter_field( new_m2m_model, old_m2m_model._meta.get_field(old_model._meta.model_name), new_m2m_model._meta.get_field(new_model._meta.model_name), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.new_name_lower, self.old_name_lower = self.old_name_lower, self.new_name_lower self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = self.old_name_lower, self.new_name_lower self.new_name, self.old_name = self.old_name, self.new_name def references_model(self, name, app_label=None): return ( name.lower() == self.old_name_lower or name.lower() == self.new_name_lower ) def describe(self): return "Rename model %s to %s" % (self.old_name, self.new_name) def reduce(self, operation, app_label=None): if (isinstance(operation, RenameModel) and self.new_name_lower == operation.old_name_lower): return [ RenameModel( self.old_name, operation.new_name, ), ] # Skip `ModelOperation.reduce` as we want to run `references_model` # against self.new_name. return ( super(ModelOperation, self).reduce(operation, app_label=app_label) or not operation.references_model(self.new_name, app_label) ) class AlterModelTable(ModelOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { 'name': self.name, 'table': self.table, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): state.models[app_label, self.name_lower].options["db_table"] = self.table state.reload_model(app_label, self.name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Rename M2M fields whose name is based on this model's db_table for (old_field, new_field) in zip(old_model._meta.local_many_to_many, new_model._meta.local_many_to_many): if new_field.remote_field.through._meta.auto_created: schema_editor.alter_db_table( new_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Rename table for %s to %s" % ( self.name, self.table if self.table is not None else "(default)" ) def reduce(self, operation, app_label=None): if isinstance(operation, (AlterModelTable, DeleteModel)) and self.name_lower == operation.name_lower: return [operation] return super().reduce(operation, app_label=app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, app_label=None): if isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower: return [operation] return super().reduce(operation, app_label=app_label) class AlterTogetherOptionOperation(ModelOptionOperation): option_name = None def __init__(self, name, option_value): if option_value: option_value = set(normalize_together(option_value)) setattr(self, self.option_name, option_value) super().__init__(name) @cached_property def option_value(self): return getattr(self, self.option_name) def deconstruct(self): kwargs = { 'name': self.name, self.option_name: self.option_value, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): model_state = state.models[app_label, self.name_lower] model_state.options[self.option_name] = self.option_value state.reload_model(app_label, self.name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) alter_together = getattr(schema_editor, 'alter_%s' % self.option_name) alter_together( new_model, getattr(old_model._meta, self.option_name, set()), getattr(new_model._meta, self.option_name, set()), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label=None): return ( self.references_model(model_name, app_label) and ( not self.option_value or any((name in fields) for fields in self.option_value) ) ) def describe(self): return "Alter %s for %s (%s constraint(s))" % (self.option_name, self.name, len(self.option_value or '')) class AlterUniqueTogether(AlterTogetherOptionOperation): """ Change the value of unique_together to the target one. Input value of unique_together must be a set of tuples. """ option_name = 'unique_together' def __init__(self, name, unique_together): super().__init__(name, unique_together) class AlterIndexTogether(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" def __init__(self, name, index_together): super().__init__(name, index_together) class AlterOrderWithRespectTo(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = 'order_with_respect_to' def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): kwargs = { 'name': self.name, 'order_with_respect_to': self.order_with_respect_to, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): model_state = state.models[app_label, self.name_lower] model_state.options['order_with_respect_to'] = self.order_with_respect_to state.reload_model(app_label, self.name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.name) # Remove a field if we need to if from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to: schema_editor.remove_field(from_model, from_model._meta.get_field("_order")) # Add a field if we need to (altering the column is untouched as # it's likely a rename) elif to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to: field = to_model._meta.get_field("_order") if not field.has_default(): field.default = 0 schema_editor.add_field( from_model, field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label=None): return ( self.references_model(model_name, app_label) and ( self.order_with_respect_to is None or name == self.order_with_respect_to ) ) def describe(self): return "Set order_with_respect_to on %s to %s" % (self.name, self.order_with_respect_to) class AlterModelOptions(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { 'name': self.name, 'options': self.options, } return ( self.__class__.__qualname__, [], kwargs ) def state_forwards(self, app_label, state): model_state = state.models[app_label, self.name_lower] model_state.options = {**model_state.options, **self.options} for key in self.ALTER_OPTION_KEYS: if key not in self.options: model_state.options.pop(key, False) state.reload_model(app_label, self.name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name class AlterModelManagers(ModelOptionOperation): """Alter the model's managers.""" serialization_expand_args = ['managers'] def __init__(self, name, managers): self.managers = managers super().__init__(name) def deconstruct(self): return ( self.__class__.__qualname__, [self.name, self.managers], {} ) def state_forwards(self, app_label, state): model_state = state.models[app_label, self.name_lower] model_state.managers = list(self.managers) state.reload_model(app_label, self.name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change managers on %s" % self.name class IndexOperation(Operation): option_name = 'indexes' @cached_property def model_name_lower(self): return self.model_name.lower() class AddIndex(IndexOperation): """Add an index on a model.""" def __init__(self, model_name, index): self.model_name = model_name if not index.name: raise ValueError( "Indexes passed to AddIndex operations require a name " "argument. %r doesn't have one." % index ) self.index = index def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] indexes = list(model_state.options[self.option_name]) indexes.append(self.index.clone()) model_state.options[self.option_name] = indexes state.reload_model(app_label, self.model_name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index) def deconstruct(self): kwargs = { 'model_name': self.model_name, 'index': self.index, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return 'Create index %s on field(s) %s of model %s' % ( self.index.name, ', '.join(self.index.fields), self.model_name, ) class RemoveIndex(IndexOperation): """Remove an index from a model.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] indexes = model_state.options[self.option_name] model_state.options[self.option_name] = [idx for idx in indexes if idx.name != self.name] state.reload_model(app_label, self.model_name_lower, delay=True) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index) def deconstruct(self): kwargs = { 'model_name': self.model_name, 'name': self.name, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return 'Remove index %s from %s' % (self.name, self.model_name) class AddConstraint(IndexOperation): option_name = 'constraints' def __init__(self, model_name, constraint): self.model_name = model_name self.constraint = constraint def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] constraints = list(model_state.options[self.option_name]) constraints.append(self.constraint) model_state.options[self.option_name] = constraints def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_constraint(model, self.constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_constraint(model, self.constraint) def deconstruct(self): return self.__class__.__name__, [], { 'model_name': self.model_name, 'constraint': self.constraint, } def describe(self): return 'Create constraint %s on model %s' % (self.constraint.name, self.model_name) class RemoveConstraint(IndexOperation): option_name = 'constraints' def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): model_state = state.models[app_label, self.model_name_lower] constraints = model_state.options[self.option_name] model_state.options[self.option_name] = [c for c in constraints if c.name != self.name] def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] constraint = from_model_state.get_constraint_by_name(self.name) schema_editor.remove_constraint(model, constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] constraint = to_model_state.get_constraint_by_name(self.name) schema_editor.add_constraint(model, constraint) def deconstruct(self): return self.__class__.__name__, [], { 'model_name': self.model_name, 'name': self.name, } def describe(self): return 'Remove constraint %s from model %s' % (self.name, self.model_name)
PypiClean
/GPR1D-1.3.1.tar.gz/GPR1D-1.3.1/scripts/GPR1D_demo.py
import os import sys import re import inspect from operator import itemgetter import numpy as np import GPR1D # Required import, only works after using 'pip install' def run_demo(): """ A demonstration script for the classes within the GPR1D module. Due to the iterative nature of the optimization method and the random nature of the kernel restart function, the results may not be exactly the same for consecutive runs of this demo script. However, all fits should fall within the fit error ranges of each other, unless the optimization algorithm has not converged. """ ### Some basic setup plot_save_directory = './GPPlots/' if not plot_save_directory.endswith('/'): plot_save_directory = plot_save_directory + '/' if not os.path.isdir(plot_save_directory): os.makedirs(plot_save_directory) ### Generating sample data # Make basic function data x_spread = 0.01 y_spread = 0.25 intercept = 3.0 slope1 = 1.0 x_values = np.linspace(0.0,1.0,21) y_values = slope1 * x_values + intercept boundary1 = 0.3 slope2 = 16.0 boundary1_filter = (x_values >= boundary1) y_values[boundary1_filter] = y_values[boundary1_filter] - slope2 * (x_values[boundary1_filter] - boundary1) boundary2 = 0.7 boundary2_filter = (x_values >= boundary2) y_values[boundary2_filter] = y_values[boundary2_filter] + (slope2 + slope1) * (x_values[boundary2_filter] - boundary2) # Add random error to generated data points raw_x_values = x_values + x_spread * np.random.randn(x_values.size) raw_y_values = y_values + y_spread * np.random.randn(y_values.size) raw_x_errors = np.full(raw_x_values.shape,x_spread) raw_y_errors = np.full(raw_y_values.shape,y_spread) raw_intercept = raw_y_values[0] ### Fitting fit_x_values = np.linspace(0.0,1.0,100) # Define a kernel to fit the data itself # Rational quadratic kernel is usually robust enough for general fitting kernel = GPR1D.RQ_Kernel(1.0e0,1.0e0,5.0e0) # This is only necessary if using kernel restart option on the data fitting kernel_hyppar_bounds = np.atleast_2d([[1.0e-1,1.0e-1,5.0e0],[1.0e1,1.0e0,2.0e1]]) # Define a kernel to fit the given y-errors, needed for rigourous estimation of fit error including data error # Typically a simple rational quadratic kernel is sufficient given a high regularization parameter (specified later) # Here, the RQ kernel is summed with a noise kernel for extra robustness and to demonstrate how to use operator kernels error_kernel = GPR1D.RQ_Kernel(1.0e-1,1.0e0,5.0e0) # Again, this is only necessary if using kernel restart option on the error fitting error_kernel_hyppar_bounds = np.atleast_2d([[1.0e-1,1.0e-1,1.0e0,],[1.0e1,1.0e0,1.0e1]]) # GPR fit using y-errors only as weights # Create class object to store raw data, kernels, and settings gpr_object = GPR1D.GaussianProcessRegression1D() # Print source location for reference, in case of multiple installations location = inspect.getsourcefile(type(gpr_object)) print("Using GPR1D definition from: %s" % (os.path.dirname(location) + '/')) # Define the kernel and regularization parameter to be used in the data fitting routine gpr_object.set_kernel(kernel=kernel,kbounds=kernel_hyppar_bounds,regpar=1.0) # Define the raw data and associated errors to be fitted gpr_object.set_raw_data(xdata=raw_x_values,ydata=raw_y_values,yerr=raw_y_errors,xerr=raw_x_errors, \ dxdata=[0.0],dydata=[0.0],dyerr=[0.0]) # Example of applying derivative constraints # Define the search criteria for data fitting routine and error fitting routine gpr_object.set_search_parameters(epsilon=1.0e-2) gpr_object.set_error_search_parameters(epsilon=1.0e-1) # Default optimizer is gradient ascent / descent - extremely robust but slow # Uncomment any of the following lines to test the recommended optimizers #gpr_object.set_search_parameters(epsilon=1.0e-2,method='adam',spars=[1.0e-1,0.4,0.8]) #gpr_object.set_error_search_parameters(epsilon=1.0e-1,method='adam',spars=[1.0e-1,0.4,0.8]) # Perform the fit with kernel restarts gpr_object.GPRFit(fit_x_values,hsgp_flag=False,nrestarts=5) # Grab optimized kernel settings - easy way to minimize data storage requirements for fit reproduction (gp_kernel_name,gp_kernel_hyppars,gp_fit_regpar) = gpr_object.get_gp_kernel_details() # Grab fit results (fit_y_values,fit_y_errors,fit_dydx_values,fit_dydx_errors) = gpr_object.get_gp_results() # Grab the log-marginal-likelihood of fit fit_lml = gpr_object.get_gp_lml() # GPR fit rigourously accounting only for y-errors (this is the recommended option) # Procedure is nearly identical to above, except for the addition of an error kernel hsgpr_object = GPR1D.GaussianProcessRegression1D() # Define the kernel and regularization parameter to be used in the data fitting routine hsgpr_object.set_kernel(kernel=kernel,kbounds=kernel_hyppar_bounds,regpar=1.0) # Define the kernel and regularization parameter to be used in the error fitting routine hsgpr_object.set_error_kernel(kernel=error_kernel,kbounds=error_kernel_hyppar_bounds,regpar=2.0) # Define the raw data and associated errors to be fitted hsgpr_object.set_raw_data(xdata=raw_x_values,ydata=raw_y_values,yerr=raw_y_errors,xerr=raw_x_errors, \ dxdata=[0.0],dydata=[0.0],dyerr=[0.0]) # Example of applying derivative constraints # Define the search criteria for data fitting routine and error fitting routine hsgpr_object.set_search_parameters(epsilon=1.0e-2) hsgpr_object.set_error_search_parameters(epsilon=1.0e-1) # Default optimizer is gradient ascent / descent - extremely robust but slow # Uncomment any of the following lines to test the recommended optimizers #hsgpr_object.set_search_parameters(epsilon=1.0e-2,method='adam',spars=[1.0e-1,0.4,0.8]) #hsgpr_object.set_error_search_parameters(epsilon=1.0e-1,method='adam',spars=[1.0e-1,0.4,0.8]) # Perform the fit with kernel restarts hsgpr_object.GPRFit(fit_x_values,hsgp_flag=True,nrestarts=5) # Grab optimized kernel settings - easy way to minimize data storage requirements for fit reproduction (hsgp_kernel_name,hsgp_kernel_hyppars,hsgp_fit_regpar) = hsgpr_object.get_gp_kernel_details() (hsgp_error_kernel_name,hsgp_error_kernel_hyppars,hsgp_error_fit_regpar) = hsgpr_object.get_gp_error_kernel_details() # Grab fit results (hs_fit_y_values,hs_fit_y_errors,hs_fit_dydx_values,hs_fit_dydx_errors) = hsgpr_object.get_gp_results() (hs_zfit_y_values,hs_zfit_y_errors,hs_zfit_dydx_values,hs_zfit_dydx_errors) = hsgpr_object.get_gp_results(noise_flag=False) # Grab the log-marginal-likelihood of fit hs_fit_lml = hsgpr_object.get_gp_lml() # GPR fit rigourously accounting for y-errors AND x-errors # Procedure is nearly identical to above, except for the addition of an extra option nigpr_object = GPR1D.GaussianProcessRegression1D() nigpr_object.set_kernel(kernel=kernel,kbounds=kernel_hyppar_bounds,regpar=1.0) nigpr_object.set_error_kernel(kernel=error_kernel,kbounds=error_kernel_hyppar_bounds,regpar=2.0) nigpr_object.set_raw_data(xdata=raw_x_values,ydata=raw_y_values,yerr=raw_y_errors,xerr=raw_x_errors, \ dxdata=[0.0],dydata=[0.0],dyerr=[0.0]) nigpr_object.set_search_parameters(epsilon=1.0e-2) nigpr_object.set_error_search_parameters(epsilon=1.0e-1) # Uncomment any of the following lines to test the recommended optimizers #nigpr_object.set_search_parameters(epsilon=1.0e-2,method='adam',spars=[1.0e-1,0.4,0.8]) #nigpr_object.set_error_search_parameters(epsilon=1.0e-1,method='adam',spars=[1.0e-1,0.4,0.8]) # Perform the fit with kernel restarts, here is the extra option to account for x-errors in fit nigpr_object.GPRFit(fit_x_values,hsgp_flag=True,nigp_flag=True,nrestarts=5) # Grab outputs (nigp_kernel_name,nigp_kernel_hyppars,nigp_fit_regpar) = nigpr_object.get_gp_kernel_details() (nigp_error_kernel_name,nigp_error_kernel_hyppars,nigp_error_fit_regpar) = nigpr_object.get_gp_error_kernel_details() (ni_fit_y_values,ni_fit_y_errors,ni_fit_dydx_values,ni_fit_dydx_errors) = nigpr_object.get_gp_results() ni_fit_lml = nigpr_object.get_gp_lml() ### Sampling distribution (only done with HSGP option) num_samples = 10000 # Samples the fit distribution - smooth noise representation sample_array = hsgpr_object.sample_GP(num_samples,actual_noise=False) # Calculates the derivatives of the sampled fit distributions dfit_x_values = (fit_x_values[1:] + fit_x_values[:-1]) / 2.0 deriv_array = (sample_array[:,1:] - sample_array[:,:-1]) / (fit_x_values[1:] - fit_x_values[:-1]) # Samples the derivative distribution - smooth noise representation dsample_array = hsgpr_object.sample_GP_derivative(num_samples,actual_noise=False) # Calculates the integrals of the sampled derivative distributions ifit_x_values = dfit_x_values.copy() integ_array = dsample_array[:,1] * (ifit_x_values[0] - fit_x_values[0]) # + raw_intercept if integ_array.ndim == 1: integ_array = np.transpose(np.atleast_2d(integ_array)) for jj in np.arange(1,dsample_array.shape[1]-1): integ = integ_array[:,jj-1] + dsample_array[:,jj] * (ifit_x_values[jj] - ifit_x_values[jj-1]) if integ.ndim == 1: integ = np.transpose(np.atleast_2d(integ)) integ_array = np.hstack((integ_array,integ)) # Integrals require renormalization to the fit mean to define the constant of integration that is lost orig_mean = np.nanmean(hs_fit_y_values) for ii in np.arange(0,num_samples): sint_mean = np.nanmean(integ_array[ii,:]) integ_array[ii,:] = integ_array[ii,:] - sint_mean + orig_mean # Samples the fit distribution - true noise representation nsample_array = hsgpr_object.sample_GP(num_samples,actual_noise=True) # Samples the derivative distribution - true noise representation ndsample_array = hsgpr_object.sample_GP_derivative(num_samples,actual_noise=True) # Samples the fit distribution - zero noise representation zsample_array = hsgpr_object.sample_GP(num_samples,without_noise=True) # Calculates the derivatives of the sampled fit distributions - zero noise representation zderiv_array = (zsample_array[:,1:] - zsample_array[:,:-1]) / (fit_x_values[1:] - fit_x_values[:-1]) # Samples the derivative distribution - zero noise representation # Note that zero noise is only different from smooth noise if an error kernel is used zdsample_array = hsgpr_object.sample_GP_derivative(num_samples,without_noise=True) # Calculates the integrals of the sampled derivative distributions - zero noise representation zinteg_array = zdsample_array[:,1] * (ifit_x_values[0] - fit_x_values[0]) # + raw_intercept if zinteg_array.ndim == 1: zinteg_array = np.transpose(np.atleast_2d(zinteg_array)) for jj in np.arange(1,zdsample_array.shape[1]-1): zinteg = zinteg_array[:,jj-1] + zdsample_array[:,jj] * (ifit_x_values[jj] - ifit_x_values[jj-1]) if zinteg.ndim == 1: zinteg = np.transpose(np.atleast_2d(zinteg)) zinteg_array = np.hstack((zinteg_array,zinteg)) # Integrals require renormalization to the fit mean to define the constant of integration that is lost zorig_mean = np.nanmean(hs_zfit_y_values) for ii in np.arange(0,num_samples): zsint_mean = np.nanmean(zinteg_array[ii,:]) zinteg_array[ii,:] = zinteg_array[ii,:] - zsint_mean + zorig_mean # Computing statistics of sampled profiles sample_mean = np.nanmean(sample_array,axis=0) deriv_mean = np.nanmean(deriv_array,axis=0) dsample_mean = np.nanmean(dsample_array,axis=0) integ_mean = np.nanmean(integ_array,axis=0) sample_std = np.nanstd(sample_array,axis=0) deriv_std = np.nanstd(deriv_array,axis=0) dsample_std = np.nanstd(dsample_array,axis=0) integ_std = np.nanstd(integ_array,axis=0) # Computing statistics of sampled profiles - zero noise representation zsample_mean = np.nanmean(zsample_array,axis=0) zderiv_mean = np.nanmean(zderiv_array,axis=0) zdsample_mean = np.nanmean(zdsample_array,axis=0) zinteg_mean = np.nanmean(zinteg_array,axis=0) zsample_std = np.nanstd(zsample_array,axis=0) zderiv_std = np.nanstd(zderiv_array,axis=0) zdsample_std = np.nanstd(zdsample_array,axis=0) zinteg_std = np.nanstd(zinteg_array,axis=0) ### Printing gp_str = "\n--- GPR Fit ---\n\n" gp_str = gp_str + "Kernel name: %30s\n" % (gp_kernel_name) gp_str = gp_str + "Regularization parameter: %17.4f\n" % (gp_fit_regpar) gp_str = gp_str + "Optimized kernel hyperparameters:\n" for hh in np.arange(0,gp_kernel_hyppars.size): gp_str = gp_str + "%15.6e" % (gp_kernel_hyppars[hh]) gp_str = gp_str + "\n\n" gp_str = gp_str + "Log-marginal-likelihood: %18.6f\n" % (fit_lml) print(gp_str) hsgp_str = "\n--- HSGPR Fit ---\n\n" hsgp_str = hsgp_str + "Kernel name: %30s\n" % (hsgp_kernel_name) hsgp_str = hsgp_str + "Regularization parameter: %17.4f\n" % (hsgp_fit_regpar) hsgp_str = hsgp_str + "Optimized kernel hyperparameters:\n" for hh in np.arange(0,hsgp_kernel_hyppars.size): hsgp_str = hsgp_str + "%15.6e" % (hsgp_kernel_hyppars[hh]) hsgp_str = hsgp_str + "\n\n" hsgp_str = hsgp_str + "Error kernel name: %24s\n" % (hsgp_error_kernel_name) hsgp_str = hsgp_str + "Regularization parameter: %17.4f\n" % (hsgp_error_fit_regpar) hsgp_str = hsgp_str + "Optimized error kernel hyperparameters:\n" for hh in np.arange(0,hsgp_error_kernel_hyppars.size): hsgp_str = hsgp_str + "%15.6e" % (hsgp_error_kernel_hyppars[hh]) hsgp_str = hsgp_str + "\n\n" hsgp_str = hsgp_str + "Log-marginal-likelihood: %18.6f\n" % (hs_fit_lml) print(hsgp_str) nigp_str = "--- NIGPR Fit ---\n\n" nigp_str = nigp_str + "Kernel name: %30s\n" % (nigp_kernel_name) nigp_str = nigp_str + "Regularization parameter: %17.4f\n" % (nigp_fit_regpar) nigp_str = nigp_str + "Optimized kernel hyperparameters:\n" for hh in np.arange(0,nigp_kernel_hyppars.size): nigp_str = nigp_str + "%15.6e" % (nigp_kernel_hyppars[hh]) nigp_str = nigp_str + "\n\n" nigp_str = nigp_str + "Error kernel name: %24s\n" % (nigp_error_kernel_name) nigp_str = nigp_str + "Regularization parameter: %17.4f\n" % (nigp_error_fit_regpar) nigp_str = nigp_str + "Optimized error kernel hyperparameters:\n" for hh in np.arange(0,nigp_error_kernel_hyppars.size): nigp_str = nigp_str + "%15.6e" % (nigp_error_kernel_hyppars[hh]) nigp_str = nigp_str + "\n\n" nigp_str = nigp_str + "Log-marginal-likelihood: %18.6f\n" % (ni_fit_lml) print(nigp_str) ### Plotting plt = None try: import matplotlib.pyplot as plt except: plt = None if plt is not None: plot_num_samples = 10 plot_sigma = 2.0 # Raw data with GPR fit and error, only accounting for y-errors plot_raw_y_errors = plot_sigma * raw_y_errors fig = plt.figure() ax = fig.add_subplot(111) ax.errorbar(raw_x_values,raw_y_values,yerr=plot_raw_y_errors,ls='',marker='.',color='k') ax.plot(fit_x_values,hs_fit_y_values,color='r') plot_hs_fit_y_lower = hs_fit_y_values - plot_sigma * hs_fit_y_errors plot_hs_fit_y_upper = hs_fit_y_values + plot_sigma * hs_fit_y_errors ax.fill_between(fit_x_values,plot_hs_fit_y_lower,plot_hs_fit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'gp_test.png') plt.close(fig) # Derivative of GPR fit and error, only accounting for y-errors fig = plt.figure() ax = fig.add_subplot(111) ax.plot(fit_x_values,fit_dydx_values,color='r') plot_hs_fit_dydx_lower = hs_fit_dydx_values - plot_sigma * hs_fit_dydx_errors plot_hs_fit_dydx_upper = hs_fit_dydx_values + plot_sigma * hs_fit_dydx_errors ax.fill_between(fit_x_values,plot_hs_fit_dydx_lower,plot_hs_fit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'gp_dtest.png') plt.close(fig) # Raw data with GPR fit and error, comparison of using y-errors as weights, rigourously accounting for y-errors, and rigourously account for y-errors AND x-errors plot_raw_x_errors = plot_sigma * raw_x_errors fig = plt.figure() ax = fig.add_subplot(111) ax.errorbar(raw_x_values,raw_y_values,xerr=plot_raw_x_errors,yerr=plot_raw_y_errors,ls='',marker='.',color='k') ax.plot(fit_x_values,fit_y_values,color='g') plot_fit_y_lower = fit_y_values - plot_sigma * fit_y_errors plot_fit_y_upper = fit_y_values + plot_sigma * fit_y_errors ax.plot(fit_x_values,plot_fit_y_lower,color='g',ls='--') ax.plot(fit_x_values,plot_fit_y_upper,color='g',ls='--') #ax.fill_between(fit_x_values,plot_fit_y_lower,plot_fit_y_upper,facecolor='g',edgecolor='None',alpha=0.2) ax.plot(fit_x_values,hs_fit_y_values,color='r') ax.plot(fit_x_values,plot_hs_fit_y_lower,color='r',ls='--') ax.plot(fit_x_values,plot_hs_fit_y_upper,color='r',ls='--') #ax.fill_between(fit_x_values,plot_hs_fit_y_lower,plot_hs_fit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) ax.plot(fit_x_values,ni_fit_y_values,color='b') plot_ni_fit_y_lower = ni_fit_y_values - plot_sigma * ni_fit_y_errors plot_ni_fit_y_upper = ni_fit_y_values + plot_sigma * ni_fit_y_errors ax.plot(fit_x_values,plot_ni_fit_y_lower,color='b',ls='--') ax.plot(fit_x_values,plot_ni_fit_y_upper,color='b',ls='--') #ax.fill_between(fit_x_values,plot_ni_fit_y_lower,plot_ni_fit_y_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'gp_options_test.png') plt.close(fig) # Derivative of GPR fit and error, comparison of using y-errors as weights, rigourously accounting for y-errors, and rigourously account for y-errors AND x-errors fig = plt.figure() ax = fig.add_subplot(111) ax.plot(fit_x_values,fit_dydx_values,color='g') plot_fit_dydx_lower = fit_dydx_values - plot_sigma * fit_dydx_errors plot_fit_dydx_upper = fit_dydx_values + plot_sigma * fit_dydx_errors ax.plot(fit_x_values,plot_fit_dydx_lower,color='g',ls='--') ax.plot(fit_x_values,plot_fit_dydx_upper,color='g',ls='--') #ax.fill_between(fit_x_values,plot_fit_dydx_lower,plot_fit_dydx_upper,facecolor='g',edgecolor='None',alpha=0.2) ax.plot(fit_x_values,hs_fit_dydx_values,color='r') ax.plot(fit_x_values,plot_hs_fit_dydx_lower,color='r',ls='--') ax.plot(fit_x_values,plot_hs_fit_dydx_upper,color='r',ls='--') #ax.fill_between(fit_x_values,plot_hs_fit_dydx_lower,plot_hs_fit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) ax.plot(fit_x_values,ni_fit_dydx_values,color='b') plot_ni_fit_dydx_lower = ni_fit_dydx_values - plot_sigma * ni_fit_dydx_errors plot_ni_fit_dydx_upper = ni_fit_dydx_values + plot_sigma * ni_fit_dydx_errors ax.plot(fit_x_values,plot_ni_fit_dydx_lower,color='b',ls='--') ax.plot(fit_x_values,plot_ni_fit_dydx_upper,color='b',ls='--') #ax.fill_between(fit_x_values,plot_ni_fit_dydx_lower,plot_ni_fit_dydx_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'gp_options_dtest.png') plt.close(fig) # Sampled fit curves (smooth noise) against GPR fit distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_y_lower,plot_hs_fit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,sample_array[ii,:],color='k',alpha=0.5) plot_hs_sample_y_lower = sample_mean - plot_sigma * sample_std plot_hs_sample_y_upper = sample_mean + plot_sigma * sample_std ax.fill_between(fit_x_values,plot_hs_sample_y_lower,plot_hs_sample_y_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_test.png') plt.close(fig) # Derivatives of sampled fit curves (smooth noise) against GPR fit derivative distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_dydx_lower,plot_hs_fit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(dfit_x_values,deriv_array[ii,:],color='k',alpha=0.5) plot_hs_sample_dydx_lower = deriv_mean - plot_sigma * deriv_std plot_hs_sample_dydx_upper = deriv_mean + plot_sigma * deriv_std ax.fill_between(dfit_x_values,plot_hs_sample_dydx_lower,plot_hs_sample_dydx_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_drv_test.png') plt.close(fig) # Sampled fit derivative curves (smooth noise) against GPR fit derivative distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_dydx_lower,plot_hs_fit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,dsample_array[ii,:],color='k',alpha=0.5) plot_hs_dsample_dydx_lower = dsample_mean - plot_sigma * dsample_std plot_hs_dsample_dydx_upper = dsample_mean + plot_sigma * dsample_std ax.fill_between(fit_x_values,plot_hs_dsample_dydx_lower,plot_hs_dsample_dydx_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_dtest.png') plt.close(fig) # Integrals of sampled fit derivative curves (smooth noise) against GPR fit distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_y_lower,plot_hs_fit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(ifit_x_values,integ_array[ii,:],color='k',alpha=0.5) plot_hs_dsample_y_lower = integ_mean - plot_sigma * integ_std plot_hs_dsample_y_upper = integ_mean + plot_sigma * integ_std ax.fill_between(ifit_x_values,plot_hs_dsample_y_lower,plot_hs_dsample_y_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_itg_dtest.png') plt.close(fig) # Sampled fit curves (true noise) against GPR fit distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_y_lower,plot_hs_fit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,nsample_array[ii,:],color='k',alpha=0.5) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_noisy_test.png') plt.close(fig) # Sampled fit derivative curves (true noise) against GPR fit derivative distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_fit_dydx_lower,plot_hs_fit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,ndsample_array[ii,:],color='k',alpha=0.5) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_noisy_dtest.png') plt.close(fig) # Sampled fit curves (zero noise) against GPR fit distribution fig = plt.figure() ax = fig.add_subplot(111) plot_hs_zfit_y_lower = hs_zfit_y_values - plot_sigma * hs_zfit_y_errors plot_hs_zfit_y_upper = hs_zfit_y_values + plot_sigma * hs_zfit_y_errors ax.fill_between(fit_x_values,plot_hs_zfit_y_lower,plot_hs_zfit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,zsample_array[ii,:],color='k',alpha=0.5) plot_hs_zsample_y_lower = zsample_mean - plot_sigma * zsample_std plot_hs_zsample_y_upper = zsample_mean + plot_sigma * zsample_std ax.fill_between(fit_x_values,plot_hs_sample_y_lower,plot_hs_sample_y_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_no_noise_test.png') plt.close(fig) # Derivatives of sampled fit curves (zero noise) against GPR fit derivative distribution fig = plt.figure() ax = fig.add_subplot(111) plot_hs_zfit_dydx_lower = hs_zfit_dydx_values - plot_sigma * hs_zfit_dydx_errors plot_hs_zfit_dydx_upper = hs_zfit_dydx_values + plot_sigma * hs_zfit_dydx_errors ax.fill_between(fit_x_values,plot_hs_zfit_dydx_lower,plot_hs_zfit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(dfit_x_values,zderiv_array[ii,:],color='k',alpha=0.5) plot_hs_zsample_dydx_lower = zderiv_mean - plot_sigma * zderiv_std plot_hs_zsample_dydx_upper = zderiv_mean + plot_sigma * zderiv_std ax.fill_between(dfit_x_values,plot_hs_zsample_dydx_lower,plot_hs_zsample_dydx_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_drv_no_noise_test.png') plt.close(fig) # Sampled fit derivative curves (zero noise) against GPR fit derivative distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_zfit_dydx_lower,plot_hs_zfit_dydx_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(fit_x_values,zdsample_array[ii,:],color='k',alpha=0.5) plot_hs_zdsample_dydx_lower = zdsample_mean - plot_sigma * zdsample_std plot_hs_zdsample_dydx_upper = zdsample_mean + plot_sigma * zdsample_std ax.fill_between(fit_x_values,plot_hs_zdsample_dydx_lower,plot_hs_zdsample_dydx_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_no_noise_dtest.png') plt.close(fig) # Integrals of sampled fit derivative curves (zero noise) against GPR fit distribution fig = plt.figure() ax = fig.add_subplot(111) ax.fill_between(fit_x_values,plot_hs_zfit_y_lower,plot_hs_zfit_y_upper,facecolor='r',edgecolor='None',alpha=0.2) for ii in np.arange(0,plot_num_samples): ax.plot(ifit_x_values,zinteg_array[ii,:],color='k',alpha=0.5) plot_hs_zdsample_y_lower = zinteg_mean - plot_sigma * zinteg_std plot_hs_zdsample_y_upper = zinteg_mean + plot_sigma * zinteg_std ax.fill_between(ifit_x_values,plot_hs_zdsample_y_lower,plot_hs_zdsample_y_upper,facecolor='b',edgecolor='None',alpha=0.2) ax.set_xlim(0.0,1.0) fig.savefig(plot_save_directory+'sample_gp_itg_no_noise_dtest.png') plt.close(fig) print("Results of demonstration plotted in directory ./GPPlots/\n") else: print(" Module matplotlib not found. Skipping plotting of demonstration results.\n") print("Demonstration script successfully completed!\n") def main(): run_demo() if __name__ == "__main__": main()
PypiClean
/Gaussian_Binomial_Distribution-1.1.tar.gz/Gaussian_Binomial_Distribution-1.1/Gaussian_Binomial_Distribution/Binomialdistribution.py
import math import matplotlib.pyplot as plt from .Generaldistribution import Distribution class Binomial(Distribution): """ Binomial distribution class for calculating and visualizing a Binomial distribution. Attributes: mean (float) representing the mean value of the distribution stdev (float) representing the standard deviation of the distribution data_list (list of floats) a list of floats to be extracted from the data file p (float) representing the probability of an event occurring n (int) number of trials TODO: Fill out all functions below """ def __init__(self, prob=.5, size=20): self.n = size self.p = prob Distribution.__init__(self, self.calculate_mean(), self.calculate_stdev()) def calculate_mean(self): """Function to calculate the mean from p and n Args: None Returns: float: mean of the data set """ self.mean = self.p * self.n return self.mean def calculate_stdev(self): """Function to calculate the standard deviation from p and n. Args: None Returns: float: standard deviation of the data set """ self.stdev = math.sqrt(self.n * self.p * (1 - self.p)) return self.stdev def replace_stats_with_data(self): """Function to calculate p and n from the data set Args: None Returns: float: the p value float: the n value """ self.n = len(self.data) self.p = 1.0 * sum(self.data) / len(self.data) self.mean = self.calculate_mean() self.stdev = self.calculate_stdev() def plot_bar(self): """Function to output a histogram of the instance variable data using matplotlib pyplot library. Args: None Returns: None """ plt.bar(x = ['0', '1'], height = [(1 - self.p) * self.n, self.p * self.n]) plt.title('Bar Chart of Data') plt.xlabel('outcome') plt.ylabel('count') def pdf(self, k): """Probability density function calculator for the gaussian distribution. Args: x (float): point for calculating the probability density function Returns: float: probability density function output """ a = math.factorial(self.n) / (math.factorial(k) * (math.factorial(self.n - k))) b = (self.p ** k) * (1 - self.p) ** (self.n - k) return a * b def plot_bar_pdf(self): """Function to plot the pdf of the binomial distribution Args: None Returns: list: x values for the pdf plot list: y values for the pdf plot """ x = [] y = [] # calculate the x values to visualize for i in range(self.n + 1): x.append(i) y.append(self.pdf(i)) # make the plots plt.bar(x, y) plt.title('Distribution of Outcomes') plt.ylabel('Probability') plt.xlabel('Outcome') plt.show() return x, y def __add__(self, other): """Function to add together two Binomial distributions with equal p Args: other (Binomial): Binomial instance Returns: Binomial: Binomial distribution """ try: assert self.p == other.p, 'p values are not equal' except AssertionError as error: raise result = Binomial() result.n = self.n + other.n result.p = self.p result.calculate_mean() result.calculate_stdev() return result def __repr__(self): """Function to output the characteristics of the Binomial instance Args: None Returns: string: characteristics of the Gaussian """ return "mean {}, standard deviation {}, p {}, n {}".\ format(self.mean, self.stdev, self.p, self.n)
PypiClean
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/jinja2/jinja2/ext.py
import re from jinja2 import nodes from jinja2.defaults import BLOCK_START_STRING, \ BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \ COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \ LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \ KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS from jinja2.environment import Environment from jinja2.runtime import concat from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError from jinja2.utils import contextfunction, import_string, Markup from jinja2._compat import with_metaclass, string_types, iteritems # the only real useful gettext functions for a Jinja template. Note # that ugettext must be assigned to gettext as Jinja doesn't support # non unicode strings. GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext') class ExtensionRegistry(type): """Gives the extension an unique identifier.""" def __new__(cls, name, bases, d): rv = type.__new__(cls, name, bases, d) rv.identifier = rv.__module__ + '.' + rv.__name__ return rv class Extension(with_metaclass(ExtensionRegistry, object)): """Extensions can be used to add extra functionality to the Jinja template system at the parser level. Custom extensions are bound to an environment but may not store environment specific data on `self`. The reason for this is that an extension can be bound to another environment (for overlays) by creating a copy and reassigning the `environment` attribute. As extensions are created by the environment they cannot accept any arguments for configuration. One may want to work around that by using a factory function, but that is not possible as extensions are identified by their import name. The correct way to configure the extension is storing the configuration values on the environment. Because this way the environment ends up acting as central configuration storage the attributes may clash which is why extensions have to ensure that the names they choose for configuration are not too generic. ``prefix`` for example is a terrible name, ``fragment_cache_prefix`` on the other hand is a good name as includes the name of the extension (fragment cache). """ #: if this extension parses this is the list of tags it's listening to. tags = set() #: the priority of that extension. This is especially useful for #: extensions that preprocess values. A lower value means higher #: priority. #: #: .. versionadded:: 2.4 priority = 100 def __init__(self, environment): self.environment = environment def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv def preprocess(self, source, name, filename=None): """This method is called before the actual lexing and can be used to preprocess the source. The `filename` is optional. The return value must be the preprocessed source. """ return source def filter_stream(self, stream): """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used to filter tokens returned. This method has to return an iterable of :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a :class:`~jinja2.lexer.TokenStream`. In the `ext` folder of the Jinja2 source distribution there is a file called `inlinegettext.py` which implements a filter that utilizes this method. """ return stream def parse(self, parser): """If any of the :attr:`tags` matched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes. """ raise NotImplementedError() def attr(self, name, lineno=None): """Return an attribute node for the current extension. This is useful to pass constants on extensions to generated template code. :: self.attr('_my_attribute', lineno=lineno) """ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno) def call_method(self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None): """Call a method of the extension. This is a shortcut for :meth:`attr` + :class:`jinja2.nodes.Call`. """ if args is None: args = [] if kwargs is None: kwargs = [] return nodes.Call(self.attr(name, lineno=lineno), args, kwargs, dyn_args, dyn_kwargs, lineno=lineno) @contextfunction def _gettext_alias(__context, *args, **kwargs): return __context.call(__context.resolve('gettext'), *args, **kwargs) def _make_new_gettext(func): @contextfunction def gettext(__context, __string, **variables): rv = __context.call(func, __string) if __context.eval_ctx.autoescape: rv = Markup(rv) return rv % variables return gettext def _make_new_ngettext(func): @contextfunction def ngettext(__context, __singular, __plural, __num, **variables): variables.setdefault('num', __num) rv = __context.call(func, __singular, __plural, __num) if __context.eval_ctx.autoescape: rv = Markup(rv) return rv % variables return ngettext class InternationalizationExtension(Extension): """This extension adds gettext support to Jinja2.""" tags = set(['trans']) # TODO: the i18n extension is currently reevaluating values in a few # situations. Take this example: # {% trans count=something() %}{{ count }} foo{% pluralize # %}{{ count }} fooss{% endtrans %} # something is called twice here. One time for the gettext value and # the other time for the n-parameter of the ngettext function. def __init__(self, environment): Extension.__init__(self, environment) environment.globals['_'] = _gettext_alias environment.extend( install_gettext_translations=self._install, install_null_translations=self._install_null, install_gettext_callables=self._install_callables, uninstall_gettext_translations=self._uninstall, extract_translations=self._extract, newstyle_gettext=False ) def _install(self, translations, newstyle=None): gettext = getattr(translations, 'ugettext', None) if gettext is None: gettext = translations.gettext ngettext = getattr(translations, 'ungettext', None) if ngettext is None: ngettext = translations.ngettext self._install_callables(gettext, ngettext, newstyle) def _install_null(self, newstyle=None): self._install_callables( lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle ) def _install_callables(self, gettext, ngettext, newstyle=None): if newstyle is not None: self.environment.newstyle_gettext = newstyle if self.environment.newstyle_gettext: gettext = _make_new_gettext(gettext) ngettext = _make_new_ngettext(ngettext) self.environment.globals.update( gettext=gettext, ngettext=ngettext ) def _uninstall(self, translations): for key in 'gettext', 'ngettext': self.environment.globals.pop(key, None) def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS): if isinstance(source, string_types): source = self.environment.parse(source) return extract_from_ast(source, gettext_functions) def parse(self, parser): """Parse a translatable tag.""" lineno = next(parser.stream).lineno num_called_num = False # find all the variables referenced. Additionally a variable can be # defined in the body of the trans block too, but this is checked at # a later state. plural_expr = None plural_expr_assignment = None variables = {} trimmed = None while parser.stream.current.type != 'block_end': if variables: parser.stream.expect('comma') # skip colon for python compatibility if parser.stream.skip_if('colon'): break name = parser.stream.expect('name') if name.value in variables: parser.fail('translatable variable %r defined twice.' % name.value, name.lineno, exc=TemplateAssertionError) # expressions if parser.stream.current.type == 'assign': next(parser.stream) variables[name.value] = var = parser.parse_expression() elif trimmed is None and name.value in ('trimmed', 'notrimmed'): trimmed = name.value == 'trimmed' continue else: variables[name.value] = var = nodes.Name(name.value, 'load') if plural_expr is None: if isinstance(var, nodes.Call): plural_expr = nodes.Name('_trans', 'load') variables[name.value] = plural_expr plural_expr_assignment = nodes.Assign( nodes.Name('_trans', 'store'), var) else: plural_expr = var num_called_num = name.value == 'num' parser.stream.expect('block_end') plural = None have_plural = False referenced = set() # now parse until endtrans or pluralize singular_names, singular = self._parse_block(parser, True) if singular_names: referenced.update(singular_names) if plural_expr is None: plural_expr = nodes.Name(singular_names[0], 'load') num_called_num = singular_names[0] == 'num' # if we have a pluralize block, we parse that too if parser.stream.current.test('name:pluralize'): have_plural = True next(parser.stream) if parser.stream.current.type != 'block_end': name = parser.stream.expect('name') if name.value not in variables: parser.fail('unknown variable %r for pluralization' % name.value, name.lineno, exc=TemplateAssertionError) plural_expr = variables[name.value] num_called_num = name.value == 'num' parser.stream.expect('block_end') plural_names, plural = self._parse_block(parser, False) next(parser.stream) referenced.update(plural_names) else: next(parser.stream) # register free names as simple name expressions for var in referenced: if var not in variables: variables[var] = nodes.Name(var, 'load') if not have_plural: plural_expr = None elif plural_expr is None: parser.fail('pluralize without variables', lineno) if trimmed is None: trimmed = self.environment.policies['ext.i18n.trimmed'] if trimmed: singular = self._trim_whitespace(singular) if plural: plural = self._trim_whitespace(plural) node = self._make_node(singular, plural, variables, plural_expr, bool(referenced), num_called_num and have_plural) node.set_lineno(lineno) if plural_expr_assignment is not None: return [plural_expr_assignment, node] else: return node def _trim_whitespace(self, string, _ws_re=re.compile(r'\s*\n\s*')): return _ws_re.sub(' ', string.strip()) def _parse_block(self, parser, allow_pluralize): """Parse until the next block tag with a given name.""" referenced = [] buf = [] while 1: if parser.stream.current.type == 'data': buf.append(parser.stream.current.value.replace('%', '%%')) next(parser.stream) elif parser.stream.current.type == 'variable_begin': next(parser.stream) name = parser.stream.expect('name').value referenced.append(name) buf.append('%%(%s)s' % name) parser.stream.expect('variable_end') elif parser.stream.current.type == 'block_begin': next(parser.stream) if parser.stream.current.test('name:endtrans'): break elif parser.stream.current.test('name:pluralize'): if allow_pluralize: break parser.fail('a translatable section can have only one ' 'pluralize section') parser.fail('control structures in translatable sections are ' 'not allowed') elif parser.stream.eos: parser.fail('unclosed translation block') else: assert False, 'internal parser error' return referenced, concat(buf) def _make_node(self, singular, plural, variables, plural_expr, vars_referenced, num_called_num): """Generates a useful node from the data provided.""" # no variables referenced? no need to escape for old style # gettext invocations only if there are vars. if not vars_referenced and not self.environment.newstyle_gettext: singular = singular.replace('%%', '%') if plural: plural = plural.replace('%%', '%') # singular only: if plural_expr is None: gettext = nodes.Name('gettext', 'load') node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None) # singular and plural else: ngettext = nodes.Name('ngettext', 'load') node = nodes.Call(ngettext, [ nodes.Const(singular), nodes.Const(plural), plural_expr ], [], None, None) # in case newstyle gettext is used, the method is powerful # enough to handle the variable expansion and autoescape # handling itself if self.environment.newstyle_gettext: for key, value in iteritems(variables): # the function adds that later anyways in case num was # called num, so just skip it. if num_called_num and key == 'num': continue node.kwargs.append(nodes.Keyword(key, value)) # otherwise do that here else: # mark the return value as safe if we are in an # environment with autoescaping turned on node = nodes.MarkSafeIfAutoescape(node) if variables: node = nodes.Mod(node, nodes.Dict([ nodes.Pair(nodes.Const(key), value) for key, value in variables.items() ])) return nodes.Output([node]) class ExprStmtExtension(Extension): """Adds a `do` tag to Jinja2 that works like the print statement just that it doesn't print the return value. """ tags = set(['do']) def parse(self, parser): node = nodes.ExprStmt(lineno=next(parser.stream).lineno) node.node = parser.parse_tuple() return node class LoopControlExtension(Extension): """Adds break and continue to the template engine.""" tags = set(['break', 'continue']) def parse(self, parser): token = next(parser.stream) if token.value == 'break': return nodes.Break(lineno=token.lineno) return nodes.Continue(lineno=token.lineno) class WithExtension(Extension): pass class AutoEscapeExtension(Extension): pass def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True): """Extract localizable strings from the given template node. Per default this function returns matches in babel style that means non string parameters as well as keyword arguments are returned as `None`. This allows Babel to figure out what you really meant if you are using gettext functions that allow keyword arguments for placeholder expansion. If you don't want that behavior set the `babel_style` parameter to `False` which causes only strings to be returned and parameters are always stored in tuples. As a consequence invalid gettext calls (calls without a single string parameter or string parameters after non-string parameters) are skipped. This example explains the behavior: >>> from jinja2 import Environment >>> env = Environment() >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}') >>> list(extract_from_ast(node)) [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))] >>> list(extract_from_ast(node, babel_style=False)) [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))] For every string found this function yields a ``(lineno, function, message)`` tuple, where: * ``lineno`` is the number of the line on which the string was found, * ``function`` is the name of the ``gettext`` function used (if the string was extracted from embedded Python code), and * ``message`` is the string itself (a ``unicode`` object, or a tuple of ``unicode`` objects for functions with multiple string arguments). This extraction function operates on the AST and is because of that unable to extract any comments. For comment support you have to use the babel extraction interface or extract comments yourself. """ for node in node.find_all(nodes.Call): if not isinstance(node.node, nodes.Name) or \ node.node.name not in gettext_functions: continue strings = [] for arg in node.args: if isinstance(arg, nodes.Const) and \ isinstance(arg.value, string_types): strings.append(arg.value) else: strings.append(None) for arg in node.kwargs: strings.append(None) if node.dyn_args is not None: strings.append(None) if node.dyn_kwargs is not None: strings.append(None) if not babel_style: strings = tuple(x for x in strings if x is not None) if not strings: continue else: if len(strings) == 1: strings = strings[0] else: strings = tuple(strings) yield node.lineno, node.node.name, strings class _CommentFinder(object): """Helper class to find comments in a token stream. Can only find comments for gettext calls forwards. Once the comment from line 4 is found, a comment for line 1 will not return a usable value. """ def __init__(self, tokens, comment_tags): self.tokens = tokens self.comment_tags = comment_tags self.offset = 0 self.last_lineno = 0 def find_backwards(self, offset): try: for _, token_type, token_value in \ reversed(self.tokens[self.offset:offset]): if token_type in ('comment', 'linecomment'): try: prefix, comment = token_value.split(None, 1) except ValueError: continue if prefix in self.comment_tags: return [comment.rstrip()] return [] finally: self.offset = offset def find_comments(self, lineno): if not self.comment_tags or self.last_lineno > lineno: return [] for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]): if token_lineno > lineno: return self.find_backwards(self.offset + idx) return self.find_backwards(len(self.tokens)) def babel_extract(fileobj, keywords, comment_tags, options): """Babel extraction method for Jinja templates. .. versionchanged:: 2.3 Basic support for translation comments was added. If `comment_tags` is now set to a list of keywords for extraction, the extractor will try to find the best preceeding comment that begins with one of the keywords. For best results, make sure to not have more than one gettext call in one line of code and the matching comment in the same line or the line before. .. versionchanged:: 2.5.1 The `newstyle_gettext` flag can be set to `True` to enable newstyle gettext calls. .. versionchanged:: 2.7 A `silent` option can now be provided. If set to `False` template syntax errors are propagated instead of being ignored. :param fileobj: the file-like object the messages should be extracted from :param keywords: a list of keywords (i.e. function names) that should be recognized as translation functions :param comment_tags: a list of translator tags to search for and include in the results. :param options: a dictionary of additional options (optional) :return: an iterator over ``(lineno, funcname, message, comments)`` tuples. (comments will be empty currently) """ extensions = set() for extension in options.get('extensions', '').split(','): extension = extension.strip() if not extension: continue extensions.add(import_string(extension)) if InternationalizationExtension not in extensions: extensions.add(InternationalizationExtension) def getbool(options, key, default=False): return options.get(key, str(default)).lower() in \ ('1', 'on', 'yes', 'true') silent = getbool(options, 'silent', True) environment = Environment( options.get('block_start_string', BLOCK_START_STRING), options.get('block_end_string', BLOCK_END_STRING), options.get('variable_start_string', VARIABLE_START_STRING), options.get('variable_end_string', VARIABLE_END_STRING), options.get('comment_start_string', COMMENT_START_STRING), options.get('comment_end_string', COMMENT_END_STRING), options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX, options.get('line_comment_prefix') or LINE_COMMENT_PREFIX, getbool(options, 'trim_blocks', TRIM_BLOCKS), getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS), NEWLINE_SEQUENCE, getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE), frozenset(extensions), cache_size=0, auto_reload=False ) if getbool(options, 'trimmed'): environment.policies['ext.i18n.trimmed'] = True if getbool(options, 'newstyle_gettext'): environment.newstyle_gettext = True source = fileobj.read().decode(options.get('encoding', 'utf-8')) try: node = environment.parse(source) tokens = list(environment.lex(environment.preprocess(source))) except TemplateSyntaxError as e: if not silent: raise # skip templates with syntax errors return finder = _CommentFinder(tokens, comment_tags) for lineno, func, message in extract_from_ast(node, keywords): yield lineno, func, message, finder.find_comments(lineno) #: nicer import names i18n = InternationalizationExtension do = ExprStmtExtension loopcontrols = LoopControlExtension with_ = WithExtension autoescape = AutoEscapeExtension
PypiClean
/2b2t.py-1.7.6.tar.gz/2b2t.py-1.7.6/py2b/listCheck.py
import requests from colorama import Fore, init import threading class listCheck(): def __init__(self, usernames, printOut=False): self.usernames = usernames self.printOut = printOut init(convert=True) def listBased(self, usernameList): for username in usernameList: self.check(username) def check(self, username): data = f'ign={username}' headers = { 'Content-Type': 'application/x-www-form-urlencoded' } request = requests.request('POST', "https://donate.2b2t.org/category/738999", data=data, headers=headers) if self.printOut: if 'rate limited' in request.text: print(Fore.LIGHTMAGENTA_EX + f"YOU'VE BEEN RATELIMITED!! :(") elif 'not a valid' in request.text: print(Fore.LIGHTRED_EX + f"{username} is not a valid username") elif 'Unable' in request.text: print(Fore.LIGHTRED_EX + f"Unable to find a player with the username: {input}") elif 'banned' not in request.text: print(Fore.LIGHTRED_EX + f"{username} is not currently banned") else: print(Fore.LIGHTGREEN_EX + f"{username} is currently banned") else: if 'rate limited' in request.text: return 0 elif 'not a valid' in request.text: return 1 elif 'Unable' in request.text: return 2 elif 'banned' not in request.text: return False else: return True def l1(self): for i in range(len(self.lines1)): self.check(self.lines1[i]) def l2(self): for i in range(len(self.lines2)): self.check(self.lines2[i]) def start(self): if self.usernames is list: self.listBased(self.usernames) else: self.lines = [item.replace("\n", "") for item in open(self.usernames, 'r').readlines()] self.lines1 = self.lines[:len(self.lines)//2] self.lines2 = self.lines[len(self.lines)//2:] self.threads = [] self.t1 = threading.Thread(target=self.l1) self.t2 = threading.Thread(target=self.l2) self.threads.append(self.t1) self.threads.append(self.t2) self.t1.start() self.t2.start() print(('\nFinished loading all threads.\n').center(119)) for x in self.threads: x.join() input(Fore.RESET + 'Finished Checking!')
PypiClean
/MTPPy-1.1.1-py3-none-any.whl/mtppy/procedure.py
import logging from mtppy.suc_data_assembly import * class Procedure(SUCServiceProcedure): def __init__(self, procedure_id: int, tag_name: str, tag_description: str = '', is_self_completing: bool = False, is_default: bool = False): """ Represents a procedure of a service. :param procedure_id: Procedure id. :param tag_name: Tag name of the procedure. :param tag_description: Tag description of the procedure. :param is_self_completing: Self-completing or not. :param is_default: Default or not. """ super().__init__(procedure_id, tag_name, tag_description, is_self_completing, is_default) self.procedure_parameters = {} self.process_value_ins = {} self.report_values = {} self.process_value_outs = {} def add_procedure_parameter(self, procedure_parameter: SUCOperationElement): """ Adds a procedure parameter to the procedure. :param procedure_parameter: Procedure parameter. :return: """ if isinstance(procedure_parameter, SUCOperationElement): self.procedure_parameters[procedure_parameter.tag_name] = procedure_parameter else: raise TypeError() def add_procedure_value_in(self, process_value_in): """ Adds an value in to the procedure. NOT IMPLEMENTED. :param process_value_in: Value in. :return: """ raise NotImplementedError() def add_report_value(self, report_value: SUCIndicatorElement): """ Adds a report value to the procedure. :param report_value: Report value. :return: """ if isinstance(report_value, SUCIndicatorElement): self.report_values[report_value.tag_name] = report_value else: raise TypeError() def add_procedure_value_out(self, process_value_out: SUCIndicatorElement): """ Adds an value out to the procedure. :param process_value_out: Value in. :return: """ if isinstance(process_value_out, SUCIndicatorElement): self.process_value_outs[process_value_out.tag_name] = process_value_out else: raise TypeError() def apply_procedure_parameters(self): """ Applies procedure parameters. :return: """ logging.debug('Applying procedure parameters') for procedure_parameter in self.procedure_parameters.values(): procedure_parameter.set_v_out()
PypiClean
/AstroAugmentations-0.1.0.tar.gz/AstroAugmentations-0.1.0/astroaugmentations/datasets/galaxy_mnist.py
import os from typing import Tuple, Any import torch import h5py import numpy as np from PIL import Image from sklearn import model_selection from torchvision.datasets.mnist import MNIST class GalaxyMNIST(MNIST): """`GalaxyMNIST <https://github.com/mwalmsley/galaxy_mnist>`_ Dataset. Based on MNIST/FashionMNIST torchvision datasets. Args: root (string): Root directory of dataset where ``GalaxyMNIST/raw/train_dataset.hdf5`` and ``GalaxyMNIST/raw/test_dataset.hdf5`` exist. train (bool, optional): If True, creates dataset from ``GalaxyMNIST/raw/train_dataset.hdf5``, otherwise from ``GalaxyMNIST/raw/test_dataset.hdf5``. download (bool, optional): If True, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again. transform (callable, optional): A function/transform that takes in an PIL image and returns a transformed version. E.g, ``transforms.RandomCrop`` target_transform (callable, optional): A function/transform that takes in the target and transforms it. """ # simply overrides mirrors, resources, classes mirrors = ["http://www.jb.man.ac.uk/research/MiraBest/MiraBest_F/"] # check_integrity will skip md5 check if None # don't bother with md5 until dataset definitely not changing? just set None # https://github.com/pytorch/vision/blob/main/torchvision/datasets/utils.py#L416 resources = [ ("train_dataset.hdf5.gz", None), # 'e408ae294e9b975482dc1abffeb373a6' ("test_dataset.hdf5.gz", None) ] classes = ["smooth_round", "smooth_cigar", "edge_on_disk", "unbarred_spiral"] def _check_legacy_exist(self): # GalaxyMNIST has no legacy data (yet). # Function exists for potential backwards compatibility only return False def _load_legacy_data(self): raise NotImplementedError( """ GalaxyMNIST has no legacy data (yet). Function exists for potential backwards compatibility only """ ) def _load_data(self): """ Reads the extracted {train/test}_dataset.hdf5. Each hdf5 includes both the images and labels - see read_dataset_file. This defines the canonical dataset (MNIST-style, as a standard reference) To make your own tweaks (e.g. set a different train-test split, use ``load_custom_data``) Returns: images: torch uint8 tensor like NCHW, 8000 train images or 2000 test images targets: torch uint64 tensor like N, 0-3 integer-encoded classes (see GalaxyMNIST.classes), similarly """ dataset_file = f"{'train' if self.train else 'test'}_dataset.hdf5" images, targets = read_dataset_file(os.path.join(self.raw_folder, dataset_file)) return images, targets def __getitem__(self, index: int) -> Tuple[Any, Any]: """ Copied from MNIST, except mode='P' not 'L' as it's RGB colour Args: index (int): Index Returns: tuple: (image, target) where target is index of the target class. """ img, target = self.data[index], int(self.targets[index]) # doing this so that it is consistent with all other datasets # to return a PIL Image img = Image.fromarray(img.numpy(), mode='RGB') if self.transform is not None: img = self.transform(image=img)['image'] if self.target_transform is not None: target = self.target_transform(image=target)['image'] return img, target def load_custom_data(self, test_size=0.2, stratify=False, random_state=42): """ Load GalaxyMNIST in a different way to the canonical GalaxyMNIST() (which is GalaxyMNIST._load_data()) Note - has no effect on GalaxyMNIST class itself e.g. self.data, self.targets, which are always canonical. Use as a pure function only. Args: test_size (float, optional): Select test size/fraction as per sklearn.model_selection.train_test_split. Defaults to 0.2. stratify (bool, optional): Force exactly even number of classes between splits. Defaults to False. Returns: (torch.tensor, torch.tensor): train dataset of labels and images like (NCHW, N), same format as self._load_data() (torch.tensor, torch.tensor): test dataset of labels and images like (NCHW, N), same format as self._load_data() """ # mnist init uses self.train to control _load_data, so need to modify self.train # need to do some bookkeeping to set it back afterwards prev_self_train_state = self.train # bool is always ref-by-value self.train = True canonical_train_images, canonical_train_targets = self._load_data() self.train = False canonical_test_images, canonical_test_targets = self._load_data() all_images = torch.cat([canonical_train_images, canonical_test_images], axis=0) all_labels = torch.cat([canonical_train_targets, canonical_test_targets], axis=0) self.train = prev_self_train_state # set self.train back how it was # print(all_images.shape, all_labels.shape) if stratify: split_indices = model_selection.StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=random_state).split(X=all_images, y=all_labels) train_indices, test_indices = list(split_indices)[0] train_images, train_labels, test_images, test_labels = all_images[train_indices], all_labels[train_indices], all_images[test_indices], all_labels[test_indices] else: train_images, train_labels, test_images, test_labels = model_selection.train_test_split(all_images, all_labels, test_size=test_size) if self.train: self.data, self.targets = (train_images, train_labels) else: self.data, self.targets = (test_images, test_labels) return (train_images, train_labels), (test_images, test_labels) def read_dataset_file(path: str) -> torch.Tensor: """ Read an hdf5 file containing galaxy images (under ``images`` and integer-encoded labels (under ``labels``) Args: path (str): path to read from (e.g. root/galaxyMNIST/train_dataset.hdf5) Returns: torch.Tensor: galaxy images, torch uint8 tensor like NCHW torch.Tensor: torch uint64 tensor like N, 0-3 integer-encoded classes (see GalaxyMNIST.classes), similarly """ with h5py.File(path, 'r') as f: images = f['images'][:] # images are saved as NHWC convention # (numpy/matplotlib being the tiebreaker for pytorch vs tensorflow) # reorder axis to NCHW for pytorch convention images = torch.from_numpy(images).type(torch.uint8).permute(0, 3, 1, 2) assert images.ndimension() == 4 targets = f['labels'][:] # integer-encoded (from 0) according to GalaxyMNIST.classes targets = torch.from_numpy(targets).type(torch.int64) # dtype consistent with mnist (same as tensor.long()) assert targets.ndimension() == 1 return images, targets # TODO optionally, download or write jpgs?
PypiClean
/AreaCode-1.0.0.tar.gz/AreaCode-1.0.0/ChinaArea/AreaCode.py
__CHINA_AREA__ = [ {"parent_id": "N1", "children": [ {"parent_id": "P34", "children": [ {"parent_id": "C2", "children": [ {"parent_id": "D14", "children": [], "type": "A", "id": "A2712", "name": "南京东路"}, {"parent_id": "D14", "children": [], "type": "A", "id": "A1534", "name": "董家渡"}, {"parent_id": "D14", "children": [], "type": "A", "id": "A183", "name": "城隍庙"}, {"parent_id": "D14", "children": [], "type": "A", "id": "A2229", "name": "老西门"}, {"parent_id": "D14", "children": [], "type": "A", "id": "A3130", "name": "人民广场"}, {"parent_id": "D14", "children": [], "type": "A", "id": "A3486", "name": "外滩"}], "type": "D", "id": "D14", "name": "黄浦区"}, {"parent_id": "C2", "children": [ {"parent_id": "D15", "children": [], "type": "A", "id": "A2713", "name": "嘉定镇"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A1535", "name": "丰庄/沃尔玛/嘉尚坊"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A2230", "name": "黄渡镇"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A184", "name": "博乐广场/罗宾森广场"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A4", "name": "安亭"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A4066", "name": "马陆镇"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A3793", "name": "戬浜镇"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A3131", "name": "江桥"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A4301", "name": "南翔"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A199", "name": "新源路"}, {"parent_id": "D15", "children": [], "type": "A", "id": "A3487", "name": "江桥万达广场"}], "type": "D", "id": "D15", "name": "嘉定区"}, {"parent_id": "C2", "children": [ {"parent_id": "D16", "children": [], "type": "A", "id": "A2714", "name": "同乐坊"}, {"parent_id": "D16", "children": [], "type": "A", "id": "A1536", "name": "静安寺"}, {"parent_id": "D16", "children": [], "type": "A", "id": "A2231", "name": "南京西路"}, {"parent_id": "D16", "children": [], "type": "A", "id": "A185", "name": "曹家渡"}], "type": "D", "id": "D16", "name": "静安区"}, {"parent_id": "C2", "children": [ {"parent_id": "D17", "children": [], "type": "A", "id": "A2715", "name": "蒙山路"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A1537", "name": "金山新城"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A2232", "name": "金山嘴"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A186", "name": "百联金山购物中心"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A4067", "name": "朱泾镇"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A3794", "name": "卫零路"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A3132", "name": "石化"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A4302", "name": "朱行镇"}, {"parent_id": "D17", "children": [], "type": "A", "id": "A3488", "name": "卫清路"}], "type": "D", "id": "D17", "name": "金山区"}, {"parent_id": "C2", "children": [ {"parent_id": "D10", "children": [], "type": "A", "id": "A1530", "name": "动物园/虹桥机场"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A3127", "name": "上海影城/新华路"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A2709", "name": "虹桥"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A179", "name": "北新泾"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A2226", "name": "古北"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A3790", "name": "中山公园"}, {"parent_id": "D10", "children": [], "type": "A", "id": "A3483", "name": "天山"}], "type": "D", "id": "D10", "name": "长宁区"}, {"parent_id": "C2", "children": [ {"parent_id": "D11", "children": [], "type": "A", "id": "A1531", "name": "南门"}, {"parent_id": "D11", "children": [], "type": "A", "id": "A180", "name": "堡镇"}], "type": "D", "id": "D11", "name": "崇明县"}, {"parent_id": "C2", "children": [ {"parent_id": "D12", "children": [], "type": "A", "id": "A2710", "name": "南桥镇"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A1532", "name": "海湾旅游区"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A181", "name": "奉城镇"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A3128", "name": "南桥百联购物中心"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A3", "name": "易买得"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A2227", "name": "环城东路"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A4064", "name": "南港路/正阳世纪星城"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A3791", "name": "南桥新都汇"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A4300", "name": "西渡镇"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A198", "name": "庄行镇"}, {"parent_id": "D12", "children": [], "type": "A", "id": "A3484", "name": "南桥新城区"}], "type": "D", "id": "D12", "name": "奉贤区"}, {"parent_id": "C2", "children": [ {"parent_id": "D13", "children": [], "type": "A", "id": "A2711", "name": "凉城/江湾镇"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A1533", "name": "虹口龙之梦"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A182", "name": "北外滩"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A3129", "name": "临平路/和平公园"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A2228", "name": "海宁路/七浦路"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A4065", "name": "四川北路"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A3792", "name": "曲阳地区"}, {"parent_id": "D13", "children": [], "type": "A", "id": "A3485", "name": "鲁迅公园"}], "type": "D", "id": "D13", "name": "虹口区"}, {"parent_id": "C2", "children": [ {"parent_id": "D19", "children": [], "type": "A", "id": "A2717", "name": "虹梅路"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A1539", "name": "虹桥镇"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A904", "name": "颛桥/北桥"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A2234", "name": "华漕镇"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A430", "name": "吴泾镇"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A188", "name": "春申地区"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A5", "name": "浦江镇"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A587", "name": "莘庄"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A4068", "name": "万源城/东兰路"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A3795", "name": "龙柏地区"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A3134", "name": "交大闵行校区"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A4303", "name": "南方商城"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A3489", "name": "老闵行"}, {"parent_id": "D19", "children": [], "type": "A", "id": "A200", "name": "七宝"}], "type": "D", "id": "D19", "name": "闵行区"}, {"parent_id": "C2", "children": [ {"parent_id": "D18", "children": [], "type": "A", "id": "A2716", "name": "瑞金宾馆区"}, {"parent_id": "D18", "children": [], "type": "A", "id": "A1538", "name": "淮海路"}, {"parent_id": "D18", "children": [], "type": "A", "id": "A2233", "name": "日月光中心广场"}, {"parent_id": "D18", "children": [], "type": "A", "id": "A187", "name": "打浦桥"}, {"parent_id": "D18", "children": [], "type": "A", "id": "A3133", "name": "新天地"}], "type": "D", "id": "D18", "name": "卢湾区"}, {"parent_id": "C2", "children": [ {"parent_id": "D9", "children": [], "type": "A", "id": "A1529", "name": "大华地区"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A3789", "name": "美兰湖"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A3126", "name": "绿地风尚广场"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A2", "name": "通河/泗塘"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A2708", "name": "共富新村"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A178", "name": "宝山万达广场"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A4299", "name": "淞南/高境"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A586", "name": "月浦镇"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A2225", "name": "顾村公园"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A4063", "name": "上海大学"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A429", "name": "杨行镇"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A197", "name": "宝山城区/吴淞"}, {"parent_id": "D9", "children": [], "type": "A", "id": "A3482", "name": "庙行镇"}], "type": "D", "id": "D9", "name": "宝山区"}, {"parent_id": "C2", "children": [ {"parent_id": "D21", "children": [], "type": "A", "id": "A2719", "name": "武宁地区"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A2236", "name": "梅川路"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A4070", "name": "长风公园/华师大"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A3491", "name": "长寿路"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A1541", "name": "曹杨地区"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A3797", "name": "中山北路/甘泉地区"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A3136", "name": "月星环球港"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A4305", "name": "真如"}, {"parent_id": "D21", "children": [], "type": "A", "id": "A190", "name": "百联中环/绿洲中环"}], "type": "D", "id": "D21", "name": "普陀区"}, {"parent_id": "C2", "children": [ {"parent_id": "D20", "children": [], "type": "A", "id": "A905", "name": "世纪公园"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A2718", "name": "川沙"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1490", "name": "源深体育中心"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A2235", "name": "碧云社区"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A431", "name": "陆家嘴"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A189", "name": "八佰伴"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A6", "name": "金桥商业广场"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A3490", "name": "惠南镇"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1394", "name": "外高桥"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1123", "name": "上南地区"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1331", "name": "塘桥"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A588", "name": "临港新城/泥城"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1540", "name": "北蔡"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1547", "name": "张江"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A4069", "name": "金桥"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1244", "name": "三林镇"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A3796", "name": "航头"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A3135", "name": "曹路"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A4304", "name": "金杨地区"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A1438", "name": "新场"}, {"parent_id": "D20", "children": [], "type": "A", "id": "A201", "name": "康桥/周浦"}], "type": "D", "id": "D20", "name": "浦东新区"}, {"parent_id": "C2", "children": [ {"parent_id": "D23", "children": [], "type": "A", "id": "A2238", "name": "江学路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A4071", "name": "松江镇"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A432", "name": "泰晤士小镇"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A7", "name": "松东路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A3492", "name": "荣乐中路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A906", "name": "新松江路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A1124", "name": "泗泾镇"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A2721", "name": "开元地中海"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A589", "name": "新桥"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A1543", "name": "九亭"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A1245", "name": "中山中路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A3798", "name": "人民北路"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A3138", "name": "鹿都国际商业广场"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A4306", "name": "松江大学城"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A192", "name": "飞航广场"}, {"parent_id": "D23", "children": [], "type": "A", "id": "A202", "name": "佘山"}], "type": "D", "id": "D23", "name": "松江区"}, {"parent_id": "C2", "children": [ {"parent_id": "D22", "children": [], "type": "A", "id": "A2237", "name": "青浦城区"}, {"parent_id": "D22", "children": [], "type": "A", "id": "A2720", "name": "朱家角"}, {"parent_id": "D22", "children": [], "type": "A", "id": "A1542", "name": "华新镇"}, {"parent_id": "D22", "children": [], "type": "A", "id": "A3137", "name": "赵巷镇"}, {"parent_id": "D22", "children": [], "type": "A", "id": "A191", "name": "重固镇"}], "type": "D", "id": "D22", "name": "青浦区"}, {"parent_id": "C2", "children": [ {"parent_id": "D25", "children": [], "type": "A", "id": "A2723", "name": "五角场/大学区"}, {"parent_id": "D25", "children": [], "type": "A", "id": "A1545", "name": "控江地区"}, {"parent_id": "D25", "children": [], "type": "A", "id": "A194", "name": "黄兴公园"}, {"parent_id": "D25", "children": [], "type": "A", "id": "A2240", "name": "平凉路"}, {"parent_id": "D25", "children": [], "type": "A", "id": "A3140", "name": "中原地区"}], "type": "D", "id": "D25", "name": "杨浦区"}, {"parent_id": "C2", "children": [ {"parent_id": "D24", "children": [], "type": "A", "id": "A2239", "name": "光启城"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A4072", "name": "徐家汇"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A8", "name": "肇嘉浜路沿线"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A3493", "name": "万体馆"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A2722", "name": "衡山路"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A1544", "name": "复兴西路/丁香花园"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A3799", "name": "上海南站"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A3139", "name": "龙华"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A4307", "name": "音乐学院"}, {"parent_id": "D24", "children": [], "type": "A", "id": "A193", "name": "漕河泾/田林"}], "type": "D", "id": "D24", "name": "徐汇区"}, {"parent_id": "C2", "children": [ {"parent_id": "D26", "children": [], "type": "A", "id": "A4073", "name": "上海大学"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A2241", "name": "大悦城"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A9", "name": "西藏北路/中兴路"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A3494", "name": "彭浦镇"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A2724", "name": "火车站"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A3800", "name": "市北工业园/汶水路"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A1546", "name": "大宁国际"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A4308", "name": "盛源生活广场"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A195", "name": "北区汽车站"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A3141", "name": "彭浦新村"}, {"parent_id": "D26", "children": [], "type": "A", "id": "A203", "name": "闸北公园"}], "type": "D", "id": "D26", "name": "闸北区"}], "type": "C", "id": "C2", "name": "上海"}], "type": "P", "id": "P34", "name": "上海"}, {"parent_id": "N1", "children": [ {"parent_id": "P1", "children": [ {"parent_id": "C1", "children": [], "type": "D", "id": "D138", "name": "门头沟"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D139", "name": "密云县"}, {"parent_id": "C1", "children": [ {"parent_id": "D130", "children": [], "type": "A", "id": "A2274", "name": "回龙观"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A387", "name": "北七家"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A3165", "name": "沙河"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A3822", "name": "小汤山镇"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A1610", "name": "昌平镇"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A2751", "name": "南口镇"}, {"parent_id": "D130", "children": [], "type": "A", "id": "A3516", "name": "天通苑"}], "type": "D", "id": "D130", "name": "昌平区"}, {"parent_id": "C1", "children": [ {"parent_id": "D131", "children": [], "type": "A", "id": "A3823", "name": "北京东站"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A915", "name": "对外经贸"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1912", "name": "立水桥"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3097", "name": "悠唐生活广场"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2691", "name": "首都机场"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2313", "name": "双桥"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1495", "name": "高碑店"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2674", "name": "四惠"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2180", "name": "潘家园"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1703", "name": "建外大街"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A596", "name": "大望路"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1551", "name": "酒仙桥"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2804", "name": "望京"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A4090", "name": "朝外大街"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2212", "name": "三里屯"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2275", "name": "百子湾"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2043", "name": "蓝色港湾"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1252", "name": "东坝"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2785", "name": "甜水园"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3120", "name": "左家庄"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2243", "name": "三元桥"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1446", "name": "工体"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2509", "name": "十里堡"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3109", "name": "燕莎"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A20", "name": "朝阳公园"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3039", "name": "霄云路"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3166", "name": "八里庄"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1400", "name": "管庄"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A213", "name": "传媒大学"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2606", "name": "十里河"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2153", "name": "农业展览馆"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2701", "name": "太阳宫"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1611", "name": "北苑家园"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2725", "name": "团结湖"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1133", "name": "大屯"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2110", "name": "亮马桥"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1652", "name": "劲松"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A1337", "name": "国贸"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2687", "name": "四惠东"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2340", "name": "十八里店"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2648", "name": "石佛营"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2192", "name": "双井"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A441", "name": "常营"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2959", "name": "小营"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3076", "name": "亚运村"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3517", "name": "北沙滩"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A4322", "name": "朝阳大悦城"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A3112", "name": "姚家园"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A388", "name": "安贞"}, {"parent_id": "D131", "children": [], "type": "A", "id": "A2752", "name": "北京欢乐谷"}], "type": "D", "id": "D131", "name": "朝阳区"}, {"parent_id": "C1", "children": [ {"parent_id": "D132", "children": [], "type": "A", "id": "A2276", "name": "西红门"}, {"parent_id": "D132", "children": [], "type": "A", "id": "A389", "name": "黄村"}, {"parent_id": "D132", "children": [], "type": "A", "id": "A1612", "name": "旧宫"}, {"parent_id": "D132", "children": [], "type": "A", "id": "A2753", "name": "亦庄"}], "type": "D", "id": "D132", "name": "大兴区"}, {"parent_id": "C1", "children": [ {"parent_id": "D133", "children": [], "type": "A", "id": "A916", "name": "天坛"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A597", "name": "沙子口"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A4091", "name": "广渠门"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A2277", "name": "崇文门"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A1253", "name": "雍和宫"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A21", "name": "建国门/北京站"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A390", "name": "安定门"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A1134", "name": "王府井/东单"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A3167", "name": "东直门"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A214", "name": "南锣鼓巷"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A3824", "name": "东四"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A1613", "name": "北新桥/簋街"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A1338", "name": "左安门"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A442", "name": "前门/大栅栏"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A3518", "name": "东四十条"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A4323", "name": "和平里"}, {"parent_id": "D133", "children": [], "type": "A", "id": "A2754", "name": "朝阳门"}], "type": "D", "id": "D133", "name": "东城区"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D134", "name": "房山区"}, {"parent_id": "C1", "children": [ {"parent_id": "D135", "children": [], "type": "A", "id": "A917", "name": "洋桥/木樨园"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A598", "name": "夏家胡同/纪家庙"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A4092", "name": "北京南站/开阳里"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A2278", "name": "草桥/公益西桥"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A22", "name": "丽泽桥/丰管路"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A391", "name": "北京西站/六里桥"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A3168", "name": "方庄/蒲黄榆"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A215", "name": "马家堡/角门"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A3825", "name": "看丹桥"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A1614", "name": "北大地/万丰路"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A443", "name": "青塔"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A3519", "name": "分钟寺/成寿寺"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A2755", "name": "大红门"}, {"parent_id": "D135", "children": [], "type": "A", "id": "A4324", "name": "刘家窑/宋家庄"}], "type": "D", "id": "D135", "name": "丰台区"}, {"parent_id": "C1", "children": [ {"parent_id": "D136", "children": [], "type": "A", "id": "A918", "name": "苏州桥"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1913", "name": "中关村"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1496", "name": "学院路"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1704", "name": "颐和园"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A599", "name": "双榆树"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1552", "name": "香山/植物园"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A4093", "name": "农业大学西区"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A3520", "name": "公主坟/万寿路"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A2279", "name": "北京大学"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A2044", "name": "紫竹桥"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1254", "name": "五棵松"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A23", "name": "人民大学"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A392", "name": "牡丹园/北太平庄"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A3169", "name": "大钟寺"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1401", "name": "万柳"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A216", "name": "上地"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A3826", "name": "航天桥"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1615", "name": "北下关"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1135", "name": "五道口"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A2111", "name": "知春路"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1653", "name": "远大路"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1339", "name": "魏公村"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A444", "name": "四季青"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A4325", "name": "清河"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A1451", "name": "西三旗"}, {"parent_id": "D136", "children": [], "type": "A", "id": "A2756", "name": "北京西站/军博"}], "type": "D", "id": "D136", "name": "海淀区"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D137", "name": "怀柔区"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D142", "name": "顺义区"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D145", "name": "延庆县"}, {"parent_id": "C1", "children": [ {"parent_id": "D141", "children": [], "type": "A", "id": "A393", "name": "古城/八角"}, {"parent_id": "D141", "children": [], "type": "A", "id": "A1616", "name": "鲁谷"}, {"parent_id": "D141", "children": [], "type": "A", "id": "A2757", "name": "苹果园"}, {"parent_id": "D141", "children": [], "type": "A", "id": "A2280", "name": "模式口"}], "type": "D", "id": "D141", "name": "石景山区"}, {"parent_id": "C1", "children": [], "type": "D", "id": "D140", "name": "平谷区"}, {"parent_id": "C1", "children": [ {"parent_id": "D143", "children": [], "type": "A", "id": "A3521", "name": "新华大街"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A394", "name": "果园"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A3827", "name": "新华联"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A1617", "name": "九棵树"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A3170", "name": "武夷花园"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A2758", "name": "通州北苑"}, {"parent_id": "D143", "children": [], "type": "A", "id": "A2281", "name": "梨园"}], "type": "D", "id": "D143", "name": "通州区"}, {"parent_id": "C1", "children": [ {"parent_id": "D144", "children": [], "type": "A", "id": "A919", "name": "新街口"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A1340", "name": "月坛/金融街"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A4094", "name": "后海/什刹海"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A3522", "name": "广外大街"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A1255", "name": "西四"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A24", "name": "牛街"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A395", "name": "菜市口/陶然亭"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A1402", "name": "右安门"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A217", "name": "前门/大栅栏"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A3828", "name": "广内大街"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A1618", "name": "德外大街"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A1136", "name": "宣武门"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A445", "name": "西单"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A4326", "name": "虎坊桥"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A600", "name": "西直门/动物园"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A3171", "name": "复兴门"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A2759", "name": "阜成门"}, {"parent_id": "D144", "children": [], "type": "A", "id": "A2282", "name": "地安门"}], "type": "D", "id": "D144", "name": "西城区"}], "type": "C", "id": "C1", "name": "北京"}], "type": "P", "id": "P1", "name": "北京"}, {"parent_id": "N1", "children": [ {"parent_id": "P3", "children": [], "type": "C", "id": "C119", "name": "丽水"}, {"parent_id": "P3", "children": [ {"parent_id": "C118", "children": [ {"parent_id": "D416", "children": [], "type": "A", "id": "A3609", "name": "院桥镇"}, {"parent_id": "D416", "children": [], "type": "A", "id": "A3270", "name": "北城区"}, {"parent_id": "D416", "children": [], "type": "A", "id": "A2413", "name": "南城区"}, {"parent_id": "D416", "children": [], "type": "A", "id": "A1789", "name": "东城区"}, {"parent_id": "D416", "children": [], "type": "A", "id": "A705", "name": "黄岩中心城区"}, {"parent_id": "D416", "children": [], "type": "A", "id": "A2873", "name": "西城区"}], "type": "D", "id": "D416", "name": "黄岩区"}, {"parent_id": "C118", "children": [ {"parent_id": "D417", "children": [], "type": "A", "id": "A3271", "name": "老城区"}, {"parent_id": "D417", "children": [], "type": "A", "id": "A2414", "name": "商业街"}, {"parent_id": "D417", "children": [], "type": "A", "id": "A1790", "name": "西商务区"}, {"parent_id": "D417", "children": [], "type": "A", "id": "A2874", "name": "十字马路"}, {"parent_id": "D417", "children": [], "type": "A", "id": "A706", "name": "东商务区"}], "type": "D", "id": "D417", "name": "椒江区"}, {"parent_id": "C118", "children": [ {"parent_id": "D422", "children": [], "type": "A", "id": "A2417", "name": "泽国镇"}, {"parent_id": "D422", "children": [], "type": "A", "id": "A1793", "name": "温岭市区"}, {"parent_id": "D422", "children": [], "type": "A", "id": "A709", "name": "九龙区"}, {"parent_id": "D422", "children": [], "type": "A", "id": "A2876", "name": "大溪镇"}], "type": "D", "id": "D422", "name": "温岭市"}, {"parent_id": "C118", "children": [], "type": "D", "id": "D423", "name": "仙居县"}, {"parent_id": "C118", "children": [], "type": "D", "id": "D420", "name": "三门县"}, {"parent_id": "C118", "children": [], "type": "D", "id": "D424", "name": "玉环县"}, {"parent_id": "C118", "children": [], "type": "D", "id": "D421", "name": "天台县"}, {"parent_id": "C118", "children": [ {"parent_id": "D419", "children": [], "type": "A", "id": "A3272", "name": "金清镇"}, {"parent_id": "D419", "children": [], "type": "A", "id": "A2416", "name": "国际塑料城"}, {"parent_id": "D419", "children": [], "type": "A", "id": "A1792", "name": "石浜公园"}, {"parent_id": "D419", "children": [], "type": "A", "id": "A708", "name": "富仕广场"}, {"parent_id": "D419", "children": [], "type": "A", "id": "A2875", "name": "会展中心"}], "type": "D", "id": "D419", "name": "路桥区"}, {"parent_id": "C118", "children": [ {"parent_id": "D418", "children": [], "type": "A", "id": "A2415", "name": "临海市区"}, {"parent_id": "D418", "children": [], "type": "A", "id": "A1791", "name": "杜桥镇"}, {"parent_id": "D418", "children": [], "type": "A", "id": "A707", "name": "大洋新区"}], "type": "D", "id": "D418", "name": "临海市"}], "type": "C", "id": "C118", "name": "台州"}, {"parent_id": "P3", "children": [ {"parent_id": "C117", "children": [ {"parent_id": "D415", "children": [], "type": "A", "id": "A701", "name": "嵊泗列岛"}], "type": "D", "id": "D415", "name": "嵊泗县"}, {"parent_id": "C117", "children": [ {"parent_id": "D414", "children": [], "type": "A", "id": "A3608", "name": "海华路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A4381", "name": "东港贸易城"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A2412", "name": "沈家门"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A281", "name": "沈家门渔港"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A980", "name": "碧海莲缘/欧尚"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A730", "name": "同济路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A1788", "name": "普陀山"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A1274", "name": "朱家尖"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A1170", "name": "渔市大街"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A3269", "name": "兴建路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A500", "name": "海州路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A4163", "name": "京汇广场/海天广场"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A3904", "name": "海莲路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A2872", "name": "国际水产城"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A72", "name": "海印路"}, {"parent_id": "D414", "children": [], "type": "A", "id": "A700", "name": "东海中路"}], "type": "D", "id": "D414", "name": "普陀区"}, {"parent_id": "C117", "children": [ {"parent_id": "D413", "children": [], "type": "A", "id": "A3607", "name": "体育路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A4380", "name": "教育学院"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1349", "name": "解放路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1169", "name": "环城东路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A2411", "name": "工农路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A280", "name": "昌国路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A699", "name": "港岛路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1574", "name": "中大街"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1469", "name": "人民南路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1787", "name": "人民中路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1273", "name": "芙蓉洲路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A499", "name": "文化路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A3268", "name": "乐购"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A4162", "name": "海天大道"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1505", "name": "海洋学院"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A3903", "name": "千岛海鲜美食广场"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A729", "name": "千岛路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A2871", "name": "海宇道"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A979", "name": "太平洋百货"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A71", "name": "环城南路"}, {"parent_id": "D413", "children": [], "type": "A", "id": "A1411", "name": "文化广场"}], "type": "D", "id": "D413", "name": "定海区"}, {"parent_id": "C117", "children": [], "type": "D", "id": "D412", "name": "岱山县"}], "type": "C", "id": "C117", "name": "舟山"}, {"parent_id": "P3", "children": [ {"parent_id": "C116", "children": [], "type": "D", "id": "D410", "name": "龙游县"}, {"parent_id": "C116", "children": [], "type": "D", "id": "D408", "name": "开化县"}, {"parent_id": "C116", "children": [ {"parent_id": "D409", "children": [], "type": "A", "id": "A2410", "name": "北区"}, {"parent_id": "D409", "children": [], "type": "A", "id": "A698", "name": "巨化区"}, {"parent_id": "D409", "children": [], "type": "A", "id": "A1786", "name": "西区"}, {"parent_id": "D409", "children": [], "type": "A", "id": "A3267", "name": "南区"}, {"parent_id": "D409", "children": [], "type": "A", "id": "A2870", "name": "市区"}], "type": "D", "id": "D409", "name": "柯城区"}, {"parent_id": "C116", "children": [], "type": "D", "id": "D407", "name": "江山市"}, {"parent_id": "C116", "children": [], "type": "D", "id": "D411", "name": "衢江区"}, {"parent_id": "C116", "children": [], "type": "D", "id": "D406", "name": "常山县"}], "type": "C", "id": "C116", "name": "衢州"}, {"parent_id": "P3", "children": [ {"parent_id": "C115", "children": [], "type": "D", "id": "D404", "name": "义乌市"}, {"parent_id": "C115", "children": [], "type": "D", "id": "D400", "name": "磐安县"}, {"parent_id": "C115", "children": [], "type": "D", "id": "D401", "name": "浦江县"}, {"parent_id": "C115", "children": [ {"parent_id": "D402", "children": [], "type": "A", "id": "A695", "name": "江南"}, {"parent_id": "D402", "children": [], "type": "A", "id": "A1783", "name": "江北"}], "type": "D", "id": "D402", "name": "婺城区"}, {"parent_id": "C115", "children": [ {"parent_id": "D405", "children": [], "type": "A", "id": "A3606", "name": "高镇商业区"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A1168", "name": "芝英镇"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A697", "name": "步行街"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A2869", "name": "大润发/老华联"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A1785", "name": "城东路"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A1272", "name": "总部中心"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A4379", "name": "龙川公园"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A498", "name": "五金城"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A978", "name": "香樟公园"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A279", "name": "望春东路"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A3266", "name": "东站"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A2409", "name": "长城工业区"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A4161", "name": "九铃中路"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A3902", "name": "古山镇"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A728", "name": "西站"}, {"parent_id": "D405", "children": [], "type": "A", "id": "A70", "name": "南苑路/农贸市场"}], "type": "D", "id": "D405", "name": "永康市"}, {"parent_id": "C115", "children": [ {"parent_id": "D403", "children": [], "type": "A", "id": "A696", "name": "白洋渡"}, {"parent_id": "D403", "children": [], "type": "A", "id": "A1784", "name": "桐琴镇"}], "type": "D", "id": "D403", "name": "武义县"}, {"parent_id": "C115", "children": [], "type": "D", "id": "D398", "name": "金东区"}, {"parent_id": "C115", "children": [], "type": "D", "id": "D399", "name": "兰溪市"}, {"parent_id": "C115", "children": [ {"parent_id": "D397", "children": [], "type": "A", "id": "A694", "name": "横店商圈"}, {"parent_id": "D397", "children": [], "type": "A", "id": "A1782", "name": "江南商圈"}, {"parent_id": "D397", "children": [], "type": "A", "id": "A2408", "name": "江北商圈"}], "type": "D", "id": "D397", "name": "东阳市"}], "type": "C", "id": "C115", "name": "金华"}, {"parent_id": "P3", "children": [ {"parent_id": "C114", "children": [ {"parent_id": "D391", "children": [], "type": "A", "id": "A3602", "name": "恒利菜场"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A690", "name": "百官"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A726", "name": "新大通"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A2865", "name": "财富大厦"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A4375", "name": "时代广场"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A495", "name": "文化广场"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A67", "name": "上虞江东路"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A976", "name": "新建路"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A276", "name": "万和城"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A3262", "name": "国际大酒店"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A2404", "name": "便民中心"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A1778", "name": "步行街"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A3898", "name": "江扬路"}, {"parent_id": "D391", "children": [], "type": "A", "id": "A4157", "name": "开发区"}], "type": "D", "id": "D391", "name": "上虞区"}, {"parent_id": "C114", "children": [ {"parent_id": "D392", "children": [], "type": "A", "id": "A3603", "name": "柯岩风景区"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A4158", "name": "明珠路"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A691", "name": "笛扬路"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A2866", "name": "鉴湖景园"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A4376", "name": "万达广场"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A3263", "name": "柯桥"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A2405", "name": "鉴湖路"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A1779", "name": "湖西路"}, {"parent_id": "D392", "children": [], "type": "A", "id": "A3899", "name": "蓝天市心广场"}], "type": "D", "id": "D392", "name": "绍兴县"}, {"parent_id": "C114", "children": [], "type": "D", "id": "D393", "name": "嵊州市"}, {"parent_id": "C114", "children": [], "type": "D", "id": "D394", "name": "新昌县"}, {"parent_id": "C114", "children": [ {"parent_id": "D395", "children": [], "type": "A", "id": "A1954", "name": "前观巷"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A3604", "name": "城东体育中心"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1167", "name": "火车站"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1348", "name": "后观巷"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2419", "name": "中兴南路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A4159", "name": "东街"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2182", "name": "塔山"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A692", "name": "城南"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2255", "name": "新建北路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1573", "name": "客运中心"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2213", "name": "咸亨新天地"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1468", "name": "解放北路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1800", "name": "袍江"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2867", "name": "城市广场"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1780", "name": "城东"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2065", "name": "人民路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1271", "name": "河山桥环岛"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A4377", "name": "大龙市场"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A496", "name": "府山西路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2540", "name": "中兴北路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A68", "name": "大滩"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A977", "name": "国际摩尔城"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2156", "name": "胜利西路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A277", "name": "迪荡新城"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A3264", "name": "仓桥直街"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2118", "name": "世茂广场"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1674", "name": "劳动路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2327", "name": "延安环岛"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2406", "name": "昌安立交桥"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1504", "name": "金时代广场"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A3900", "name": "大校场沿"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A727", "name": "府横街"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A1410", "name": "环城西路"}, {"parent_id": "D395", "children": [], "type": "A", "id": "A2204", "name": "投醪河"}], "type": "D", "id": "D395", "name": "越城区"}, {"parent_id": "C114", "children": [ {"parent_id": "D396", "children": [], "type": "A", "id": "A3605", "name": "江东路"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A693", "name": "大润发"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A2868", "name": "店口镇"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A1781", "name": "大唐"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A4378", "name": "三角广场"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A497", "name": "西施故里"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A69", "name": "三都镇"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A278", "name": "望云路"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A3265", "name": "郭家"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A2407", "name": "第一百货"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A4160", "name": "客运中心"}, {"parent_id": "D396", "children": [], "type": "A", "id": "A3901", "name": "暨阳路"}], "type": "D", "id": "D396", "name": "诸暨市"}], "type": "C", "id": "C114", "name": "绍兴"}, {"parent_id": "P3", "children": [ {"parent_id": "C113", "children": [ {"parent_id": "D389", "children": [], "type": "A", "id": "A3600", "name": "衣裳街/南街"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A1166", "name": "织里镇"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A2863", "name": "莲花庄"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A4374", "name": "星海名城"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A494", "name": "仁皇山"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A66", "name": "太湖路"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A275", "name": "太湖度假区"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A3260", "name": "湖东"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A688", "name": "市中心"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A2402", "name": "府庙"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A725", "name": "凤凰"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A1776", "name": "市陌"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A3897", "name": "米兰"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A975", "name": "加利广场"}, {"parent_id": "D389", "children": [], "type": "A", "id": "A4156", "name": "康城国际"}], "type": "D", "id": "D389", "name": "吴兴区"}, {"parent_id": "C113", "children": [], "type": "D", "id": "D388", "name": "南浔区"}, {"parent_id": "C113", "children": [], "type": "D", "id": "D387", "name": "安吉县"}, {"parent_id": "C113", "children": [], "type": "D", "id": "D386", "name": "德清县"}, {"parent_id": "C113", "children": [ {"parent_id": "D390", "children": [], "type": "A", "id": "A3601", "name": "金陵"}, {"parent_id": "D390", "children": [], "type": "A", "id": "A2864", "name": "古城街"}, {"parent_id": "D390", "children": [], "type": "A", "id": "A3261", "name": "北门"}, {"parent_id": "D390", "children": [], "type": "A", "id": "A2403", "name": "明珠路"}, {"parent_id": "D390", "children": [], "type": "A", "id": "A1777", "name": "轻纺城"}, {"parent_id": "D390", "children": [], "type": "A", "id": "A689", "name": "城西"}], "type": "D", "id": "D390", "name": "长兴县"}], "type": "C", "id": "C113", "name": "湖州"}, {"parent_id": "P3", "children": [ {"parent_id": "C112", "children": [], "type": "D", "id": "D383", "name": "平湖市"}, {"parent_id": "C112", "children": [ {"parent_id": "D382", "children": [], "type": "A", "id": "A1953", "name": "中核大厦"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1165", "name": "三水湾"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1347", "name": "旭辉广场"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A3258", "name": "华庭街"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1572", "name": "中山西路"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1467", "name": "友谊街"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A2861", "name": "放鹤洲"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1270", "name": "文化体育中心"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A4373", "name": "江南太阳城"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A493", "name": "欧尚"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1409", "name": "月河"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A65", "name": "梅湾街"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A274", "name": "南湖"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1673", "name": "中港城"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A2400", "name": "城北路"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A3598", "name": "火车站"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1503", "name": "中山东路"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A724", "name": "汽车西站"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1773", "name": "城南路"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A685", "name": "巴黎都市"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A3895", "name": "洪兴路"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A1799", "name": "紫阳街"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A974", "name": "汽车北站"}, {"parent_id": "D382", "children": [], "type": "A", "id": "A4154", "name": "吉水路"}], "type": "D", "id": "D382", "name": "南湖区"}, {"parent_id": "C112", "children": [ {"parent_id": "D381", "children": [], "type": "A", "id": "A3257", "name": "亭桥路"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A4153", "name": "西塘"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A3894", "name": "体育路"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A2399", "name": "人民大道"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A2860", "name": "市中心"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A3597", "name": "谈公路"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A1772", "name": "解放路"}, {"parent_id": "D381", "children": [], "type": "A", "id": "A684", "name": "晋阳路"}], "type": "D", "id": "D381", "name": "嘉善县"}, {"parent_id": "C112", "children": [], "type": "D", "id": "D380", "name": "海盐县"}, {"parent_id": "C112", "children": [ {"parent_id": "D385", "children": [], "type": "A", "id": "A1775", "name": "金都景苑"}, {"parent_id": "D385", "children": [], "type": "A", "id": "A687", "name": "江南摩尔"}], "type": "D", "id": "D385", "name": "秀洲区"}, {"parent_id": "C112", "children": [ {"parent_id": "D384", "children": [], "type": "A", "id": "A3896", "name": "沃尔玛"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A3259", "name": "市政府"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A2862", "name": "庆丰南路"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A2401", "name": "庆丰北路"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A3599", "name": "乌镇"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A1774", "name": "复兴路"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A4155", "name": "濮院"}, {"parent_id": "D384", "children": [], "type": "A", "id": "A686", "name": "东兴"}], "type": "D", "id": "D384", "name": "桐乡市"}, {"parent_id": "C112", "children": [ {"parent_id": "D379", "children": [], "type": "A", "id": "A3256", "name": "皮革城"}, {"parent_id": "D379", "children": [], "type": "A", "id": "A2398", "name": "工人路步行街"}, {"parent_id": "D379", "children": [], "type": "A", "id": "A3596", "name": "银泰城"}, {"parent_id": "D379", "children": [], "type": "A", "id": "A1771", "name": "东山"}, {"parent_id": "D379", "children": [], "type": "A", "id": "A683", "name": "百合新城"}, {"parent_id": "D379", "children": [], "type": "A", "id": "A2859", "name": "火车站"}], "type": "D", "id": "D379", "name": "海宁市"}], "type": "C", "id": "C112", "name": "嘉兴"}, {"parent_id": "P3", "children": [ {"parent_id": "C111", "children": [], "type": "D", "id": "D369", "name": "洞头县"}, {"parent_id": "C111", "children": [], "type": "D", "id": "D368", "name": "苍南县"}, {"parent_id": "C111", "children": [], "type": "D", "id": "D378", "name": "乐清市"}, {"parent_id": "C111", "children": [ {"parent_id": "D372", "children": [], "type": "A", "id": "A1769", "name": "新桥"}, {"parent_id": "D372", "children": [], "type": "A", "id": "A680", "name": "大学城"}], "type": "D", "id": "D372", "name": "瓯海区"}, {"parent_id": "C111", "children": [], "type": "D", "id": "D373", "name": "平阳县"}, {"parent_id": "C111", "children": [ {"parent_id": "D370", "children": [], "type": "A", "id": "A1767", "name": "永中"}, {"parent_id": "D370", "children": [], "type": "A", "id": "A678", "name": "万达广场"}], "type": "D", "id": "D370", "name": "龙湾区"}, {"parent_id": "C111", "children": [ {"parent_id": "D371", "children": [], "type": "A", "id": "A1952", "name": "西山"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1164", "name": "汤家桥"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A3893", "name": "江滨东路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1346", "name": "望江路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A3255", "name": "江滨西路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A2397", "name": "黄龙"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1768", "name": "茶山"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1571", "name": "学院路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A679", "name": "车站大道"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1466", "name": "下吕浦"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A2064", "name": "银泰百货"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A4372", "name": "马鞍池"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A492", "name": "水心"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1408", "name": "吴桥路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A64", "name": "欧洲城"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A973", "name": "上陡门"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A273", "name": "蒲鞋市"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1672", "name": "信河街"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A3595", "name": "江心屿"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1502", "name": "新城"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A723", "name": "双屿"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A4152", "name": "鹿城路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A2858", "name": "锦绣路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1798", "name": "西城路"}, {"parent_id": "D371", "children": [], "type": "A", "id": "A1269", "name": "五马街/大南门"}], "type": "D", "id": "D371", "name": "鹿城区"}, {"parent_id": "C111", "children": [], "type": "D", "id": "D376", "name": "文成县"}, {"parent_id": "C111", "children": [ {"parent_id": "D377", "children": [], "type": "A", "id": "A682", "name": "瓯北"}], "type": "D", "id": "D377", "name": "永嘉县"}, {"parent_id": "C111", "children": [ {"parent_id": "D374", "children": [], "type": "A", "id": "A1770", "name": "塘下"}, {"parent_id": "D374", "children": [], "type": "A", "id": "A681", "name": "瑞安市区"}], "type": "D", "id": "D374", "name": "瑞安市"}, {"parent_id": "C111", "children": [], "type": "D", "id": "D375", "name": "泰顺县"}], "type": "C", "id": "C111", "name": "温州"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C135", "name": "嘉善"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C134", "name": "兰溪"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C137", "name": "安吉"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C136", "name": "海宁"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C131", "name": "瑞安"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C130", "name": "诸暨"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C133", "name": "桐乡"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C132", "name": "乐清"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C139", "name": "嵊泗"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C138", "name": "江山"}, {"parent_id": "P3", "children": [ {"parent_id": "C110", "children": [ {"parent_id": "D365", "children": [], "type": "A", "id": "A3253", "name": "联丰路沿线"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A3891", "name": "南部商务区"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A2394", "name": "联盛广场"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A1764", "name": "集士港"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A675", "name": "东钱湖"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A4370", "name": "鄞州万达广场"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A62", "name": "鄞奉路沿线"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A271", "name": "舟宿渡"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A3593", "name": "印象城/麦德龙"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A2855", "name": "利时百货"}, {"parent_id": "D365", "children": [], "type": "A", "id": "A4150", "name": "轻纺城"}], "type": "D", "id": "D365", "name": "鄞州区"}, {"parent_id": "C110", "children": [], "type": "D", "id": "D364", "name": "宁海县"}, {"parent_id": "C110", "children": [ {"parent_id": "D367", "children": [], "type": "A", "id": "A2396", "name": "骆驼街道"}, {"parent_id": "D367", "children": [], "type": "A", "id": "A1766", "name": "蛟川街道"}, {"parent_id": "D367", "children": [], "type": "A", "id": "A677", "name": "城关"}, {"parent_id": "D367", "children": [], "type": "A", "id": "A2857", "name": "庄市街道"}], "type": "D", "id": "D367", "name": "镇海区"}, {"parent_id": "C110", "children": [ {"parent_id": "D366", "children": [], "type": "A", "id": "A3892", "name": "泗门"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A3254", "name": "胜山路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A2395", "name": "富达广场"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A1765", "name": "东旱门路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A676", "name": "滨江路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A4371", "name": "文山路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A63", "name": "阳明西路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A272", "name": "舜大财富广场"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A3594", "name": "四明西路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A2856", "name": "南雷路"}, {"parent_id": "D366", "children": [], "type": "A", "id": "A4151", "name": "万达广场"}], "type": "D", "id": "D366", "name": "余姚市"}, {"parent_id": "C110", "children": [ {"parent_id": "D361", "children": [], "type": "A", "id": "A3251", "name": "宁波大学"}, {"parent_id": "D361", "children": [], "type": "A", "id": "A2392", "name": "来福士广场"}, {"parent_id": "D361", "children": [], "type": "A", "id": "A1761", "name": "江北万达广场"}, {"parent_id": "D361", "children": [], "type": "A", "id": "A672", "name": "大剧院"}, {"parent_id": "D361", "children": [], "type": "A", "id": "A3591", "name": "日湖公园"}, {"parent_id": "D361", "children": [], "type": "A", "id": "A2853", "name": "老外滩"}], "type": "D", "id": "D361", "name": "江北区"}, {"parent_id": "C110", "children": [ {"parent_id": "D360", "children": [], "type": "A", "id": "A3250", "name": "和义大道"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A2391", "name": "鼓楼"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A1760", "name": "翠柏路沿线"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A671", "name": "城隍庙"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A4368", "name": "西门口"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A60", "name": "月湖盛园"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A4148", "name": "天一广场"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A3590", "name": "南塘老街"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A2852", "name": "海曙欧尚"}, {"parent_id": "D360", "children": [], "type": "A", "id": "A3889", "name": "汽车南站"}], "type": "D", "id": "D360", "name": "海曙区"}, {"parent_id": "C110", "children": [ {"parent_id": "D363", "children": [], "type": "A", "id": "A1763", "name": "象山县"}, {"parent_id": "D363", "children": [], "type": "A", "id": "A674", "name": "奉化市"}], "type": "D", "id": "D363", "name": "近郊"}, {"parent_id": "C110", "children": [ {"parent_id": "D362", "children": [], "type": "A", "id": "A3890", "name": "宁波书城"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A3252", "name": "高新区"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A2393", "name": "儿童公园"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A1762", "name": "彩虹广场"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A673", "name": "滨江商业广场"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A491", "name": "兴宁时代广场"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A61", "name": "体育中心"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A270", "name": "兴宁路"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A4149", "name": "汽车东站"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A3592", "name": "和丰创意广场"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A2854", "name": "国际会展中心"}, {"parent_id": "D362", "children": [], "type": "A", "id": "A4369", "name": "世纪东方广场"}], "type": "D", "id": "D362", "name": "江东区"}, {"parent_id": "C110", "children": [], "type": "D", "id": "D358", "name": "北仑区"}, {"parent_id": "C110", "children": [ {"parent_id": "D359", "children": [], "type": "A", "id": "A59", "name": "孙塘街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A269", "name": "新城大道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A3589", "name": "坎墩街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A2390", "name": "古塘街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A670", "name": "白沙路街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A490", "name": "慈溪银泰城"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A3249", "name": "杭州湾新区"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A4147", "name": "上林坊"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A722", "name": "周巷"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A1759", "name": "观海卫"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A2851", "name": "浒山街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A4367", "name": "三北西大街"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A972", "name": "宗汉街道"}, {"parent_id": "D359", "children": [], "type": "A", "id": "A3888", "name": "青少年宫路"}], "type": "D", "id": "D359", "name": "慈溪市"}], "type": "C", "id": "C110", "name": "宁波"}, {"parent_id": "P3", "children": [ {"parent_id": "C314", "children": [], "type": "D", "id": "D929", "name": "富阳市"}, {"parent_id": "C314", "children": [ {"parent_id": "D928", "children": [], "type": "A", "id": "A2595", "name": "垃圾街"}, {"parent_id": "D928", "children": [], "type": "A", "id": "A1113", "name": "彩虹城"}, {"parent_id": "D928", "children": [], "type": "A", "id": "A3030", "name": "星光大道"}, {"parent_id": "D928", "children": [], "type": "A", "id": "A2030", "name": "开发区/高教园"}], "type": "D", "id": "D928", "name": "滨江区"}, {"parent_id": "C314", "children": [], "type": "D", "id": "D935", "name": "桐庐县"}, {"parent_id": "C314", "children": [ {"parent_id": "D934", "children": [], "type": "A", "id": "A2598", "name": "湖滨"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A3402", "name": "南山路"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A3721", "name": "平海路"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A3033", "name": "解放路沿线"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A1117", "name": "城站火车站"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A2034", "name": "复兴路沿线"}, {"parent_id": "D934", "children": [], "type": "A", "id": "A4004", "name": "吴山广场/河坊街"}], "type": "D", "id": "D934", "name": "上城区"}, {"parent_id": "C314", "children": [ {"parent_id": "D937", "children": [], "type": "A", "id": "A3404", "name": "恒隆广场"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A140", "name": "通惠路沿线"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A551", "name": "湘湖"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A361", "name": "闻堰"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A3723", "name": "加州阳光"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A2600", "name": "瓜沥镇"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A4251", "name": "市心南路"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A1119", "name": "北干"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A4458", "name": "市心北路"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A3035", "name": "国际机场"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A2036", "name": "城厢"}, {"parent_id": "D937", "children": [], "type": "A", "id": "A4006", "name": "临浦"}], "type": "D", "id": "D937", "name": "萧山区"}, {"parent_id": "C314", "children": [ {"parent_id": "D939", "children": [], "type": "A", "id": "A2602", "name": "塘栖"}, {"parent_id": "D939", "children": [], "type": "A", "id": "A1121", "name": "临平"}, {"parent_id": "D939", "children": [], "type": "A", "id": "A2038", "name": "老余杭"}], "type": "D", "id": "D939", "name": "余杭区"}, {"parent_id": "C314", "children": [ {"parent_id": "D930", "children": [], "type": "A", "id": "A4249", "name": "莫干山路"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A2596", "name": "大关"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A3400", "name": "德胜路沿线"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A4456", "name": "信义坊"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A1114", "name": "北景园/半山"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A138", "name": "运河广场"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A3719", "name": "拱宸桥/上塘"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A3031", "name": "石祥路/沈半路沿线"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A2031", "name": "城西银泰城"}, {"parent_id": "D930", "children": [], "type": "A", "id": "A4002", "name": "湖墅南路"}], "type": "D", "id": "D930", "name": "拱墅区"}, {"parent_id": "C314", "children": [ {"parent_id": "D931", "children": [], "type": "A", "id": "A2597", "name": "艮山东路"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A3401", "name": "艮山路沿线"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A550", "name": "新塘路/秋涛路沿线"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A360", "name": "下沙"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A3720", "name": "九堡"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A4250", "name": "钱江新城"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A1115", "name": "城东"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A4457", "name": "四季青"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A139", "name": "天城路沿线"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A3032", "name": "艮山西路"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A2032", "name": "丁桥"}, {"parent_id": "D931", "children": [], "type": "A", "id": "A4003", "name": "凯旋路/机场路沿线"}], "type": "D", "id": "D931", "name": "江干区"}, {"parent_id": "C314", "children": [ {"parent_id": "D932", "children": [], "type": "A", "id": "A1116", "name": "淳安县"}, {"parent_id": "D932", "children": [], "type": "A", "id": "A2033", "name": "建德市"}], "type": "D", "id": "D932", "name": "近郊"}, {"parent_id": "C314", "children": [], "type": "D", "id": "D933", "name": "临安市"}, {"parent_id": "C314", "children": [ {"parent_id": "D936", "children": [], "type": "A", "id": "A2599", "name": "庆春路沿线"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A3403", "name": "武林广场"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A3722", "name": "延安路沿线"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A1118", "name": "凤起路沿线"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A3034", "name": "体育场路沿线"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A2035", "name": "建国路沿线"}, {"parent_id": "D936", "children": [], "type": "A", "id": "A4005", "name": "朝晖地区"}], "type": "D", "id": "D936", "name": "下城区"}, {"parent_id": "C314", "children": [ {"parent_id": "D938", "children": [], "type": "A", "id": "A4252", "name": "文一路沿线"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A3405", "name": "灵隐"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A141", "name": "万塘路"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A3724", "name": "三墩镇"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A1074", "name": "转塘"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A4459", "name": "文二路沿线"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A2601", "name": "教工路/学院路"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A1120", "name": "古墩路沿线"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A811", "name": "西城广场"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A3036", "name": "龙井/虎跑"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A2037", "name": "高新文教区"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A552", "name": "西溪"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A362", "name": "西湖北线/黄龙"}, {"parent_id": "D938", "children": [], "type": "A", "id": "A4007", "name": "文三路沿线"}], "type": "D", "id": "D938", "name": "西湖区"}], "type": "C", "id": "C314", "name": "杭州"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C128", "name": "临海"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C129", "name": "德清"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C122", "name": "慈溪"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C123", "name": "东阳"}, {"parent_id": "P3", "children": [ {"parent_id": "C120", "children": [], "type": "D", "id": "D428", "name": "稠江街道"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D429", "name": "大陈镇"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D426", "name": "城西街道"}, {"parent_id": "C120", "children": [ {"parent_id": "D427", "children": [], "type": "A", "id": "A2418", "name": "商贸城"}, {"parent_id": "D427", "children": [], "type": "A", "id": "A1794", "name": "贝村"}, {"parent_id": "D427", "children": [], "type": "A", "id": "A710", "name": "绣湖"}], "type": "D", "id": "D427", "name": "稠城街道"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D425", "name": "北苑街道"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D435", "name": "苏溪镇"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D434", "name": "上溪镇"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D436", "name": "义亭镇"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D431", "name": "后宅街道"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D430", "name": "佛堂镇"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D433", "name": "廿三里街道"}, {"parent_id": "C120", "children": [], "type": "D", "id": "D432", "name": "江东街道"}], "type": "C", "id": "C120", "name": "义乌"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C121", "name": "长兴"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C126", "name": "永康"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C127", "name": "余姚"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C124", "name": "上虞"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C125", "name": "温岭"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C140", "name": "宁海"}, {"parent_id": "P3", "children": [], "type": "C", "id": "C141", "name": "平湖"}], "type": "P", "id": "P3", "name": "浙江"}, {"parent_id": "N1", "children": [ {"parent_id": "P2", "children": [ {"parent_id": "C373", "children": [ {"parent_id": "D992", "children": [], "type": "A", "id": "A1215", "name": "虹悦城"}], "type": "D", "id": "D992", "name": "雨花台区"}, {"parent_id": "C373", "children": [ {"parent_id": "D990", "children": [], "type": "A", "id": "A2084", "name": "西站/中山码头"}, {"parent_id": "D990", "children": [], "type": "A", "id": "A1213", "name": "和燕路"}], "type": "D", "id": "D990", "name": "下关区"}, {"parent_id": "C373", "children": [ {"parent_id": "D215", "children": [], "type": "A", "id": "A1664", "name": "化工医院"}, {"parent_id": "D215", "children": [], "type": "A", "id": "A459", "name": "铁东"}, {"parent_id": "D215", "children": [], "type": "A", "id": "A2323", "name": "江北公园"}, {"parent_id": "D215", "children": [], "type": "A", "id": "A2792", "name": "龙潭区政府"}], "type": "D", "id": "D215", "name": "龙潭区"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D214", "name": "蛟河市"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D217", "name": "舒兰市"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D216", "name": "磐石市"}, {"parent_id": "C373", "children": [ {"parent_id": "D211", "children": [], "type": "A", "id": "A1662", "name": "珲春街"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A4111", "name": "冯家屯"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A3197", "name": "解放中路"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A3542", "name": "中东新生活"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A4339", "name": "临江门"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A230", "name": "河南街"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A457", "name": "大东门"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A3846", "name": "德胜门"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A2321", "name": "青岛街"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A466", "name": "光华路"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A2790", "name": "儿童公园"}, {"parent_id": "D211", "children": [], "type": "A", "id": "A34", "name": "长春路"}], "type": "D", "id": "D211", "name": "船营区"}, {"parent_id": "C373", "children": [ {"parent_id": "D210", "children": [], "type": "A", "id": "A1661", "name": "松江二厅"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A456", "name": "东市场"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A4110", "name": "昌邑区政府"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A3196", "name": "桃园广场"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A3541", "name": "财富广场"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A2789", "name": "天津街"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A3845", "name": "解放东路"}, {"parent_id": "D210", "children": [], "type": "A", "id": "A2320", "name": "解放北路"}], "type": "D", "id": "D210", "name": "昌邑区"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D213", "name": "桦甸市"}, {"parent_id": "C373", "children": [ {"parent_id": "D212", "children": [], "type": "A", "id": "A3198", "name": "新玛特"}, {"parent_id": "D212", "children": [], "type": "A", "id": "A1663", "name": "泰山路"}, {"parent_id": "D212", "children": [], "type": "A", "id": "A458", "name": "世纪广场"}, {"parent_id": "D212", "children": [], "type": "A", "id": "A2322", "name": "恒山路"}, {"parent_id": "D212", "children": [], "type": "A", "id": "A2791", "name": "厦门街"}], "type": "D", "id": "D212", "name": "丰满区"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D218", "name": "永吉县"}, {"parent_id": "C373", "children": [ {"parent_id": "D991", "children": [], "type": "A", "id": "A2085", "name": "紫金山/孝陵卫"}, {"parent_id": "D991", "children": [], "type": "A", "id": "A1214", "name": "火车站/玄武湖"}, {"parent_id": "D991", "children": [], "type": "A", "id": "A2629", "name": "珠江路沿线"}], "type": "D", "id": "D991", "name": "玄武区"}, {"parent_id": "C373", "children": [ {"parent_id": "D983", "children": [], "type": "A", "id": "A3422", "name": "三牌楼"}, {"parent_id": "D983", "children": [], "type": "A", "id": "A2623", "name": "南大/南师大"}, {"parent_id": "D983", "children": [], "type": "A", "id": "A3055", "name": "山西路/湖南路"}, {"parent_id": "D983", "children": [], "type": "A", "id": "A2078", "name": "鼓楼广场"}, {"parent_id": "D983", "children": [], "type": "A", "id": "A1207", "name": "草场门/龙江"}], "type": "D", "id": "D983", "name": "鼓楼区"}, {"parent_id": "C373", "children": [ {"parent_id": "D989", "children": [], "type": "A", "id": "A2083", "name": "马群街道"}, {"parent_id": "D989", "children": [], "type": "A", "id": "A1212", "name": "迈皋桥/和燕路"}, {"parent_id": "D989", "children": [], "type": "A", "id": "A2628", "name": "仙林大学城"}], "type": "D", "id": "D989", "name": "栖霞区"}, {"parent_id": "C373", "children": [ {"parent_id": "D988", "children": [], "type": "A", "id": "A2082", "name": "夫子庙地区"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A2627", "name": "苜蓿园"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A1211", "name": "常府街/长白街"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A3739", "name": "升州路/集庆路"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A3057", "name": "秦虹村/中华门"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A4020", "name": "新街口地区"}, {"parent_id": "D988", "children": [], "type": "A", "id": "A3424", "name": "瑞金路沿线"}], "type": "D", "id": "D988", "name": "秦淮区"}, {"parent_id": "C373", "children": [ {"parent_id": "D985", "children": [], "type": "A", "id": "A2080", "name": "建邺万达"}, {"parent_id": "D985", "children": [], "type": "A", "id": "A2625", "name": "莫愁湖/水西门"}, {"parent_id": "D985", "children": [], "type": "A", "id": "A1209", "name": "奥体中心"}], "type": "D", "id": "D985", "name": "建邺区"}, {"parent_id": "C373", "children": [ {"parent_id": "D984", "children": [], "type": "A", "id": "A2624", "name": "江宁万达"}, {"parent_id": "D984", "children": [], "type": "A", "id": "A3738", "name": "同曦商业圈"}, {"parent_id": "D984", "children": [], "type": "A", "id": "A3056", "name": "开发区"}, {"parent_id": "D984", "children": [], "type": "A", "id": "A3423", "name": "汤山镇"}, {"parent_id": "D984", "children": [], "type": "A", "id": "A2079", "name": "江宁大学城"}, {"parent_id": "D984", "children": [], "type": "A", "id": "A1208", "name": "东山镇"}], "type": "D", "id": "D984", "name": "江宁区"}, {"parent_id": "C373", "children": [], "type": "D", "id": "D987", "name": "浦口区"}, {"parent_id": "C373", "children": [ {"parent_id": "D986", "children": [], "type": "A", "id": "A2081", "name": "六合区"}, {"parent_id": "D986", "children": [], "type": "A", "id": "A2626", "name": "溧水县"}, {"parent_id": "D986", "children": [], "type": "A", "id": "A1210", "name": "高淳县"}], "type": "D", "id": "D986", "name": "近郊"}], "type": "C", "id": "C373", "name": "南京"}, {"parent_id": "P2", "children": [ {"parent_id": "C79", "children": [ {"parent_id": "D260", "children": [], "type": "A", "id": "A1950", "name": "新桥镇/高铁站"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1343", "name": "通江路"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1669", "name": "薛家"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1499", "name": "魏村"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A2357", "name": "常发广场"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1157", "name": "青龙"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1722", "name": "百丈镇"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A714", "name": "孟河"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A3566", "name": "飞龙路"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A4131", "name": "红梅"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A2820", "name": "道生中心"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1463", "name": "万达广场"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A965", "name": "每家玛"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A2061", "name": "西夏墅"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A4355", "name": "晋陵北路"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1405", "name": "太湖路"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A49", "name": "恐龙园"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A259", "name": "龙虎塘"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A3867", "name": "河海大学"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A3222", "name": "丰臣国际广场"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1796", "name": "新北中心公园"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1568", "name": "圩塘镇"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A1264", "name": "时代广场"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A481", "name": "罗溪镇"}, {"parent_id": "D260", "children": [], "type": "A", "id": "A620", "name": "奥体中心"}], "type": "D", "id": "D260", "name": "新北区"}, {"parent_id": "C79", "children": [ {"parent_id": "D261", "children": [], "type": "A", "id": "A50", "name": "清潭"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A260", "name": "青枫公园"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A2358", "name": "关河路"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A1723", "name": "广化街"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A715", "name": "吾悦国际广场"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A3567", "name": "莱蒙都会"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A4132", "name": "路桥"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A2821", "name": "怀德路"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A966", "name": "延陵西路"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A4356", "name": "南大街"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A3868", "name": "蓝天花园"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A3223", "name": "嘉业国贸"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A482", "name": "青山桥"}, {"parent_id": "D261", "children": [], "type": "A", "id": "A621", "name": "北大街"}], "type": "D", "id": "D261", "name": "钟楼区"}, {"parent_id": "C79", "children": [ {"parent_id": "D259", "children": [], "type": "A", "id": "A1342", "name": "牛塘镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1498", "name": "三勤生态园"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1795", "name": "新城上街"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2356", "name": "淹城"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1721", "name": "常武中路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2181", "name": "遥观镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A713", "name": "礼嘉镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A3565", "name": "广电路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A4130", "name": "横林镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1404", "name": "前黄镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1462", "name": "人民路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A964", "name": "鸣凰大学城"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2060", "name": "西太湖"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A619", "name": "奔牛镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A4354", "name": "横山桥镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1156", "name": "马杭镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2154", "name": "延政中路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A48", "name": "湟里镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1949", "name": "新天地"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A258", "name": "路劲又一城"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A3866", "name": "湖塘乐购"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2116", "name": "雪堰镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1668", "name": "万博生活广场"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A3221", "name": "古方路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2819", "name": "定安东路"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1567", "name": "吾悦广场"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A2203", "name": "邹区镇"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A1263", "name": "茂业百货"}, {"parent_id": "D259", "children": [], "type": "A", "id": "A480", "name": "兰陵欧尚"}], "type": "D", "id": "D259", "name": "武进区"}, {"parent_id": "C79", "children": [ {"parent_id": "D258", "children": [], "type": "A", "id": "A2355", "name": "火车站"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A1720", "name": "吊桥路"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A712", "name": "中吴大道"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A3564", "name": "晋陵中路"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A257", "name": "新闸"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A618", "name": "翠竹"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A4353", "name": "天宁寺"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A47", "name": "文化宫"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A479", "name": "延陵中路"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A3865", "name": "局前街"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A3220", "name": "和平路中路"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A4129", "name": "兰陵"}, {"parent_id": "D258", "children": [], "type": "A", "id": "A2818", "name": "和平路北路"}], "type": "D", "id": "D258", "name": "天宁区"}, {"parent_id": "C79", "children": [ {"parent_id": "D255", "children": [], "type": "A", "id": "A3218", "name": "金城"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A2352", "name": "华城二村"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A3562", "name": "市一中"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A615", "name": "北站/四中"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A3863", "name": "愚池"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A1717", "name": "城西"}, {"parent_id": "D255", "children": [], "type": "A", "id": "A2816", "name": "华中"}], "type": "D", "id": "D255", "name": "金坛市"}, {"parent_id": "C79", "children": [ {"parent_id": "D257", "children": [], "type": "A", "id": "A2354", "name": "戚大街"}, {"parent_id": "D257", "children": [], "type": "A", "id": "A617", "name": "河苑"}, {"parent_id": "D257", "children": [], "type": "A", "id": "A1719", "name": "潞城"}], "type": "D", "id": "D257", "name": "戚墅堰区"}, {"parent_id": "C79", "children": [ {"parent_id": "D256", "children": [], "type": "A", "id": "A3219", "name": "平陵广场"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A2353", "name": "罗湾路/南大街"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A3563", "name": "上河城/金鹰"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A616", "name": "大润发/锦汇广场"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A3864", "name": "市政府周边"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A1718", "name": "高静园"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A4128", "name": "天目湖"}, {"parent_id": "D256", "children": [], "type": "A", "id": "A2817", "name": "南山竹海"}], "type": "D", "id": "D256", "name": "溧阳市"}], "type": "C", "id": "C79", "name": "常州"}, {"parent_id": "P2", "children": [ {"parent_id": "C78", "children": [], "type": "D", "id": "D248", "name": "沛县"}, {"parent_id": "C78", "children": [], "type": "D", "id": "D249", "name": "邳州市"}, {"parent_id": "C78", "children": [], "type": "D", "id": "D246", "name": "贾汪区"}, {"parent_id": "C78", "children": [ {"parent_id": "D247", "children": [], "type": "A", "id": "A611", "name": "九龙湖"}], "type": "D", "id": "D247", "name": "九里区"}, {"parent_id": "C78", "children": [], "type": "D", "id": "D244", "name": "丰县"}, {"parent_id": "C78", "children": [ {"parent_id": "D245", "children": [], "type": "A", "id": "A3215", "name": "彭城一号"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A610", "name": "1818美食广场"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A3861", "name": "下淀邻里美食城"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A2349", "name": "夹河街"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A1714", "name": "金地国际"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A4126", "name": "杨庄生活广场"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A2813", "name": "彭城广场"}, {"parent_id": "D245", "children": [], "type": "A", "id": "A3559", "name": "西街"}], "type": "D", "id": "D245", "name": "鼓楼区"}, {"parent_id": "C78", "children": [], "type": "D", "id": "D251", "name": "睢宁县"}, {"parent_id": "C78", "children": [ {"parent_id": "D250", "children": [], "type": "A", "id": "A2350", "name": "富国街"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A3560", "name": "淮海西路"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A256", "name": "音乐主题街区"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A4352", "name": "西苑"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A612", "name": "滨湖"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A46", "name": "云龙湖"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A3862", "name": "建国西路"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A1715", "name": "段庄广场"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A4127", "name": "矿业大学"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A2814", "name": "凤鸣路"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A3216", "name": "公园壹号"}, {"parent_id": "D250", "children": [], "type": "A", "id": "A478", "name": "云龙山"}], "type": "D", "id": "D250", "name": "泉山区"}, {"parent_id": "C78", "children": [], "type": "D", "id": "D253", "name": "新沂市"}, {"parent_id": "C78", "children": [ {"parent_id": "D252", "children": [], "type": "A", "id": "A613", "name": "师范大学"}], "type": "D", "id": "D252", "name": "铜山新区"}, {"parent_id": "C78", "children": [ {"parent_id": "D254", "children": [], "type": "A", "id": "A2351", "name": "青年路"}, {"parent_id": "D254", "children": [], "type": "A", "id": "A3561", "name": "万达广场"}, {"parent_id": "D254", "children": [], "type": "A", "id": "A614", "name": "绿地世纪城"}, {"parent_id": "D254", "children": [], "type": "A", "id": "A1716", "name": "老东门"}, {"parent_id": "D254", "children": [], "type": "A", "id": "A2815", "name": "世茂广场"}, {"parent_id": "D254", "children": [], "type": "A", "id": "A3217", "name": "食品城"}], "type": "D", "id": "D254", "name": "云龙区"}], "type": "C", "id": "C78", "name": "徐州"}, {"parent_id": "P2", "children": [ {"parent_id": "C77", "children": [ {"parent_id": "D242", "children": [], "type": "A", "id": "A1712", "name": "丰汇欢乐广场"}, {"parent_id": "D242", "children": [], "type": "A", "id": "A608", "name": "东亭/东北塘"}], "type": "D", "id": "D242", "name": "锡山区"}, {"parent_id": "C77", "children": [ {"parent_id": "D243", "children": [], "type": "A", "id": "A3214", "name": "和桥/屺亭"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A477", "name": "张渚"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A45", "name": "新天地/太滆桥"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A255", "name": "现代生活广场/大润发"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A3860", "name": "金三角汽车站"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A2348", "name": "官林"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A1713", "name": "丁蜀"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A4351", "name": "万达及周边"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A4125", "name": "人民南路/森林公园"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A2812", "name": "环科园/城铁站"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A3558", "name": "家和花园/大润发"}, {"parent_id": "D243", "children": [], "type": "A", "id": "A609", "name": "步行街/市中心"}], "type": "D", "id": "D243", "name": "宜兴市"}, {"parent_id": "C77", "children": [ {"parent_id": "D240", "children": [], "type": "A", "id": "A3212", "name": "清扬路"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A3858", "name": "新天地广场"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A606", "name": "东林书院"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A44", "name": "招商城"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A2346", "name": "南长街"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A1710", "name": "南禅寺"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A4123", "name": "阳光广场"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A2810", "name": "清扬路沿线"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A3556", "name": "西水东广场"}, {"parent_id": "D240", "children": [], "type": "A", "id": "A4349", "name": "中桥/芦庄"}], "type": "D", "id": "D240", "name": "南长区"}, {"parent_id": "C77", "children": [ {"parent_id": "D241", "children": [], "type": "A", "id": "A3213", "name": "梅村"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A3859", "name": "旺庄"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A607", "name": "宝龙城市广场"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A2347", "name": "坊前/春潮"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A1711", "name": "长江北路沿线"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A4350", "name": "新之城广场"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A4124", "name": "新地假日广场"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A2811", "name": "新区哥伦布广场"}, {"parent_id": "D241", "children": [], "type": "A", "id": "A3557", "name": "硕放"}], "type": "D", "id": "D241", "name": "新区"}, {"parent_id": "C77", "children": [ {"parent_id": "D239", "children": [], "type": "A", "id": "A3211", "name": "天鹤小区"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A3857", "name": "新一城"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A1709", "name": "花园新村"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A254", "name": "中山公园"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A2809", "name": "江阴市中"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A43", "name": "一中初中部"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A2345", "name": "黄山湖公园"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A4122", "name": "希望广场"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A3555", "name": "万达广场"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A605", "name": "东门"}, {"parent_id": "D239", "children": [], "type": "A", "id": "A4348", "name": "新百业广场"}], "type": "D", "id": "D239", "name": "江阴市"}, {"parent_id": "C77", "children": [ {"parent_id": "D238", "children": [], "type": "A", "id": "A3856", "name": "玉祁"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A3210", "name": "钱桥"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A1708", "name": "惠山万达广场"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A476", "name": "阳山"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A2808", "name": "藕塘"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A604", "name": "长安"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A42", "name": "堰桥"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A253", "name": "杨市"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A2344", "name": "洛社"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A4121", "name": "时代广场"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A3554", "name": "前洲"}, {"parent_id": "D238", "children": [], "type": "A", "id": "A4347", "name": "西漳"}], "type": "D", "id": "D238", "name": "惠山区"}, {"parent_id": "C77", "children": [ {"parent_id": "D237", "children": [], "type": "A", "id": "A3855", "name": "汇金广场/八佰伴"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A1707", "name": "保利广场"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A475", "name": "中华美食城"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A2807", "name": "大成巷/东方广场"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A603", "name": "1912酒吧街"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A41", "name": "远东百货/胜利门"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A252", "name": "中山路"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A3209", "name": "哥伦布广场"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A2343", "name": "崇安寺"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A4120", "name": "恒隆广场"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A3553", "name": "火车站/上马墩/广瑞"}, {"parent_id": "D237", "children": [], "type": "A", "id": "A4346", "name": "苏宁广场"}], "type": "D", "id": "D237", "name": "崇安区"}, {"parent_id": "C77", "children": [ {"parent_id": "D236", "children": [], "type": "A", "id": "A3854", "name": "梁清路"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A711", "name": "万科酩悦商业街"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A4119", "name": "梁溪路沿线"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A474", "name": "滨湖万达广场"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A2806", "name": "河埒口"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A1706", "name": "湖滨商业街"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A963", "name": "新体育中心/奥林花园"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A602", "name": "长广溪公园"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A40", "name": "落霞苑商业街"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A251", "name": "梅园"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A3208", "name": "华莱坞"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A2342", "name": "湖滨路"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A3552", "name": "江南大学城"}, {"parent_id": "D236", "children": [], "type": "A", "id": "A4345", "name": "蠡园/太湖景区"}], "type": "D", "id": "D236", "name": "滨湖区"}, {"parent_id": "C77", "children": [ {"parent_id": "D235", "children": [], "type": "A", "id": "A3853", "name": "五爱广场/五爱路"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A4118", "name": "运河公园"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A1705", "name": "惠山古镇"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A2805", "name": "民丰里"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A3207", "name": "青石路/北大街"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A2341", "name": "金太湖广场"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A3551", "name": "盛岸路沿线"}, {"parent_id": "D235", "children": [], "type": "A", "id": "A601", "name": "广石路沿线"}], "type": "D", "id": "D235", "name": "北塘区"}], "type": "C", "id": "C77", "name": "无锡"}, {"parent_id": "P2", "children": [ {"parent_id": "C80", "children": [ {"parent_id": "D262", "children": [], "type": "A", "id": "A2359", "name": "十全街/凤凰街"}, {"parent_id": "D262", "children": [], "type": "A", "id": "A1724", "name": "盘门"}, {"parent_id": "D262", "children": [], "type": "A", "id": "A2822", "name": "苏纶场"}, {"parent_id": "D262", "children": [], "type": "A", "id": "A3224", "name": "亿象城&世茂运河城"}, {"parent_id": "D262", "children": [], "type": "A", "id": "A622", "name": "南门"}], "type": "D", "id": "D262", "name": "沧浪区"}, {"parent_id": "C80", "children": [ {"parent_id": "D263", "children": [], "type": "A", "id": "A1725", "name": "京门"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A3568", "name": "虞景文华"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A2823", "name": "世茂"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A3869", "name": "招商城"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A3225", "name": "印象城"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A2360", "name": "美城广场"}, {"parent_id": "D263", "children": [], "type": "A", "id": "A623", "name": "方塔街"}], "type": "D", "id": "D263", "name": "常熟市"}, {"parent_id": "C80", "children": [ {"parent_id": "D264", "children": [], "type": "A", "id": "A3870", "name": "永利广场"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A1726", "name": "绿宝广场"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A3569", "name": "玉山路"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A3226", "name": "塔园路"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A2824", "name": "苏州乐园"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A2361", "name": "狮山地区"}, {"parent_id": "D264", "children": [], "type": "A", "id": "A624", "name": "枫桥地区"}], "type": "D", "id": "D264", "name": "高新区"}, {"parent_id": "C80", "children": [ {"parent_id": "D265", "children": [], "type": "A", "id": "A51", "name": "师惠坊"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A261", "name": "圆融时代广场"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A3871", "name": "玲珑湾"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A1727", "name": "独墅湖高教区"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A716", "name": "印象城"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A4133", "name": "邻瑞广场"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A2825", "name": "湖滨新天地"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A967", "name": "左岸商业街"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A3227", "name": "娄葑镇"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A2362", "name": "湖东邻里中心"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A3570", "name": "李公堤"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A4357", "name": "欧尚购物中心"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A483", "name": "月亮湾"}, {"parent_id": "D265", "children": [], "type": "A", "id": "A625", "name": "博览中心"}], "type": "D", "id": "D265", "name": "工业园区"}, {"parent_id": "C80", "children": [ {"parent_id": "D266", "children": [], "type": "A", "id": "A1728", "name": "通安镇"}, {"parent_id": "D266", "children": [], "type": "A", "id": "A626", "name": "浒关镇"}], "type": "D", "id": "D266", "name": "虎丘区"}, {"parent_id": "C80", "children": [ {"parent_id": "D267", "children": [], "type": "A", "id": "A3872", "name": "西城永捷"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A1729", "name": "虎丘景区"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A2826", "name": "阊胥路"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A3228", "name": "三香路沿线"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A2363", "name": "留园"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A3571", "name": "新苏天地"}, {"parent_id": "D267", "children": [], "type": "A", "id": "A627", "name": "石路地区"}], "type": "D", "id": "D267", "name": "金阊区"}, {"parent_id": "C80", "children": [], "type": "D", "id": "D268", "name": "昆山市"}, {"parent_id": "C80", "children": [ {"parent_id": "D269", "children": [], "type": "A", "id": "A3873", "name": "拙政园"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A2827", "name": "平江路"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A3229", "name": "苏州大学/相门后庄"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A1730", "name": "火车站"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A2364", "name": "景德路沿线"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A3572", "name": "万达广场"}, {"parent_id": "D269", "children": [], "type": "A", "id": "A628", "name": "观前街地区"}], "type": "D", "id": "D269", "name": "平江区"}, {"parent_id": "C80", "children": [ {"parent_id": "D273", "children": [], "type": "A", "id": "A3232", "name": "中环百汇广场"}, {"parent_id": "D273", "children": [], "type": "A", "id": "A632", "name": "采莲商业广场"}, {"parent_id": "D273", "children": [], "type": "A", "id": "A1734", "name": "华元路"}, {"parent_id": "D273", "children": [], "type": "A", "id": "A2368", "name": "新尚广场"}, {"parent_id": "D273", "children": [], "type": "A", "id": "A3575", "name": "中翔/家乐福"}, {"parent_id": "D273", "children": [], "type": "A", "id": "A2831", "name": "相城商业街"}], "type": "D", "id": "D273", "name": "相城区"}, {"parent_id": "C80", "children": [ {"parent_id": "D272", "children": [], "type": "A", "id": "A3875", "name": "吴中商城"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A3231", "name": "丽丰广场"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A4135", "name": "长桥地区"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A631", "name": "东吴北路"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A1733", "name": "SM广场"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A2367", "name": "花苑街"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A3574", "name": "木渎地区"}, {"parent_id": "D272", "children": [], "type": "A", "id": "A2830", "name": "金山路沿线"}], "type": "D", "id": "D272", "name": "吴中区"}, {"parent_id": "C80", "children": [ {"parent_id": "D271", "children": [], "type": "A", "id": "A3874", "name": "同里"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A4134", "name": "震泽"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A2829", "name": "平望"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A630", "name": "横扇"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A1732", "name": "芦墟"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A2366", "name": "黎里"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A3573", "name": "盛泽"}, {"parent_id": "D271", "children": [], "type": "A", "id": "A3230", "name": "松陵"}], "type": "D", "id": "D271", "name": "吴江区"}, {"parent_id": "C80", "children": [ {"parent_id": "D270", "children": [], "type": "A", "id": "A629", "name": "南洋广场"}, {"parent_id": "D270", "children": [], "type": "A", "id": "A2828", "name": "五洋广场"}, {"parent_id": "D270", "children": [], "type": "A", "id": "A1731", "name": "太平南路沿线"}, {"parent_id": "D270", "children": [], "type": "A", "id": "A2365", "name": "万达广场"}], "type": "D", "id": "D270", "name": "太仓市"}, {"parent_id": "C80", "children": [], "type": "D", "id": "D274", "name": "张家港市"}], "type": "C", "id": "C80", "name": "苏州"}, {"parent_id": "P2", "children": [ {"parent_id": "C81", "children": [], "type": "D", "id": "D277", "name": "海门市"}, {"parent_id": "C81", "children": [ {"parent_id": "D276", "children": [], "type": "A", "id": "A3234", "name": "越江路口"}, {"parent_id": "D276", "children": [], "type": "A", "id": "A2370", "name": "秦灶"}, {"parent_id": "D276", "children": [], "type": "A", "id": "A634", "name": "北大街"}, {"parent_id": "D276", "children": [], "type": "A", "id": "A1736", "name": "高店"}, {"parent_id": "D276", "children": [], "type": "A", "id": "A2833", "name": "唐闸"}], "type": "D", "id": "D276", "name": "港闸区"}, {"parent_id": "C81", "children": [ {"parent_id": "D275", "children": [], "type": "A", "id": "A52", "name": "虹桥"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A262", "name": "南大街"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1344", "name": "小石桥"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A3876", "name": "东景国际"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A3233", "name": "电视塔"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A717", "name": "轻纺城"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A4136", "name": "段家坝"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1464", "name": "新大润发"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A633", "name": "城山路"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A968", "name": "人民中路"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A4358", "name": "方天市场"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1406", "name": "新一佳"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1670", "name": "中南世纪城"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1735", "name": "城隍庙"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1500", "name": "友谊桥"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A2369", "name": "长江中路"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A3576", "name": "端平桥"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A2832", "name": "长途车站"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1158", "name": "体育公园"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1569", "name": "姚港路"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A1265", "name": "五一路"}, {"parent_id": "D275", "children": [], "type": "A", "id": "A484", "name": "圆融广场"}], "type": "D", "id": "D275", "name": "崇川区"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D279", "name": "开发区"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D278", "name": "海安县"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D282", "name": "如东县"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D283", "name": "如皋市"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D280", "name": "通州区"}, {"parent_id": "C81", "children": [], "type": "D", "id": "D281", "name": "启东市"}], "type": "C", "id": "C81", "name": "南通"}, {"parent_id": "P2", "children": [ {"parent_id": "C82", "children": [ {"parent_id": "D290", "children": [], "type": "A", "id": "A53", "name": "朝阳路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A263", "name": "陇海步行街"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A3877", "name": "南极路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A3235", "name": "海昌路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A2371", "name": "解放路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A4137", "name": "盐河路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A4359", "name": "通灌路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A635", "name": "万润街"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A1737", "name": "海连路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A3577", "name": "苍梧路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A2834", "name": "巨龙路"}, {"parent_id": "D290", "children": [], "type": "A", "id": "A485", "name": "郁洲路"}], "type": "D", "id": "D290", "name": "新浦区"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D286", "name": "灌南县"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D287", "name": "灌云县"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D284", "name": "东海县"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D285", "name": "赣榆县"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D288", "name": "海州区"}, {"parent_id": "C82", "children": [], "type": "D", "id": "D289", "name": "连云区"}], "type": "C", "id": "C82", "name": "连云港"}, {"parent_id": "P2", "children": [ {"parent_id": "C83", "children": [], "type": "D", "id": "D299", "name": "盱眙县"}, {"parent_id": "C83", "children": [ {"parent_id": "D298", "children": [], "type": "A", "id": "A3879", "name": "承德南路"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A3237", "name": "文庙新天地"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A638", "name": "大学城"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A2373", "name": "北京南路"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A4139", "name": "淮海南路"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A1739", "name": "联盛国际"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A3579", "name": "人民南路"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A2836", "name": "台北city不夜城"}, {"parent_id": "D298", "children": [], "type": "A", "id": "A4361", "name": "解放东路"}], "type": "D", "id": "D298", "name": "清浦区"}, {"parent_id": "C83", "children": [], "type": "D", "id": "D295", "name": "开发区"}, {"parent_id": "C83", "children": [], "type": "D", "id": "D294", "name": "金湖县"}, {"parent_id": "C83", "children": [ {"parent_id": "D297", "children": [], "type": "A", "id": "A54", "name": "健康东路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A264", "name": "承德北路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A3878", "name": "健康西路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A3236", "name": "淮海西路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A637", "name": "翔宇大道"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A1159", "name": "和平路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A718", "name": "新亚国际"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A2372", "name": "上海路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A4138", "name": "开元路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A969", "name": "大运河广场"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A1738", "name": "一号生活大院"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A3578", "name": "北京北路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A2835", "name": "淮海北路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A1266", "name": "万达广场"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A4360", "name": "交通路"}, {"parent_id": "D297", "children": [], "type": "A", "id": "A486", "name": "淮海东路"}], "type": "D", "id": "D297", "name": "清河区"}, {"parent_id": "C83", "children": [], "type": "D", "id": "D296", "name": "涟水县"}, {"parent_id": "C83", "children": [], "type": "D", "id": "D291", "name": "楚州区"}, {"parent_id": "C83", "children": [ {"parent_id": "D293", "children": [], "type": "A", "id": "A636", "name": "承德北路"}], "type": "D", "id": "D293", "name": "淮阴区"}, {"parent_id": "C83", "children": [], "type": "D", "id": "D292", "name": "洪泽县"}], "type": "C", "id": "C83", "name": "淮安"}, {"parent_id": "P2", "children": [ {"parent_id": "C84", "children": [ {"parent_id": "D303", "children": [], "type": "A", "id": "A3239", "name": "德润广场"}, {"parent_id": "D303", "children": [], "type": "A", "id": "A2375", "name": "汇仙湖"}, {"parent_id": "D303", "children": [], "type": "A", "id": "A1741", "name": "金东广场"}, {"parent_id": "D303", "children": [], "type": "A", "id": "A2838", "name": "鼓楼步行街"}, {"parent_id": "D303", "children": [], "type": "A", "id": "A641", "name": "向阳桥"}], "type": "D", "id": "D303", "name": "东台市"}, {"parent_id": "C84", "children": [ {"parent_id": "D302", "children": [], "type": "A", "id": "A3238", "name": "工农路"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A3580", "name": "永泰国际广场"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A2374", "name": "人民路"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A2837", "name": "名都广场"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A1740", "name": "康平路"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A640", "name": "商业街"}, {"parent_id": "D302", "children": [], "type": "A", "id": "A3880", "name": "花都美食城"}], "type": "D", "id": "D302", "name": "大丰市"}, {"parent_id": "C84", "children": [ {"parent_id": "D301", "children": [], "type": "A", "id": "A639", "name": "聚龙湖"}], "type": "D", "id": "D301", "name": "城南新区"}, {"parent_id": "C84", "children": [], "type": "D", "id": "D300", "name": "滨海县"}, {"parent_id": "C84", "children": [], "type": "D", "id": "D307", "name": "射阳县"}, {"parent_id": "C84", "children": [ {"parent_id": "D306", "children": [], "type": "A", "id": "A642", "name": "开发区商业街"}], "type": "D", "id": "D306", "name": "经济技术开发区"}, {"parent_id": "C84", "children": [], "type": "D", "id": "D305", "name": "建湖县"}, {"parent_id": "C84", "children": [], "type": "D", "id": "D304", "name": "阜宁县"}, {"parent_id": "C84", "children": [], "type": "D", "id": "D309", "name": "响水县"}, {"parent_id": "C84", "children": [ {"parent_id": "D308", "children": [], "type": "A", "id": "A55", "name": "黄海路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A265", "name": "毓龙路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1951", "name": "迎宾路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1345", "name": "金鹰购物中心"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1160", "name": "建军路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1797", "name": "农民街"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A3581", "name": "站前不夜城"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A719", "name": "大庆路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A2376", "name": "解放北路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1570", "name": "浠沧商业街"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1742", "name": "缤纷亚洲"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A3881", "name": "希望路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1465", "name": "东进路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A2062", "name": "先锋国际广场"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1407", "name": "青年路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A2155", "name": "盐马路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A2117", "name": "东进路美食街"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A3240", "name": "国飞尚城"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1671", "name": "开放大道"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A4140", "name": "西环路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1501", "name": "中茵海华广场"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A2839", "name": "解放南路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A643", "name": "宝龙城市广场"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A1267", "name": "双元路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A4362", "name": "文港路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A970", "name": "人民路"}, {"parent_id": "D308", "children": [], "type": "A", "id": "A487", "name": "五洲国际广场"}], "type": "D", "id": "D308", "name": "亭湖区"}, {"parent_id": "C84", "children": [ {"parent_id": "D310", "children": [], "type": "A", "id": "A644", "name": "世纪大道"}, {"parent_id": "D310", "children": [], "type": "A", "id": "A1743", "name": "新都路"}], "type": "D", "id": "D310", "name": "盐都区"}], "type": "C", "id": "C84", "name": "盐城"}, {"parent_id": "P2", "children": [ {"parent_id": "C85", "children": [], "type": "D", "id": "D311", "name": "宝应县"}, {"parent_id": "C85", "children": [], "type": "D", "id": "D312", "name": "高邮市"}, {"parent_id": "C85", "children": [ {"parent_id": "D313", "children": [], "type": "A", "id": "A56", "name": "解放桥"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A1161", "name": "何园"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A266", "name": "时代广场"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A3582", "name": "荷花池"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A2377", "name": "东关街"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A720", "name": "文昌广场/文昌百汇"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A3882", "name": "淮海路"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A2840", "name": "国庆路"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A3241", "name": "个园"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A1744", "name": "城东"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A4141", "name": "虹桥坊"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A647", "name": "1912区"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A1268", "name": "珍园"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A4363", "name": "邗江中路"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A971", "name": "跃进桥"}, {"parent_id": "D313", "children": [], "type": "A", "id": "A488", "name": "四望亭"}], "type": "D", "id": "D313", "name": "广陵区"}, {"parent_id": "C85", "children": [ {"parent_id": "D314", "children": [], "type": "A", "id": "A2378", "name": "绿地"}, {"parent_id": "D314", "children": [], "type": "A", "id": "A2841", "name": "文汇西路"}, {"parent_id": "D314", "children": [], "type": "A", "id": "A1745", "name": "来鹤台广场"}, {"parent_id": "D314", "children": [], "type": "A", "id": "A648", "name": "汊河汇金谷"}], "type": "D", "id": "D314", "name": "邗江区"}, {"parent_id": "C85", "children": [ {"parent_id": "D315", "children": [], "type": "A", "id": "A2379", "name": "新加坡花园"}, {"parent_id": "D315", "children": [], "type": "A", "id": "A1746", "name": "世纪花园美食街"}, {"parent_id": "D315", "children": [], "type": "A", "id": "A649", "name": "龙川路美食街"}], "type": "D", "id": "D315", "name": "江都区"}, {"parent_id": "C85", "children": [ {"parent_id": "D316", "children": [], "type": "A", "id": "A650", "name": "京华城"}, {"parent_id": "D316", "children": [], "type": "A", "id": "A2842", "name": "兴城路"}, {"parent_id": "D316", "children": [], "type": "A", "id": "A2380", "name": "望月路"}, {"parent_id": "D316", "children": [], "type": "A", "id": "A1747", "name": "力宝广场"}], "type": "D", "id": "D316", "name": "开发区"}, {"parent_id": "C85", "children": [ {"parent_id": "D317", "children": [], "type": "A", "id": "A3583", "name": "扬州大学"}, {"parent_id": "D317", "children": [], "type": "A", "id": "A1748", "name": "梅岭路"}, {"parent_id": "D317", "children": [], "type": "A", "id": "A651", "name": "沃尔玛"}, {"parent_id": "D317", "children": [], "type": "A", "id": "A2843", "name": "新天地"}, {"parent_id": "D317", "children": [], "type": "A", "id": "A3242", "name": "扬子江路"}, {"parent_id": "D317", "children": [], "type": "A", "id": "A2381", "name": "瘦西湖"}], "type": "D", "id": "D317", "name": "维扬区"}, {"parent_id": "C85", "children": [ {"parent_id": "D318", "children": [], "type": "A", "id": "A1749", "name": "解放东路"}, {"parent_id": "D318", "children": [], "type": "A", "id": "A652", "name": "鼓楼"}, {"parent_id": "D318", "children": [], "type": "A", "id": "A2844", "name": "万年大道"}, {"parent_id": "D318", "children": [], "type": "A", "id": "A2382", "name": "时代广场-步行街"}], "type": "D", "id": "D318", "name": "仪征市"}], "type": "C", "id": "C85", "name": "扬州"}, {"parent_id": "P2", "children": [ {"parent_id": "C86", "children": [ {"parent_id": "D321", "children": [], "type": "A", "id": "A656", "name": "新市口"}, {"parent_id": "D321", "children": [], "type": "A", "id": "A1750", "name": "西门"}], "type": "D", "id": "D321", "name": "丹阳市"}, {"parent_id": "C86", "children": [ {"parent_id": "D320", "children": [], "type": "A", "id": "A655", "name": "优盛生活广场"}], "type": "D", "id": "D320", "name": "丹徒区"}, {"parent_id": "C86", "children": [ {"parent_id": "D323", "children": [], "type": "A", "id": "A658", "name": "中街"}], "type": "D", "id": "D323", "name": "句容市"}, {"parent_id": "C86", "children": [ {"parent_id": "D322", "children": [], "type": "A", "id": "A3584", "name": "龙吟坊"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A657", "name": "大市口"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A3883", "name": "江苏大学"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A2845", "name": "沃德广场"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A4364", "name": "八佰伴"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A3243", "name": "梦溪广场"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A4142", "name": "大润发"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A1751", "name": "红豆广场/东吴路"}, {"parent_id": "D322", "children": [], "type": "A", "id": "A2383", "name": "欧尚/学府路"}], "type": "D", "id": "D322", "name": "京口区"}, {"parent_id": "C86", "children": [], "type": "D", "id": "D325", "name": "扬中市"}, {"parent_id": "C86", "children": [ {"parent_id": "D324", "children": [], "type": "A", "id": "A3585", "name": "金山宝地"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A659", "name": "九润广场"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A3884", "name": "三茅宫"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A2846", "name": "常发广场"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A3244", "name": "中浩国际"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A4143", "name": "天和星城"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A1752", "name": "西津渡"}, {"parent_id": "D324", "children": [], "type": "A", "id": "A2384", "name": "万达广场"}], "type": "D", "id": "D324", "name": "润州区"}, {"parent_id": "C86", "children": [], "type": "D", "id": "D319", "name": "大港新区"}], "type": "C", "id": "C86", "name": "镇江"}, {"parent_id": "P2", "children": [ {"parent_id": "C87", "children": [ {"parent_id": "D329", "children": [], "type": "A", "id": "A2848", "name": "北大街文化街区"}, {"parent_id": "D329", "children": [], "type": "A", "id": "A3246", "name": "海上海"}, {"parent_id": "D329", "children": [], "type": "A", "id": "A2386", "name": "正大路"}, {"parent_id": "D329", "children": [], "type": "A", "id": "A1755", "name": "南大街"}, {"parent_id": "D329", "children": [], "type": "A", "id": "A663", "name": "东方不夜城"}], "type": "D", "id": "D329", "name": "姜堰区"}, {"parent_id": "C87", "children": [ {"parent_id": "D328", "children": [], "type": "A", "id": "A57", "name": "老街"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A267", "name": "金鹰天地"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A3586", "name": "莲花六号区"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A3885", "name": "税东街"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A2847", "name": "世纪联华二店"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A3245", "name": "乐天玛特九洲店"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A4144", "name": "活力城"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A721", "name": "稻河湾"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A2385", "name": "江州南路"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A1754", "name": "凤城国际"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A662", "name": "万达广场"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A4365", "name": "三水湾"}, {"parent_id": "D328", "children": [], "type": "A", "id": "A489", "name": "坡子街"}], "type": "D", "id": "D328", "name": "海陵区"}, {"parent_id": "C87", "children": [ {"parent_id": "D327", "children": [], "type": "A", "id": "A661", "name": "医药城"}], "type": "D", "id": "D327", "name": "高新区"}, {"parent_id": "C87", "children": [ {"parent_id": "D326", "children": [], "type": "A", "id": "A1753", "name": "口岸街道"}, {"parent_id": "D326", "children": [], "type": "A", "id": "A660", "name": "刁铺街道"}], "type": "D", "id": "D326", "name": "高港区"}, {"parent_id": "C87", "children": [], "type": "D", "id": "D331", "name": "泰兴市"}, {"parent_id": "C87", "children": [ {"parent_id": "D332", "children": [], "type": "A", "id": "A2388", "name": "板桥街"}, {"parent_id": "D332", "children": [], "type": "A", "id": "A1757", "name": "大润发"}, {"parent_id": "D332", "children": [], "type": "A", "id": "A665", "name": "海德国际"}], "type": "D", "id": "D332", "name": "兴化市"}, {"parent_id": "C87", "children": [ {"parent_id": "D330", "children": [], "type": "A", "id": "A3587", "name": "东环"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A3886", "name": "渔婆南路"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A2849", "name": "巧丽公寓"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A3247", "name": "客运站"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A4145", "name": "靖江国际大酒店"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A2387", "name": "恒天广场"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A1756", "name": "上海城"}, {"parent_id": "D330", "children": [], "type": "A", "id": "A664", "name": "德诚广场"}], "type": "D", "id": "D330", "name": "靖江市"}], "type": "C", "id": "C87", "name": "泰州"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C108", "name": "高邮"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C109", "name": "仪征"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C104", "name": "句容"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C105", "name": "兴化"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C106", "name": "泰兴"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C107", "name": "海门"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C100", "name": "丹阳"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C101", "name": "邳州"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C102", "name": "启东"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C103", "name": "如皋"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C88", "name": "宿迁"}, {"parent_id": "P2", "children": [ {"parent_id": "C89", "children": [], "type": "D", "id": "D341", "name": "周市镇"}, {"parent_id": "C89", "children": [], "type": "D", "id": "D340", "name": "张浦镇"}, {"parent_id": "C89", "children": [ {"parent_id": "D338", "children": [], "type": "A", "id": "A668", "name": "千灯"}], "type": "D", "id": "D338", "name": "千灯镇"}, {"parent_id": "C89", "children": [ {"parent_id": "D339", "children": [], "type": "A", "id": "A58", "name": "长江路"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A268", "name": "百盛"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A3588", "name": "嘉茂广场"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A3887", "name": "超华城市广场"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A3248", "name": "北门路"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A4146", "name": "吉田国际广场"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A2389", "name": "柏庐路"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A1758", "name": "人民路"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A669", "name": "世茂"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A2850", "name": "新客站"}, {"parent_id": "D339", "children": [], "type": "A", "id": "A4366", "name": "前进路"}], "type": "D", "id": "D339", "name": "玉山镇"}, {"parent_id": "C89", "children": [], "type": "D", "id": "D336", "name": "开发区"}, {"parent_id": "C89", "children": [], "type": "D", "id": "D337", "name": "陆家镇"}, {"parent_id": "C89", "children": [ {"parent_id": "D334", "children": [], "type": "A", "id": "A666", "name": "淀山湖"}], "type": "D", "id": "D334", "name": "淀山湖镇"}, {"parent_id": "C89", "children": [ {"parent_id": "D335", "children": [], "type": "A", "id": "A667", "name": "花桥"}], "type": "D", "id": "D335", "name": "花桥镇"}, {"parent_id": "C89", "children": [], "type": "D", "id": "D333", "name": "巴城镇"}], "type": "C", "id": "C89", "name": "昆山"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C93", "name": "金坛"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C92", "name": "宜兴"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C91", "name": "溧阳"}, {"parent_id": "P2", "children": [ {"parent_id": "C90", "children": [], "type": "D", "id": "D349", "name": "青果路"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D348", "name": "江阴市中"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D347", "name": "花园新村"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D346", "name": "黄山湖公园"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D345", "name": "东门"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D344", "name": "城东开发区"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D343", "name": "澄江福地"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D342", "name": "长山镇"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D354", "name": "新一城"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D355", "name": "希望广场"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D356", "name": "一中初中部"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D357", "name": "中山公园"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D350", "name": "天鹤小区"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D351", "name": "万达广场"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D352", "name": "夏港街道"}, {"parent_id": "C90", "children": [], "type": "D", "id": "D353", "name": "新百业广场"}], "type": "C", "id": "C90", "name": "江阴"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C97", "name": "大丰"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C96", "name": "太仓"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C95", "name": "吴江"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C94", "name": "靖江"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C99", "name": "常熟"}, {"parent_id": "P2", "children": [], "type": "C", "id": "C98", "name": "东台"}], "type": "P", "id": "P2", "name": "江苏"}, {"parent_id": "N1", "children": [ {"parent_id": "P11", "children": [ {"parent_id": "C39", "children": [ {"parent_id": "D152", "children": [], "type": "A", "id": "A1624", "name": "科学城"}, {"parent_id": "D152", "children": [], "type": "A", "id": "A2765", "name": "中心城"}, {"parent_id": "D152", "children": [], "type": "A", "id": "A401", "name": "开发区东区"}, {"parent_id": "D152", "children": [], "type": "A", "id": "A2288", "name": "开发区西区"}], "type": "D", "id": "D152", "name": "萝岗区"}, {"parent_id": "C39", "children": [], "type": "D", "id": "D153", "name": "南沙区"}, {"parent_id": "C39", "children": [ {"parent_id": "D150", "children": [], "type": "A", "id": "A1622", "name": "文冲"}, {"parent_id": "D150", "children": [], "type": "A", "id": "A399", "name": "大沙地"}, {"parent_id": "D150", "children": [], "type": "A", "id": "A2763", "name": "鱼珠"}, {"parent_id": "D150", "children": [], "type": "A", "id": "A2286", "name": "夏园/南岗"}], "type": "D", "id": "D150", "name": "黄埔区"}, {"parent_id": "C39", "children": [ {"parent_id": "D151", "children": [], "type": "A", "id": "A3831", "name": "西城都荟"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A1623", "name": "恒宝广场"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A4097", "name": "中山七八路"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A3525", "name": "西村西场"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A2764", "name": "上下九商业区"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A400", "name": "芳村"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A3175", "name": "沙面"}, {"parent_id": "D151", "children": [], "type": "A", "id": "A2287", "name": "康王路"}], "type": "D", "id": "D151", "name": "荔湾区"}, {"parent_id": "C39", "children": [ {"parent_id": "D156", "children": [], "type": "A", "id": "A3834", "name": "麓湖公园周边"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A1627", "name": "东风东/杨箕"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A3528", "name": "海珠广场"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A4330", "name": "沿江路沿线/二沙岛"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A28", "name": "中山二三路/东山口"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A2768", "name": "环市东路沿线"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A2291", "name": "东风中路/越秀公园"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A4100", "name": "五羊新城"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A404", "name": "北京路商业区"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A3178", "name": "火车站/人民北路"}, {"parent_id": "D156", "children": [], "type": "A", "id": "A220", "name": "中山六路"}], "type": "D", "id": "D156", "name": "越秀区"}, {"parent_id": "C39", "children": [ {"parent_id": "D157", "children": [], "type": "A", "id": "A1628", "name": "荔城大润发/东汇城"}, {"parent_id": "D157", "children": [], "type": "A", "id": "A2769", "name": "新塘太阳城/凯旋门"}, {"parent_id": "D157", "children": [], "type": "A", "id": "A2292", "name": "新塘大润发/现代城"}, {"parent_id": "D157", "children": [], "type": "A", "id": "A405", "name": "荔城挂绿/泰富广场"}, {"parent_id": "D157", "children": [], "type": "A", "id": "A3179", "name": "增城其他"}], "type": "D", "id": "D157", "name": "增城市"}, {"parent_id": "C39", "children": [ {"parent_id": "D154", "children": [], "type": "A", "id": "A3832", "name": "市桥南"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A1625", "name": "大学城"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A4098", "name": "石基"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A3526", "name": "市桥"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A26", "name": "钟村"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A2766", "name": "南村"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A402", "name": "大石"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A4328", "name": "沙湾镇"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A3176", "name": "番禺广场"}, {"parent_id": "D154", "children": [], "type": "A", "id": "A2289", "name": "洛浦"}], "type": "D", "id": "D154", "name": "番禺区"}, {"parent_id": "C39", "children": [ {"parent_id": "D155", "children": [], "type": "A", "id": "A3833", "name": "天河公园/棠下"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A1626", "name": "花城汇/高德置地"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A646", "name": "燕岭/五山"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A4099", "name": "体育中心"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A3527", "name": "时尚天河"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A27", "name": "天河北/广州东站"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A2290", "name": "车陂/东圃"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A219", "name": "天河客运站"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A2767", "name": "龙洞/岑村"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A461", "name": "小新塘"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A403", "name": "石牌/龙口"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A4329", "name": "天河城/正佳广场"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A934", "name": "珠江新城/跑马场"}, {"parent_id": "D155", "children": [], "type": "A", "id": "A3177", "name": "天平架"}], "type": "D", "id": "D155", "name": "天河区"}, {"parent_id": "C39", "children": [ {"parent_id": "D148", "children": [], "type": "A", "id": "A3830", "name": "琶洲"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A1620", "name": "东晓南路沿线"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A4096", "name": "新港西路沿线"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A3524", "name": "客村/赤岗"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A397", "name": "滨江路沿线"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A2761", "name": "江南大道沿线"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A3173", "name": "江南西"}, {"parent_id": "D148", "children": [], "type": "A", "id": "A2284", "name": "工业大道沿线"}], "type": "D", "id": "D148", "name": "海珠区"}, {"parent_id": "C39", "children": [ {"parent_id": "D149", "children": [], "type": "A", "id": "A1621", "name": "花山"}, {"parent_id": "D149", "children": [], "type": "A", "id": "A398", "name": "花东"}, {"parent_id": "D149", "children": [], "type": "A", "id": "A2762", "name": "新华"}, {"parent_id": "D149", "children": [], "type": "A", "id": "A3174", "name": "雅瑶"}, {"parent_id": "D149", "children": [], "type": "A", "id": "A2285", "name": "狮岭"}], "type": "D", "id": "D149", "name": "花都区"}, {"parent_id": "C39", "children": [], "type": "D", "id": "D147", "name": "从化市"}, {"parent_id": "C39", "children": [ {"parent_id": "D146", "children": [], "type": "A", "id": "A3829", "name": "罗冲围/金沙洲"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A4095", "name": "三元里"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A3523", "name": "嘉裕太阳城"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A25", "name": "同德围"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A396", "name": "白云大道沿线"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A218", "name": "万达广场"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A2760", "name": "机场路沿线"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A1619", "name": "广园新村"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A460", "name": "五号停机坪"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A4327", "name": "同和/京溪"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A645", "name": "新市"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A933", "name": "永泰"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A3172", "name": "嘉禾/人和"}, {"parent_id": "D146", "children": [], "type": "A", "id": "A2283", "name": "黄石"}], "type": "D", "id": "D146", "name": "白云区"}], "type": "C", "id": "C39", "name": "广州"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C276", "name": "肇庆"}, {"parent_id": "P11", "children": [ {"parent_id": "C277", "children": [ {"parent_id": "D811", "children": [], "type": "A", "id": "A2553", "name": "石湾园洲"}, {"parent_id": "D811", "children": [], "type": "A", "id": "A1971", "name": "义和龙溪"}, {"parent_id": "D811", "children": [], "type": "A", "id": "A1018", "name": "罗阳县城"}, {"parent_id": "D811", "children": [], "type": "A", "id": "A2994", "name": "福田长宁"}], "type": "D", "id": "D811", "name": "博罗县"}, {"parent_id": "C277", "children": [ {"parent_id": "D813", "children": [], "type": "A", "id": "A2555", "name": "吉隆一带"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A1973", "name": "平海港口"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A3982", "name": "黄排"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A3695", "name": "华侨城"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A3374", "name": "大岭"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A2996", "name": "巽寮"}, {"parent_id": "D813", "children": [], "type": "A", "id": "A1020", "name": "平山"}], "type": "D", "id": "D813", "name": "惠东县"}, {"parent_id": "C277", "children": [ {"parent_id": "D812", "children": [], "type": "A", "id": "A2554", "name": "小金"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A1972", "name": "水口"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A4440", "name": "南坛下埔"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A125", "name": "麦地片区"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A1019", "name": "河南岸"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A3373", "name": "仲恺陈江"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A4230", "name": "东平"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A3694", "name": "江北"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A3981", "name": "上排龙丰"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A2995", "name": "汝湖"}, {"parent_id": "D812", "children": [], "type": "A", "id": "A346", "name": "西湖下角"}], "type": "D", "id": "D812", "name": "惠城区"}, {"parent_id": "C277", "children": [ {"parent_id": "D815", "children": [], "type": "A", "id": "A1975", "name": "永汉一带"}, {"parent_id": "D815", "children": [], "type": "A", "id": "A1022", "name": "龙城片区"}], "type": "D", "id": "D815", "name": "龙门县"}, {"parent_id": "C277", "children": [ {"parent_id": "D814", "children": [], "type": "A", "id": "A2556", "name": "人民四路"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A1974", "name": "立交桥"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A4441", "name": "万联广场"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A126", "name": "开城大道"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A3983", "name": "土湖白云坑"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A3696", "name": "秋长一带"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A4231", "name": "天虹商场"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A2997", "name": "开城大道南"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A1021", "name": "好宜多"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A3375", "name": "澳头大亚湾"}, {"parent_id": "D814", "children": [], "type": "A", "id": "A347", "name": "华都广场"}], "type": "D", "id": "D814", "name": "惠阳区"}], "type": "C", "id": "C277", "name": "惠州"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C274", "name": "湛江"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C275", "name": "茂名"}, {"parent_id": "P11", "children": [ {"parent_id": "C272", "children": [ {"parent_id": "D800", "children": [], "type": "A", "id": "A1598", "name": "文华里"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A4228", "name": "华远东路"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1683", "name": "印象城"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1514", "name": "文华北路沿线"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A124", "name": "九鼎国际"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A2989", "name": "石湾"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A3979", "name": "湖景路"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1479", "name": "同济路/流行前线"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1296", "name": "丽日玫瑰"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1423", "name": "普君新城"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A4439", "name": "季华五路"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A2547", "name": "东方广场"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1371", "name": "岭南明珠"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A781", "name": "绿景路"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1965", "name": "朝安"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A541", "name": "魁奇地铁站周边"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A3692", "name": "汾江路沿线"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1193", "name": "岭南天地"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1987", "name": "张槎"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1009", "name": "创意产业园"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A345", "name": "季华路沿线"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1819", "name": "祖庙"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A1042", "name": "岭南大道"}, {"parent_id": "D800", "children": [], "type": "A", "id": "A3369", "name": "东建世纪广场"}], "type": "D", "id": "D800", "name": "禅城区"}, {"parent_id": "C272", "children": [], "type": "D", "id": "D801", "name": "顺德区"}, {"parent_id": "C272", "children": [ {"parent_id": "D802", "children": [], "type": "A", "id": "A1010", "name": "百胜广场"}, {"parent_id": "D802", "children": [], "type": "A", "id": "A2548", "name": "金典广场"}, {"parent_id": "D802", "children": [], "type": "A", "id": "A1966", "name": "富盛广场"}, {"parent_id": "D802", "children": [], "type": "A", "id": "A2990", "name": "新城广场"}, {"parent_id": "D802", "children": [], "type": "A", "id": "A3370", "name": "雅居乐广场"}], "type": "D", "id": "D802", "name": "西樵"}, {"parent_id": "C272", "children": [], "type": "D", "id": "D803", "name": "盐步"}, {"parent_id": "C272", "children": [ {"parent_id": "D798", "children": [], "type": "A", "id": "A1007", "name": "吉利购物广场"}], "type": "D", "id": "D798", "name": "南庄"}, {"parent_id": "C272", "children": [ {"parent_id": "D799", "children": [], "type": "A", "id": "A1008", "name": "西南"}], "type": "D", "id": "D799", "name": "三水区"}, {"parent_id": "C272", "children": [ {"parent_id": "D796", "children": [], "type": "A", "id": "A2987", "name": "金沙洲"}, {"parent_id": "D796", "children": [], "type": "A", "id": "A2545", "name": "嘉洲广场"}, {"parent_id": "D796", "children": [], "type": "A", "id": "A1963", "name": "黄岐步行街"}, {"parent_id": "D796", "children": [], "type": "A", "id": "A1005", "name": "国昌新城市广场"}, {"parent_id": "D796", "children": [], "type": "A", "id": "A3367", "name": "南方广场"}], "type": "D", "id": "D796", "name": "黄岐"}, {"parent_id": "C272", "children": [ {"parent_id": "D797", "children": [], "type": "A", "id": "A1597", "name": "狮山"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A4227", "name": "家天下"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1682", "name": "壹品广场"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1513", "name": "松岗"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A123", "name": "九江镇"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A2988", "name": "官窑"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A3978", "name": "佳盛国际"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1295", "name": "南海体育馆"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1422", "name": "平洲"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A4438", "name": "南舜.金百福都市广场"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A2546", "name": "丹灶"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1370", "name": "南舜·桂平美食城"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A780", "name": "里水"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1964", "name": "百花时代"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A540", "name": "罗村"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A3691", "name": "季华七路/石啃"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1192", "name": "南海广场"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1006", "name": "保利水城"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A344", "name": "凯德广场"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1478", "name": "鹏瑞利季华广场"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1818", "name": "紫金城"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A1041", "name": "南海新天地"}, {"parent_id": "D797", "children": [], "type": "A", "id": "A3368", "name": "鸿大广场"}], "type": "D", "id": "D797", "name": "南海区"}, {"parent_id": "C272", "children": [ {"parent_id": "D794", "children": [], "type": "A", "id": "A2544", "name": "兴沥雄"}, {"parent_id": "D794", "children": [], "type": "A", "id": "A1962", "name": "新都会"}, {"parent_id": "D794", "children": [], "type": "A", "id": "A1003", "name": "巴黎春天"}], "type": "D", "id": "D794", "name": "大沥"}, {"parent_id": "C272", "children": [ {"parent_id": "D795", "children": [], "type": "A", "id": "A1004", "name": "荷城"}], "type": "D", "id": "D795", "name": "高明区"}], "type": "C", "id": "C272", "name": "佛山"}, {"parent_id": "P11", "children": [ {"parent_id": "C273", "children": [ {"parent_id": "D808", "children": [], "type": "A", "id": "A2551", "name": "地王"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A4229", "name": "潮连"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A2992", "name": "白石"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A1014", "name": "江华"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A3980", "name": "荷塘"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A3372", "name": "北郊"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A1969", "name": "益华"}, {"parent_id": "D808", "children": [], "type": "A", "id": "A3693", "name": "白沙"}], "type": "D", "id": "D808", "name": "蓬江区"}, {"parent_id": "C273", "children": [], "type": "D", "id": "D809", "name": "台山市"}, {"parent_id": "C273", "children": [ {"parent_id": "D810", "children": [], "type": "A", "id": "A2552", "name": "华润万家"}, {"parent_id": "D810", "children": [], "type": "A", "id": "A1970", "name": "仁寿广场"}, {"parent_id": "D810", "children": [], "type": "A", "id": "A2993", "name": "大润发"}, {"parent_id": "D810", "children": [], "type": "A", "id": "A1015", "name": "世纪广场"}], "type": "D", "id": "D810", "name": "新会区"}, {"parent_id": "C273", "children": [], "type": "D", "id": "D804", "name": "恩平市"}, {"parent_id": "C273", "children": [ {"parent_id": "D805", "children": [], "type": "A", "id": "A1011", "name": "人民东路"}, {"parent_id": "D805", "children": [], "type": "A", "id": "A2549", "name": "新天地"}, {"parent_id": "D805", "children": [], "type": "A", "id": "A1967", "name": "大润发"}], "type": "D", "id": "D805", "name": "鹤山市"}, {"parent_id": "C273", "children": [ {"parent_id": "D806", "children": [], "type": "A", "id": "A1012", "name": "江海"}], "type": "D", "id": "D806", "name": "江海区"}, {"parent_id": "C273", "children": [ {"parent_id": "D807", "children": [], "type": "A", "id": "A2550", "name": "新昌"}, {"parent_id": "D807", "children": [], "type": "A", "id": "A1013", "name": "长沙区域"}, {"parent_id": "D807", "children": [], "type": "A", "id": "A1968", "name": "城市广场"}, {"parent_id": "D807", "children": [], "type": "A", "id": "A2991", "name": "详龙"}, {"parent_id": "D807", "children": [], "type": "A", "id": "A3371", "name": "水口"}], "type": "D", "id": "D807", "name": "开平市"}], "type": "C", "id": "C273", "name": "江门"}, {"parent_id": "P11", "children": [ {"parent_id": "C270", "children": [], "type": "D", "id": "D783", "name": "兰埔"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D782", "name": "金湾区"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D781", "name": "井岸镇"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D780", "name": "吉大"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D787", "name": "前山"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D786", "name": "柠溪"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D789", "name": "湾仔"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D788", "name": "唐家湾"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D785", "name": "南屏"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D784", "name": "明珠商业广场"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D776", "name": "斗门区"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D777", "name": "拱北"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D778", "name": "横琴新区"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D779", "name": "华发世纪城"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D790", "name": "香洲"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D791", "name": "香洲区"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D792", "name": "夏湾"}, {"parent_id": "C270", "children": [], "type": "D", "id": "D793", "name": "新香洲"}], "type": "C", "id": "C270", "name": "珠海"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C271", "name": "汕头"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C278", "name": "梅州"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C279", "name": "汕尾"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C76", "name": "深圳"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C294", "name": "英德"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C290", "name": "开平"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C292", "name": "鹤山"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C293", "name": "乐昌"}, {"parent_id": "P11", "children": [ {"parent_id": "C433", "children": [], "type": "D", "id": "D1082", "name": "洪梅镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1083", "children": [], "type": "A", "id": "A1452", "name": "康乐路"}], "type": "D", "id": "D1083", "name": "厚街镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1080", "children": [], "type": "A", "id": "A2693", "name": "君尚百货/威尼斯广场"}, {"parent_id": "D1080", "children": [], "type": "A", "id": "A3784", "name": "运河路"}, {"parent_id": "D1080", "children": [], "type": "A", "id": "A3475", "name": "堑头/学院路/育兴路"}, {"parent_id": "D1080", "children": [], "type": "A", "id": "A2196", "name": "地王广场/东湖花园"}, {"parent_id": "D1080", "children": [], "type": "A", "id": "A3114", "name": "人民公园/西城楼/可园"}, {"parent_id": "D1080", "children": [], "type": "A", "id": "A1450", "name": "八达路/旗峰路"}], "type": "D", "id": "D1080", "name": "莞城区"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1081", "name": "横沥镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1086", "name": "寮步镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1087", "name": "麻涌镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1084", "children": [], "type": "A", "id": "A2694", "name": "黄江天虹"}, {"parent_id": "D1084", "children": [], "type": "A", "id": "A2197", "name": "黄江嘉荣"}, {"parent_id": "D1084", "children": [], "type": "A", "id": "A3115", "name": "太子酒店"}, {"parent_id": "D1084", "children": [], "type": "A", "id": "A1453", "name": "黄江大道"}], "type": "D", "id": "D1084", "name": "黄江镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1085", "children": [], "type": "A", "id": "A2695", "name": "丰泰花园酒店"}, {"parent_id": "D1085", "children": [], "type": "A", "id": "A3785", "name": "虎门国际购物中心"}, {"parent_id": "D1085", "children": [], "type": "A", "id": "A3476", "name": "黄河时装城"}, {"parent_id": "D1085", "children": [], "type": "A", "id": "A2198", "name": "博美"}, {"parent_id": "D1085", "children": [], "type": "A", "id": "A3116", "name": "虎门步行街"}, {"parent_id": "D1085", "children": [], "type": "A", "id": "A1454", "name": "不夜天/天虹"}], "type": "D", "id": "D1085", "name": "虎门镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1088", "children": [], "type": "A", "id": "A2696", "name": "都会广场"}, {"parent_id": "D1088", "children": [], "type": "A", "id": "A2199", "name": "石美"}, {"parent_id": "D1088", "children": [], "type": "A", "id": "A3117", "name": "下坝坊"}, {"parent_id": "D1088", "children": [], "type": "A", "id": "A1455", "name": "华南摩尔"}], "type": "D", "id": "D1088", "name": "万江区"}, {"parent_id": "C433", "children": [ {"parent_id": "D1089", "children": [], "type": "A", "id": "A2697", "name": "富民步行街"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A3786", "name": "名牌商业街/体育路"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A3477", "name": "景湖时代城/西平"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A4297", "name": "中心广场/华凯广场"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A2200", "name": "第一国际/汇一城"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A4060", "name": "银丰路"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A3118", "name": "鸿福路口"}, {"parent_id": "D1089", "children": [], "type": "A", "id": "A1456", "name": "城市风景街"}], "type": "D", "id": "D1089", "name": "南城区"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1073", "name": "石碣镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1072", "name": "大岭山镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1071", "children": [], "type": "A", "id": "A1447", "name": "长盛广场"}, {"parent_id": "D1071", "children": [], "type": "A", "id": "A2193", "name": "金朗中路"}], "type": "D", "id": "D1071", "name": "大朗镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1070", "name": "茶山镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1077", "name": "东坑镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1076", "children": [], "type": "A", "id": "A2692", "name": "花园新村"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A575", "name": "主山/海港城"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A4059", "name": "世纪广场"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A3783", "name": "世博/金月湾/星玺"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A1448", "name": "东泰/嘉荣广场"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A3474", "name": "旗峰广场"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A170", "name": "新世界花园/酒吧街"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A4495", "name": "星河城/十三碗"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A2194", "name": "东宝路"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A4296", "name": "石井"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A3113", "name": "火炼树/怡丰都市"}, {"parent_id": "D1076", "children": [], "type": "A", "id": "A386", "name": "雍华庭"}], "type": "D", "id": "D1076", "name": "东城区"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1075", "name": "道滘镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1074", "name": "石龙镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1079", "name": "高埗镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1078", "children": [], "type": "A", "id": "A1449", "name": "永盛大街"}, {"parent_id": "D1078", "children": [], "type": "A", "id": "A2195", "name": "雁田"}], "type": "D", "id": "D1078", "name": "凤岗镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1091", "children": [], "type": "A", "id": "A2698", "name": "香芒东路"}, {"parent_id": "D1091", "children": [], "type": "A", "id": "A2201", "name": "金阳广场/天和百货"}, {"parent_id": "D1091", "children": [], "type": "A", "id": "A1458", "name": "聚富路"}], "type": "D", "id": "D1091", "name": "清溪镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1090", "children": [], "type": "A", "id": "A1457", "name": "广隆百货"}], "type": "D", "id": "D1090", "name": "桥头镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1093", "name": "沙田镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1092", "name": "企石镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1095", "name": "松山湖"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1094", "name": "石排镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1097", "name": "望牛墩镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1096", "children": [], "type": "A", "id": "A2699", "name": "隆福花园"}, {"parent_id": "D1096", "children": [], "type": "A", "id": "A2202", "name": "花园街"}, {"parent_id": "D1096", "children": [], "type": "A", "id": "A3119", "name": "塘厦沃尔玛"}, {"parent_id": "D1096", "children": [], "type": "A", "id": "A1459", "name": "东圃市场"}], "type": "D", "id": "D1096", "name": "塘厦镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1099", "children": [], "type": "A", "id": "A1460", "name": "天一城"}], "type": "D", "id": "D1099", "name": "樟木头镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1098", "name": "谢岗镇"}, {"parent_id": "C433", "children": [], "type": "D", "id": "D1100", "name": "中堂镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1068", "children": [], "type": "A", "id": "A3782", "name": "振安路"}, {"parent_id": "D1068", "children": [], "type": "A", "id": "A1444", "name": "长安镇区"}, {"parent_id": "D1068", "children": [], "type": "A", "id": "A3472", "name": "乌沙大润发"}, {"parent_id": "D1068", "children": [], "type": "A", "id": "A2689", "name": "厦边大道"}, {"parent_id": "D1068", "children": [], "type": "A", "id": "A2190", "name": "地王广场"}, {"parent_id": "D1068", "children": [], "type": "A", "id": "A3110", "name": "万达广场"}], "type": "D", "id": "D1068", "name": "长安镇"}, {"parent_id": "C433", "children": [ {"parent_id": "D1069", "children": [], "type": "A", "id": "A2690", "name": "乐购购物广场"}, {"parent_id": "D1069", "children": [], "type": "A", "id": "A1445", "name": "常平镇中心"}, {"parent_id": "D1069", "children": [], "type": "A", "id": "A3473", "name": "天鹅湖"}, {"parent_id": "D1069", "children": [], "type": "A", "id": "A2191", "name": "丽城酒店"}, {"parent_id": "D1069", "children": [], "type": "A", "id": "A3111", "name": "世纪康城"}], "type": "D", "id": "D1069", "name": "常平镇"}], "type": "C", "id": "C433", "name": "东莞"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C291", "name": "台山"}, {"parent_id": "P11", "children": [ {"parent_id": "C269", "children": [], "type": "D", "id": "D767", "name": "南雄市"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D766", "name": "乐昌市"}, {"parent_id": "C269", "children": [ {"parent_id": "D769", "children": [], "type": "A", "id": "A1000", "name": "丹霞山"}], "type": "D", "id": "D769", "name": "仁化县"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D768", "name": "曲江区"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D774", "name": "新丰县"}, {"parent_id": "C269", "children": [ {"parent_id": "D775", "children": [], "type": "A", "id": "A539", "name": "南郊"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A4226", "name": "步行街"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A779", "name": "信德万汇广场"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A2986", "name": "碧桂园凤凰城"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A122", "name": "东河"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A3977", "name": "大润发"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A2543", "name": "东联"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A1961", "name": "百年东街"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A3690", "name": "解放路"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A4437", "name": "中山公园"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A1002", "name": "韶关大学"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A343", "name": "火车站"}, {"parent_id": "D775", "children": [], "type": "A", "id": "A3366", "name": "五里亭"}], "type": "D", "id": "D775", "name": "浈江区"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D772", "name": "翁源县"}, {"parent_id": "C269", "children": [ {"parent_id": "D773", "children": [], "type": "A", "id": "A4225", "name": "沙洲尾"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A3689", "name": "中环广场"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A121", "name": "第十五中学"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A2985", "name": "东岗岭"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A3976", "name": "沃尔玛"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A2542", "name": "旭日玩具厂"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A1960", "name": "工业中路"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A4436", "name": "矿山公园"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A1001", "name": "工业路"}, {"parent_id": "D773", "children": [], "type": "A", "id": "A3365", "name": "西客运站"}], "type": "D", "id": "D773", "name": "武江区"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D770", "name": "乳源瑶族自治县"}, {"parent_id": "C269", "children": [], "type": "D", "id": "D771", "name": "始兴县"}], "type": "C", "id": "C269", "name": "韶关"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C289", "name": "增城"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C288", "name": "惠东"}, {"parent_id": "P11", "children": [ {"parent_id": "C287", "children": [ {"parent_id": "D851", "children": [], "type": "A", "id": "A1051", "name": "奥园"}, {"parent_id": "D851", "children": [], "type": "A", "id": "A1992", "name": "威斯广场"}], "type": "D", "id": "D851", "name": "乐从"}, {"parent_id": "C287", "children": [ {"parent_id": "D850", "children": [], "type": "A", "id": "A1050", "name": "骏景酒店"}], "type": "D", "id": "D850", "name": "均安"}, {"parent_id": "C287", "children": [ {"parent_id": "D848", "children": [], "type": "A", "id": "A1048", "name": "顺联广场"}, {"parent_id": "D848", "children": [], "type": "A", "id": "A1990", "name": "陈村旧虚"}], "type": "D", "id": "D848", "name": "陈村"}, {"parent_id": "C287", "children": [ {"parent_id": "D849", "children": [], "type": "A", "id": "A3005", "name": "南国路"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A129", "name": "嘉信广场"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A3701", "name": "福盈酒店"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A2566", "name": "凤岭公园"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A4445", "name": "凤城食都"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A783", "name": "乐购"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A3987", "name": "东乐路"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A4235", "name": "东苑市场"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A3380", "name": "桂畔海沿线"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A349", "name": "新世界"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A1044", "name": "凤城酒店"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A1049", "name": "新一城"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A543", "name": "永旺购物中心"}, {"parent_id": "D849", "children": [], "type": "A", "id": "A1991", "name": "大润发"}], "type": "D", "id": "D849", "name": "大良"}, {"parent_id": "C287", "children": [ {"parent_id": "D847", "children": [], "type": "A", "id": "A3004", "name": "北滘碧桂园"}, {"parent_id": "D847", "children": [], "type": "A", "id": "A2565", "name": "南源路"}, {"parent_id": "D847", "children": [], "type": "A", "id": "A1989", "name": "北滘广场"}, {"parent_id": "D847", "children": [], "type": "A", "id": "A1047", "name": "华美达酒店"}], "type": "D", "id": "D847", "name": "北滘"}, {"parent_id": "C287", "children": [ {"parent_id": "D856", "children": [], "type": "A", "id": "A1056", "name": "杏坛大酒店"}], "type": "D", "id": "D856", "name": "杏坛"}, {"parent_id": "C287", "children": [ {"parent_id": "D855", "children": [], "type": "A", "id": "A3007", "name": "容桂车站"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A3702", "name": "宏骏广场"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A1055", "name": "天佑城"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A3988", "name": "大凤山公园"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A4236", "name": "容山商场"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A3381", "name": "花溪公园"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A1996", "name": "凤祥路"}, {"parent_id": "D855", "children": [], "type": "A", "id": "A2570", "name": "文华路"}], "type": "D", "id": "D855", "name": "容桂"}, {"parent_id": "C287", "children": [ {"parent_id": "D854", "children": [], "type": "A", "id": "A3006", "name": "大福广场"}, {"parent_id": "D854", "children": [], "type": "A", "id": "A1054", "name": "永丰市场"}, {"parent_id": "D854", "children": [], "type": "A", "id": "A2569", "name": "康乐中心"}, {"parent_id": "D854", "children": [], "type": "A", "id": "A1995", "name": "大成花园"}], "type": "D", "id": "D854", "name": "伦教"}, {"parent_id": "C287", "children": [ {"parent_id": "D853", "children": [], "type": "A", "id": "A1053", "name": "盈信城市广场"}, {"parent_id": "D853", "children": [], "type": "A", "id": "A2568", "name": "排沙商圈"}, {"parent_id": "D853", "children": [], "type": "A", "id": "A1994", "name": "前进会展中心"}], "type": "D", "id": "D853", "name": "龙江"}, {"parent_id": "C287", "children": [ {"parent_id": "D852", "children": [], "type": "A", "id": "A1052", "name": "勒流水上乐园"}, {"parent_id": "D852", "children": [], "type": "A", "id": "A2567", "name": "勒流文化广场"}, {"parent_id": "D852", "children": [], "type": "A", "id": "A1993", "name": "新港城商场"}], "type": "D", "id": "D852", "name": "勒流"}], "type": "C", "id": "C287", "name": "顺德"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C286", "name": "云浮"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C285", "name": "揭阳"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C284", "name": "潮州"}, {"parent_id": "P11", "children": [ {"parent_id": "C283", "children": [], "type": "D", "id": "D824", "name": "大涌镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D825", "children": [], "type": "A", "id": "A1025", "name": "名扬世纪广场"}], "type": "D", "id": "D825", "name": "东凤镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D828", "name": "阜沙镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D829", "children": [], "type": "A", "id": "A1979", "name": "港口市场"}, {"parent_id": "D829", "children": [], "type": "A", "id": "A1027", "name": "美景花园"}], "type": "D", "id": "D829", "name": "港口镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D826", "children": [], "type": "A", "id": "A2559", "name": "中山海关"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A1978", "name": "库充一带"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A4444", "name": "利和广场"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A3000", "name": "竹苑周边"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A3986", "name": "白沙湾"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A4234", "name": "东裕路"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A3699", "name": "京华利和"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A1026", "name": "假日广场"}, {"parent_id": "D826", "children": [], "type": "A", "id": "A3378", "name": "远洋城"}], "type": "D", "id": "D826", "name": "东区"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D827", "name": "东升镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D823", "name": "板芙镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D839", "children": [], "type": "A", "id": "A3001", "name": "顺昌广场"}, {"parent_id": "D839", "children": [], "type": "A", "id": "A1031", "name": "雅居乐酒店"}, {"parent_id": "D839", "children": [], "type": "A", "id": "A2561", "name": "三乡市场"}, {"parent_id": "D839", "children": [], "type": "A", "id": "A1983", "name": "华丰片区"}], "type": "D", "id": "D839", "name": "三乡镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D838", "name": "三角镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D831", "name": "横栏镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D830", "children": [], "type": "A", "id": "A1980", "name": "古镇"}, {"parent_id": "D830", "children": [], "type": "A", "id": "A1028", "name": "国贸"}], "type": "D", "id": "D830", "name": "古镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D832", "name": "黄圃镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D835", "name": "南朗镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D834", "name": "民众镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D837", "name": "南头镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D836", "children": [], "type": "A", "id": "A1030", "name": "万科一带"}, {"parent_id": "D836", "children": [], "type": "A", "id": "A2560", "name": "南下新码头"}, {"parent_id": "D836", "children": [], "type": "A", "id": "A1982", "name": "悦来南路"}], "type": "D", "id": "D836", "name": "南区"}, {"parent_id": "C283", "children": [ {"parent_id": "D833", "children": [], "type": "A", "id": "A1981", "name": "中山港"}, {"parent_id": "D833", "children": [], "type": "A", "id": "A1029", "name": "张家边"}], "type": "D", "id": "D833", "name": "火炬开发区"}, {"parent_id": "C283", "children": [ {"parent_id": "D846", "children": [], "type": "A", "id": "A3003", "name": "翠景商业街"}, {"parent_id": "D846", "children": [], "type": "A", "id": "A1036", "name": "歧江公园"}, {"parent_id": "D846", "children": [], "type": "A", "id": "A2564", "name": "黄金广场"}, {"parent_id": "D846", "children": [], "type": "A", "id": "A1986", "name": "富华商圈"}], "type": "D", "id": "D846", "name": "西区"}, {"parent_id": "C283", "children": [ {"parent_id": "D844", "children": [], "type": "A", "id": "A1034", "name": "长命水广药"}], "type": "D", "id": "D844", "name": "五桂山区"}, {"parent_id": "C283", "children": [ {"parent_id": "D845", "children": [], "type": "A", "id": "A1035", "name": "大信顺昌"}, {"parent_id": "D845", "children": [], "type": "A", "id": "A2563", "name": "小榄"}, {"parent_id": "D845", "children": [], "type": "A", "id": "A1985", "name": "永宁"}], "type": "D", "id": "D845", "name": "小榄镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D840", "children": [], "type": "A", "id": "A1032", "name": "星宝"}], "type": "D", "id": "D840", "name": "沙溪镇"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D841", "name": "神湾镇"}, {"parent_id": "C283", "children": [ {"parent_id": "D842", "children": [], "type": "A", "id": "A3002", "name": "峰华28广场"}, {"parent_id": "D842", "children": [], "type": "A", "id": "A3700", "name": "兴中广场"}, {"parent_id": "D842", "children": [], "type": "A", "id": "A1033", "name": "大信新都汇"}, {"parent_id": "D842", "children": [], "type": "A", "id": "A1984", "name": "逢源商业街"}, {"parent_id": "D842", "children": [], "type": "A", "id": "A2562", "name": "孙文步行街"}, {"parent_id": "D842", "children": [], "type": "A", "id": "A3379", "name": "泰安路"}], "type": "D", "id": "D842", "name": "石岐区"}, {"parent_id": "C283", "children": [], "type": "D", "id": "D843", "name": "坦洲镇"}], "type": "C", "id": "C283", "name": "中山"}, {"parent_id": "P11", "children": [ {"parent_id": "C282", "children": [ {"parent_id": "D819", "children": [], "type": "A", "id": "A2557", "name": "小市体育馆"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A1976", "name": "洲心"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A4442", "name": "松岗市场"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A127", "name": "上下廓街"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A3984", "name": "东城"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A782", "name": "南门街"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A4232", "name": "锦绣清城/大润发"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A3697", "name": "小市桥南"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A1194", "name": "城市花园"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A3376", "name": "新城汽车站"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A2998", "name": "东方巴黎/凤城世家"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A1023", "name": "赢之城"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A348", "name": "城市广场"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A1043", "name": "广泰商业街"}, {"parent_id": "D819", "children": [], "type": "A", "id": "A542", "name": "北门街"}], "type": "D", "id": "D819", "name": "清城区"}, {"parent_id": "C282", "children": [], "type": "D", "id": "D818", "name": "连州市"}, {"parent_id": "C282", "children": [], "type": "D", "id": "D822", "name": "英德市"}, {"parent_id": "C282", "children": [ {"parent_id": "D820", "children": [], "type": "A", "id": "A2558", "name": "笔架路"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A1977", "name": "广硕文化广场"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A4443", "name": "城北汽车站"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A128", "name": "美林广场"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A3985", "name": "中山路"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A4233", "name": "清和大道"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A3698", "name": "明霞大道"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A3377", "name": "玄真路"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A2999", "name": "骏豪城"}, {"parent_id": "D820", "children": [], "type": "A", "id": "A1024", "name": "恒大世纪旅游城"}], "type": "D", "id": "D820", "name": "清新区"}, {"parent_id": "C282", "children": [], "type": "D", "id": "D821", "name": "阳山县"}, {"parent_id": "C282", "children": [], "type": "D", "id": "D817", "name": "连南瑶族自治县"}, {"parent_id": "C282", "children": [], "type": "D", "id": "D816", "name": "佛冈县"}], "type": "C", "id": "C282", "name": "清远"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C281", "name": "阳江"}, {"parent_id": "P11", "children": [], "type": "C", "id": "C280", "name": "河源"}], "type": "P", "id": "P11", "name": "广东"}, {"parent_id": "N1", "children": [ {"parent_id": "P10", "children": [ {"parent_id": "C427", "children": [ {"parent_id": "D1051", "children": [], "type": "A", "id": "A3460", "name": "麓谷"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A163", "name": "岳麓大学城"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A1328", "name": "奥克斯广场"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A2672", "name": "观沙岭/茶子山"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A4487", "name": "市政府"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A4288", "name": "涉外经济学院"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A569", "name": "阳光100"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A3770", "name": "汽车西站"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A3095", "name": "含浦"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A4048", "name": "商学院/人人乐"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A380", "name": "溁湾镇"}, {"parent_id": "D1051", "children": [], "type": "A", "id": "A2149", "name": "步步高广场"}], "type": "D", "id": "D1051", "name": "岳麓区"}, {"parent_id": "C427", "children": [], "type": "D", "id": "D1050", "name": "望城县"}, {"parent_id": "C427", "children": [ {"parent_id": "D1052", "children": [], "type": "A", "id": "A1109", "name": "武广高铁"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A3461", "name": "桂花路/车站南路"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A3096", "name": "高桥"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A164", "name": "树木岭"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1320", "name": "雨花亭"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1329", "name": "奥特莱斯/环保路"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A2673", "name": "德政园/杨家山"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A570", "name": "体育新城"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A4488", "name": "汽车南站"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A4289", "name": "民政学院/香樟路"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1218", "name": "喜盈门"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1390", "name": "窑岭/长岭"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A2150", "name": "东塘"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1488", "name": "左家塘"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A1435", "name": "梓园路/省儿童医院"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A3771", "name": "红星会展中心"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A871", "name": "铁道学院"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A4049", "name": "井湾子"}, {"parent_id": "D1052", "children": [], "type": "A", "id": "A381", "name": "识字岭"}], "type": "D", "id": "D1052", "name": "雨花区"}, {"parent_id": "C427", "children": [ {"parent_id": "D1046", "children": [], "type": "A", "id": "A161", "name": "月湖公园/长沙大学"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A1325", "name": "四方坪"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A4485", "name": "湘雅附一医院"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A3768", "name": "世界之窗/国际会展中心"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A4286", "name": "湘江世纪城"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A3457", "name": "松桂园"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A378", "name": "中山亭/乐和城"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A567", "name": "珠江花城/万国城"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A2669", "name": "马栏山/鸭子铺"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A3092", "name": "芙蓉广场"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A4046", "name": "伍家岭"}, {"parent_id": "D1046", "children": [], "type": "A", "id": "A2146", "name": "开福万达广场"}], "type": "D", "id": "D1046", "name": "开福区"}, {"parent_id": "C427", "children": [], "type": "D", "id": "D1047", "name": "浏阳市"}, {"parent_id": "C427", "children": [ {"parent_id": "D1044", "children": [], "type": "A", "id": "A1323", "name": "步行街"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A4483", "name": "筑梦园"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A3766", "name": "星沙通程广场"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A4284", "name": "易初莲花"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A3455", "name": "泉塘/星城国际"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A2667", "name": "大众传媒"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A3090", "name": "黄花镇/黄花机场"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A4044", "name": "星沙一桥"}, {"parent_id": "D1044", "children": [], "type": "A", "id": "A2144", "name": "城西安置小区"}], "type": "D", "id": "D1044", "name": "长沙县"}, {"parent_id": "C427", "children": [ {"parent_id": "D1045", "children": [], "type": "A", "id": "A1388", "name": "袁家岭/火车站"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A1107", "name": "五一广场"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A160", "name": "汽车东站"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A1324", "name": "八一路"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A4484", "name": "梦泽园"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A3767", "name": "韭菜园"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A4285", "name": "马王堆"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A869", "name": "省委"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A377", "name": "芙蓉广场"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A1216", "name": "五里牌"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A3456", "name": "湖南农业大学"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A566", "name": "司门口"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A1318", "name": "晚报大道"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A2668", "name": "德政园"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A3091", "name": "古曲路/浏阳河婚庆文化园"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A4045", "name": "烈士公园"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A1433", "name": "人民中路/朝阳路/融圣国际"}, {"parent_id": "D1045", "children": [], "type": "A", "id": "A2145", "name": "八一桥"}], "type": "D", "id": "D1045", "name": "芙蓉区"}, {"parent_id": "C427", "children": [ {"parent_id": "D1048", "children": [], "type": "A", "id": "A1326", "name": "东站"}, {"parent_id": "D1048", "children": [], "type": "A", "id": "A2670", "name": "南站"}, {"parent_id": "D1048", "children": [], "type": "A", "id": "A3458", "name": "沿江风光带外滩"}, {"parent_id": "D1048", "children": [], "type": "A", "id": "A3093", "name": "人人乐/大润发"}, {"parent_id": "D1048", "children": [], "type": "A", "id": "A2147", "name": "灰汤温泉镇"}], "type": "D", "id": "D1048", "name": "宁乡县"}, {"parent_id": "C427", "children": [ {"parent_id": "D1049", "children": [], "type": "A", "id": "A1389", "name": "天心阁"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A1108", "name": "识字岭"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A162", "name": "坡子街"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A1327", "name": "步行街"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A2671", "name": "侯家塘"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A4486", "name": "南门口"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A3769", "name": "解放西路"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A4287", "name": "摩天轮"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A379", "name": "浦沅"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A1217", "name": "铁道/林科大"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A3459", "name": "贺龙体育场"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A568", "name": "人民西路口"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A1319", "name": "天虹"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A870", "name": "省政府"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A3094", "name": "黄土岭"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A4047", "name": "劳动广场/书院路"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A1434", "name": "新开铺"}, {"parent_id": "D1049", "children": [], "type": "A", "id": "A2148", "name": "定王台"}], "type": "D", "id": "D1049", "name": "天心区"}], "type": "C", "id": "C427", "name": "长沙"}, {"parent_id": "P10", "children": [ {"parent_id": "C258", "children": [], "type": "D", "id": "D761", "name": "临澧县"}, {"parent_id": "C258", "children": [], "type": "D", "id": "D760", "name": "汉寿县"}, {"parent_id": "C258", "children": [], "type": "D", "id": "D763", "name": "桃源县"}, {"parent_id": "C258", "children": [], "type": "D", "id": "D762", "name": "澧县"}, {"parent_id": "C258", "children": [], "type": "D", "id": "D765", "name": "安乡县"}, {"parent_id": "C258", "children": [ {"parent_id": "D764", "children": [], "type": "A", "id": "A1369", "name": "下南门"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A538", "name": "文理学院"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A3688", "name": "文化宫"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A778", "name": "光荣路"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A2984", "name": "大润发"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A120", "name": "不夜城"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A3975", "name": "火车站"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A1294", "name": "皂果路"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A960", "name": "紫桥"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A1948", "name": "三闾路"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A1191", "name": "武陵大道"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A4435", "name": "水星楼"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A4224", "name": "步行街"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A342", "name": "高山街"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A1040", "name": "东门"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A2539", "name": "梅尼广场"}, {"parent_id": "D764", "children": [], "type": "A", "id": "A3364", "name": "市政府"}], "type": "D", "id": "D764", "name": "武陵区"}, {"parent_id": "C258", "children": [ {"parent_id": "D759", "children": [], "type": "A", "id": "A1947", "name": "桥南"}, {"parent_id": "D759", "children": [], "type": "A", "id": "A959", "name": "德山十字路口"}], "type": "D", "id": "D759", "name": "鼎城区"}], "type": "C", "id": "C258", "name": "常德"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C259", "name": "张家界"}, {"parent_id": "P10", "children": [ {"parent_id": "C253", "children": [ {"parent_id": "D732", "children": [], "type": "A", "id": "A1938", "name": "田心"}, {"parent_id": "D732", "children": [], "type": "A", "id": "A949", "name": "响石广场"}, {"parent_id": "D732", "children": [], "type": "A", "id": "A2530", "name": "清石广场"}], "type": "D", "id": "D732", "name": "石峰区"}, {"parent_id": "C253", "children": [ {"parent_id": "D733", "children": [], "type": "A", "id": "A1939", "name": "红旗广场"}, {"parent_id": "D733", "children": [], "type": "A", "id": "A950", "name": "华润万家"}, {"parent_id": "D733", "children": [], "type": "A", "id": "A2531", "name": "合泰街"}], "type": "D", "id": "D733", "name": "荷塘区"}, {"parent_id": "C253", "children": [], "type": "D", "id": "D731", "name": "茶陵县"}, {"parent_id": "C253", "children": [ {"parent_id": "D736", "children": [], "type": "A", "id": "A1941", "name": "长江广场"}, {"parent_id": "D736", "children": [], "type": "A", "id": "A2533", "name": "沿江风光带"}, {"parent_id": "D736", "children": [], "type": "A", "id": "A952", "name": "神农城"}], "type": "D", "id": "D736", "name": "天元区"}, {"parent_id": "C253", "children": [], "type": "D", "id": "D737", "name": "株洲县"}, {"parent_id": "C253", "children": [ {"parent_id": "D735", "children": [], "type": "A", "id": "A4222", "name": "火车站"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A3686", "name": "徐家桥步行街"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A3973", "name": "七星潮流购物广场"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A1940", "name": "平和堂"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A2978", "name": "王府井"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A2532", "name": "汉华国际"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A3360", "name": "贺家土"}, {"parent_id": "D735", "children": [], "type": "A", "id": "A951", "name": "中心广场"}], "type": "D", "id": "D735", "name": "芦淞区"}, {"parent_id": "C253", "children": [], "type": "D", "id": "D734", "name": "醴陵市"}], "type": "C", "id": "C253", "name": "株洲"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C254", "name": "湘潭"}, {"parent_id": "P10", "children": [ {"parent_id": "C255", "children": [ {"parent_id": "D749", "children": [], "type": "A", "id": "A2982", "name": "苗圃"}, {"parent_id": "D749", "children": [], "type": "A", "id": "A1945", "name": "湘江东路沿线"}, {"parent_id": "D749", "children": [], "type": "A", "id": "A2537", "name": "冶金"}, {"parent_id": "D749", "children": [], "type": "A", "id": "A957", "name": "东风东路沿线"}], "type": "D", "id": "D749", "name": "珠晖区"}, {"parent_id": "C255", "children": [ {"parent_id": "D748", "children": [], "type": "A", "id": "A2981", "name": "华新步步高商场"}, {"parent_id": "D748", "children": [], "type": "A", "id": "A3362", "name": "船山实验中学"}, {"parent_id": "D748", "children": [], "type": "A", "id": "A2536", "name": "华新开发区"}, {"parent_id": "D748", "children": [], "type": "A", "id": "A1944", "name": "立新开发区"}, {"parent_id": "D748", "children": [], "type": "A", "id": "A956", "name": "南华大学"}], "type": "D", "id": "D748", "name": "蒸湘区"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D743", "name": "衡阳县"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D742", "name": "衡山县"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D741", "name": "衡南县"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D740", "name": "衡东县"}, {"parent_id": "C255", "children": [ {"parent_id": "D747", "children": [], "type": "A", "id": "A3361", "name": "老师院/八中"}, {"parent_id": "D747", "children": [], "type": "A", "id": "A2980", "name": "白沙洲广场"}, {"parent_id": "D747", "children": [], "type": "A", "id": "A1943", "name": "中山南路"}, {"parent_id": "D747", "children": [], "type": "A", "id": "A2535", "name": "岳屏公园"}, {"parent_id": "D747", "children": [], "type": "A", "id": "A955", "name": "崇尚广场"}], "type": "D", "id": "D747", "name": "雁峰区"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D746", "name": "祁东县"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D745", "name": "南岳区"}, {"parent_id": "C255", "children": [ {"parent_id": "D744", "children": [], "type": "A", "id": "A954", "name": "耒阳"}], "type": "D", "id": "D744", "name": "耒阳市"}, {"parent_id": "C255", "children": [], "type": "D", "id": "D738", "name": "常宁市"}, {"parent_id": "C255", "children": [ {"parent_id": "D739", "children": [], "type": "A", "id": "A1942", "name": "石鼓广场"}, {"parent_id": "D739", "children": [], "type": "A", "id": "A2979", "name": "西湖公园"}, {"parent_id": "D739", "children": [], "type": "A", "id": "A2534", "name": "莲湖广场"}, {"parent_id": "D739", "children": [], "type": "A", "id": "A953", "name": "解放路口"}], "type": "D", "id": "D739", "name": "石鼓区"}], "type": "C", "id": "C255", "name": "衡阳"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C256", "name": "邵阳"}, {"parent_id": "P10", "children": [ {"parent_id": "C257", "children": [], "type": "D", "id": "D758", "name": "云溪区"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D750", "name": "华容县"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D751", "name": "君山区"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D752", "name": "临湘市"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D753", "name": "汨罗市"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D754", "name": "平江县"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D755", "name": "湘阴县"}, {"parent_id": "C257", "children": [ {"parent_id": "D756", "children": [], "type": "A", "id": "A537", "name": "八字门"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A4223", "name": "火车站"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A3687", "name": "南湖"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A3363", "name": "美食街"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A777", "name": "岳城"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A2983", "name": "汴河街"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A3974", "name": "国大"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A119", "name": "泰和"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A1946", "name": "天伦城"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A4434", "name": "奇家岭"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A341", "name": "花板桥"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A2538", "name": "新路口"}, {"parent_id": "D756", "children": [], "type": "A", "id": "A958", "name": "步行街"}], "type": "D", "id": "D756", "name": "岳阳楼区"}, {"parent_id": "C257", "children": [], "type": "D", "id": "D757", "name": "岳阳县"}], "type": "C", "id": "C257", "name": "岳阳"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C261", "name": "郴州"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C260", "name": "益阳"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C263", "name": "怀化"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C262", "name": "永州"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C265", "name": "湘西"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C264", "name": "娄底"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C267", "name": "耒阳"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C266", "name": "凤凰"}, {"parent_id": "P10", "children": [], "type": "C", "id": "C268", "name": "宁乡"}], "type": "P", "id": "P10", "name": "湖南"}, {"parent_id": "N1", "children": [ {"parent_id": "P9", "children": [], "type": "C", "id": "C236", "name": "十堰"}, {"parent_id": "P9", "children": [ {"parent_id": "C237", "children": [], "type": "D", "id": "D691", "name": "五峰土家族自治县"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D690", "name": "东山开发区"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D695", "name": "兴山县"}, {"parent_id": "C237", "children": [ {"parent_id": "D694", "children": [], "type": "A", "id": "A773", "name": "夷陵广场"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A2962", "name": "403"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A335", "name": "华祥"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A113", "name": "卓悦广场"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A927", "name": "CBD"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A3676", "name": "北门"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A4214", "name": "国贸商圈"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A1920", "name": "葛洲坝"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A3964", "name": "铁路坝"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A1037", "name": "云集路商圈"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A533", "name": "解放路步行街"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A4427", "name": "东门"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A2513", "name": "绿萝路"}, {"parent_id": "D694", "children": [], "type": "A", "id": "A3349", "name": "星火路"}], "type": "D", "id": "D694", "name": "西陵区"}, {"parent_id": "C237", "children": [ {"parent_id": "D697", "children": [], "type": "A", "id": "A928", "name": "小溪塔"}], "type": "D", "id": "D697", "name": "夷陵区"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D696", "name": "宜都市"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D693", "name": "猇亭区"}, {"parent_id": "C237", "children": [ {"parent_id": "D692", "children": [], "type": "A", "id": "A1919", "name": "五一广场"}, {"parent_id": "D692", "children": [], "type": "A", "id": "A2961", "name": "隆康路"}, {"parent_id": "D692", "children": [], "type": "A", "id": "A926", "name": "万达"}, {"parent_id": "D692", "children": [], "type": "A", "id": "A3675", "name": "胜利三路"}, {"parent_id": "D692", "children": [], "type": "A", "id": "A2512", "name": "胜利四路"}, {"parent_id": "D692", "children": [], "type": "A", "id": "A3348", "name": "南湖公园"}], "type": "D", "id": "D692", "name": "伍家岗区"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D699", "name": "枝江市"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D698", "name": "长阳土家族自治县"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D689", "name": "点军区"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D700", "name": "秭归县"}, {"parent_id": "C237", "children": [], "type": "D", "id": "D688", "name": "当阳市"}], "type": "C", "id": "C237", "name": "宜昌"}, {"parent_id": "P9", "children": [ {"parent_id": "C235", "children": [], "type": "D", "id": "D684", "name": "铁山区"}, {"parent_id": "C235", "children": [ {"parent_id": "D685", "children": [], "type": "A", "id": "A1917", "name": "老下陆"}, {"parent_id": "D685", "children": [], "type": "A", "id": "A923", "name": "新下陆"}], "type": "D", "id": "D685", "name": "下陆区"}, {"parent_id": "C235", "children": [ {"parent_id": "D682", "children": [], "type": "A", "id": "A1915", "name": "步行街/大上海"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A2960", "name": "湖师/沈家营"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A921", "name": "青山湖/延安路"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A3674", "name": "新百/国贸"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A3963", "name": "芜湖路/华新路"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A2510", "name": "黄石大桥/天方花园"}, {"parent_id": "D682", "children": [], "type": "A", "id": "A3347", "name": "湖滨大道/亚光新村"}], "type": "D", "id": "D682", "name": "黄石港区"}, {"parent_id": "C235", "children": [ {"parent_id": "D683", "children": [], "type": "A", "id": "A1916", "name": "团城山开发区"}, {"parent_id": "D683", "children": [], "type": "A", "id": "A922", "name": "花湖开发区"}, {"parent_id": "D683", "children": [], "type": "A", "id": "A2511", "name": "黄金山开发区"}], "type": "D", "id": "D683", "name": "黄石经济开发区"}, {"parent_id": "C235", "children": [ {"parent_id": "D681", "children": [], "type": "A", "id": "A1914", "name": "雨润广场/观山路"}, {"parent_id": "D681", "children": [], "type": "A", "id": "A920", "name": "东风路/黄狮蟹"}], "type": "D", "id": "D681", "name": "大冶市"}, {"parent_id": "C235", "children": [ {"parent_id": "D686", "children": [], "type": "A", "id": "A1918", "name": "上窑/西塞山"}, {"parent_id": "D686", "children": [], "type": "A", "id": "A924", "name": "陈家湾/八卦嘴"}], "type": "D", "id": "D686", "name": "西塞山区"}, {"parent_id": "C235", "children": [ {"parent_id": "D687", "children": [], "type": "A", "id": "A925", "name": "兴国镇"}], "type": "D", "id": "D687", "name": "阳新县"}], "type": "C", "id": "C235", "name": "黄石"}, {"parent_id": "P9", "children": [ {"parent_id": "C238", "children": [ {"parent_id": "D707", "children": [], "type": "A", "id": "A1923", "name": "襄州"}, {"parent_id": "D707", "children": [], "type": "A", "id": "A931", "name": "二汽"}], "type": "D", "id": "D707", "name": "襄州区"}, {"parent_id": "C238", "children": [ {"parent_id": "D706", "children": [], "type": "A", "id": "A2964", "name": "胜利街"}, {"parent_id": "D706", "children": [], "type": "A", "id": "A1922", "name": "檀溪路"}, {"parent_id": "D706", "children": [], "type": "A", "id": "A2515", "name": "闸口"}, {"parent_id": "D706", "children": [], "type": "A", "id": "A930", "name": "鼓楼"}], "type": "D", "id": "D706", "name": "襄城区"}, {"parent_id": "C238", "children": [], "type": "D", "id": "D705", "name": "南漳县"}, {"parent_id": "C238", "children": [], "type": "D", "id": "D704", "name": "老河口市"}, {"parent_id": "C238", "children": [], "type": "D", "id": "D703", "name": "谷城县"}, {"parent_id": "C238", "children": [ {"parent_id": "D702", "children": [], "type": "A", "id": "A2963", "name": "人民广场"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A3350", "name": "华洋堂"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A929", "name": "沃尔玛"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A3677", "name": "鱼梁洲"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A4215", "name": "火车站"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A1921", "name": "华丰路"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A3965", "name": "沿江大道"}, {"parent_id": "D702", "children": [], "type": "A", "id": "A2514", "name": "万达"}], "type": "D", "id": "D702", "name": "樊城区"}, {"parent_id": "C238", "children": [], "type": "D", "id": "D701", "name": "保康县"}, {"parent_id": "C238", "children": [ {"parent_id": "D709", "children": [], "type": "A", "id": "A2965", "name": "汽车站"}, {"parent_id": "D709", "children": [], "type": "A", "id": "A1924", "name": "东园"}, {"parent_id": "D709", "children": [], "type": "A", "id": "A932", "name": "中心商业区"}, {"parent_id": "D709", "children": [], "type": "A", "id": "A2516", "name": "南城"}], "type": "D", "id": "D709", "name": "枣阳市"}, {"parent_id": "C238", "children": [], "type": "D", "id": "D708", "name": "宜城市"}], "type": "C", "id": "C238", "name": "襄阳"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C239", "name": "鄂州"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C250", "name": "枣阳"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C251", "name": "仙桃"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C252", "name": "三峡"}, {"parent_id": "P9", "children": [ {"parent_id": "C374", "children": [ {"parent_id": "D994", "children": [], "type": "A", "id": "A2086", "name": "吴家山"}, {"parent_id": "D994", "children": [], "type": "A", "id": "A1221", "name": "常青花园"}], "type": "D", "id": "D994", "name": "东西湖区"}, {"parent_id": "C374", "children": [], "type": "D", "id": "D995", "name": "汉南区"}, {"parent_id": "C374", "children": [], "type": "D", "id": "D993", "name": "蔡甸区"}, {"parent_id": "C374", "children": [ {"parent_id": "D996", "children": [], "type": "A", "id": "A2087", "name": "王家湾"}, {"parent_id": "D996", "children": [], "type": "A", "id": "A2630", "name": "腰路堤/建港"}, {"parent_id": "D996", "children": [], "type": "A", "id": "A3058", "name": "钟家村"}, {"parent_id": "D996", "children": [], "type": "A", "id": "A3425", "name": "沌口"}, {"parent_id": "D996", "children": [], "type": "A", "id": "A1222", "name": "琴台"}], "type": "D", "id": "D996", "name": "汉阳区"}, {"parent_id": "C374", "children": [], "type": "D", "id": "D998", "name": "黄陂区"}, {"parent_id": "C374", "children": [ {"parent_id": "D999", "children": [], "type": "A", "id": "A3741", "name": "武汉广场"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A2089", "name": "江汉路步行街"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A2632", "name": "菱角湖"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A3060", "name": "六渡桥/汉正街"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A3427", "name": "青年路/常青路"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A4022", "name": "西北湖"}, {"parent_id": "D999", "children": [], "type": "A", "id": "A1224", "name": "汉口火车站"}], "type": "D", "id": "D999", "name": "江汉区"}, {"parent_id": "C374", "children": [ {"parent_id": "D997", "children": [], "type": "A", "id": "A4264", "name": "珞狮南路"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A2088", "name": "东湖风景区"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A3740", "name": "黄家湖大学城"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A2631", "name": "光谷/鲁巷"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A3059", "name": "光谷天地"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A3426", "name": "虎泉/关西"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A4021", "name": "南湖城市广场"}, {"parent_id": "D997", "children": [], "type": "A", "id": "A1223", "name": "石碑岭/街道口"}], "type": "D", "id": "D997", "name": "洪山区"}, {"parent_id": "C374", "children": [ {"parent_id": "D1002", "children": [], "type": "A", "id": "A2092", "name": "仙桃市"}, {"parent_id": "D1002", "children": [], "type": "A", "id": "A1227", "name": "潜江市"}], "type": "D", "id": "D1002", "name": "近郊"}, {"parent_id": "C374", "children": [ {"parent_id": "D1003", "children": [], "type": "A", "id": "A3429", "name": "武胜路"}, {"parent_id": "D1003", "children": [], "type": "A", "id": "A2635", "name": "硚口路"}, {"parent_id": "D1003", "children": [], "type": "A", "id": "A3063", "name": "武胜路凯德广场"}, {"parent_id": "D1003", "children": [], "type": "A", "id": "A2093", "name": "汉西"}, {"parent_id": "D1003", "children": [], "type": "A", "id": "A1228", "name": "古田路"}], "type": "D", "id": "D1003", "name": "硚口区"}, {"parent_id": "C374", "children": [ {"parent_id": "D1000", "children": [], "type": "A", "id": "A4265", "name": "竹叶山/花桥"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A3428", "name": "三阳路/澳门路"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A2633", "name": "解放公园/永清街"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A3061", "name": "客运港/江滩"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A4468", "name": "竹叶山/后湖"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A2090", "name": "吉庆街/大智路"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A4023", "name": "武汉天地"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A1225", "name": "百步亭/二七"}, {"parent_id": "D1000", "children": [], "type": "A", "id": "A3742", "name": "台北路/香港路"}], "type": "D", "id": "D1000", "name": "江岸区"}, {"parent_id": "C374", "children": [ {"parent_id": "D1001", "children": [], "type": "A", "id": "A2634", "name": "庙山"}, {"parent_id": "D1001", "children": [], "type": "A", "id": "A3062", "name": "纸坊"}, {"parent_id": "D1001", "children": [], "type": "A", "id": "A2091", "name": "大花岭"}, {"parent_id": "D1001", "children": [], "type": "A", "id": "A1226", "name": "藏龙岛"}], "type": "D", "id": "D1001", "name": "江夏区"}, {"parent_id": "C374", "children": [], "type": "D", "id": "D1006", "name": "新洲区"}, {"parent_id": "C374", "children": [ {"parent_id": "D1004", "children": [], "type": "A", "id": "A4266", "name": "武钢厂区/武东"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A2636", "name": "红钢城/沿港路"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A3064", "name": "欢乐大道/仁和路"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A4469", "name": "余家头/四美塘"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A2094", "name": "工业路"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A3743", "name": "铁机/柴林花园"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A4024", "name": "武汉火车站/杨春湖"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A1229", "name": "奥山/钢都花园"}, {"parent_id": "D1004", "children": [], "type": "A", "id": "A3430", "name": "建二/八大家"}], "type": "D", "id": "D1004", "name": "青山区"}, {"parent_id": "C374", "children": [ {"parent_id": "D1005", "children": [], "type": "A", "id": "A559", "name": "岳家嘴/东亭"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A2637", "name": "付家坡/大东门"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A4470", "name": "司门口"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A3065", "name": "和平大道积玉桥"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A1230", "name": "白沙洲"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A4267", "name": "首义汇/阅马场"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A2095", "name": "丁字桥/石牌岭"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A818", "name": "中南路/洪山广场"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A3431", "name": "汉街/水果湖"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A150", "name": "武昌火车站"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A3744", "name": "汉街"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A369", "name": "徐东大街"}, {"parent_id": "D1005", "children": [], "type": "A", "id": "A4025", "name": "南湖花园"}], "type": "D", "id": "D1005", "name": "武昌区"}], "type": "C", "id": "C374", "name": "武汉"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C249", "name": "当阳"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C248", "name": "神农架"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C243", "name": "黄冈"}, {"parent_id": "P9", "children": [ {"parent_id": "C242", "children": [], "type": "D", "id": "D714", "name": "监利县"}, {"parent_id": "C242", "children": [ {"parent_id": "D715", "children": [], "type": "A", "id": "A2966", "name": "荆东路"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A3351", "name": "张居正街"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A3678", "name": "小北门"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A4216", "name": "南环路"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A1925", "name": "东门"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A3966", "name": "老南门"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A935", "name": "花台"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A2517", "name": "荆北路"}, {"parent_id": "D715", "children": [], "type": "A", "id": "A4428", "name": "新南门"}], "type": "D", "id": "D715", "name": "荆州区"}, {"parent_id": "C242", "children": [ {"parent_id": "D716", "children": [], "type": "A", "id": "A1596", "name": "时尚广场"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1368", "name": "武德路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A534", "name": "园林路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1681", "name": "中山路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A774", "name": "红门路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1512", "name": "北京西路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A2967", "name": "文化宫"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1293", "name": "江津路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1038", "name": "塔桥路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A336", "name": "公园路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1421", "name": "大庆路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A3352", "name": "红星路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A114", "name": "长港路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A3679", "name": "安良百货"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A4217", "name": "女人街"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1926", "name": "沙隆达广场"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1190", "name": "太岳路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A3967", "name": "江汉南路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A1477", "name": "北京东路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A2518", "name": "中央大道"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A4429", "name": "江汉北路"}, {"parent_id": "D716", "children": [], "type": "A", "id": "A936", "name": "美佳华"}], "type": "D", "id": "D716", "name": "沙市区"}, {"parent_id": "C242", "children": [], "type": "D", "id": "D717", "name": "松滋市"}, {"parent_id": "C242", "children": [], "type": "D", "id": "D710", "name": "石首市"}, {"parent_id": "C242", "children": [], "type": "D", "id": "D711", "name": "公安县"}, {"parent_id": "C242", "children": [], "type": "D", "id": "D712", "name": "洪湖市"}, {"parent_id": "C242", "children": [], "type": "D", "id": "D713", "name": "江陵县"}], "type": "C", "id": "C242", "name": "荆州"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C241", "name": "孝感"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C240", "name": "荆门"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C247", "name": "武当山"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C246", "name": "恩施"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C245", "name": "随州"}, {"parent_id": "P9", "children": [], "type": "C", "id": "C244", "name": "咸宁"}], "type": "P", "id": "P9", "name": "湖北"}, {"parent_id": "N1", "children": [ {"parent_id": "P5", "children": [ {"parent_id": "C159", "children": [ {"parent_id": "D468", "children": [], "type": "A", "id": "A792", "name": "罗源县"}, {"parent_id": "D468", "children": [], "type": "A", "id": "A2435", "name": "马尾区"}, {"parent_id": "D468", "children": [], "type": "A", "id": "A1825", "name": "闽侯县"}, {"parent_id": "D468", "children": [], "type": "A", "id": "A3286", "name": "永泰县"}, {"parent_id": "D468", "children": [], "type": "A", "id": "A2890", "name": "闽清县"}], "type": "D", "id": "D468", "name": "近郊"}, {"parent_id": "C159", "children": [ {"parent_id": "D469", "children": [], "type": "A", "id": "A793", "name": "东区/鼓山"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A2436", "name": "福飞路/新店"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A3916", "name": "省图书馆/六一北路"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A4174", "name": "泰禾广场"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A1826", "name": "福新路/塔头"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A4391", "name": "五四北"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A509", "name": "岳峰镇"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A82", "name": "五里亭"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A290", "name": "象园"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A3287", "name": "金鸡山公园"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A2891", "name": "火车站"}, {"parent_id": "D469", "children": [], "type": "A", "id": "A3622", "name": "建材市场/茶会"}], "type": "D", "id": "D469", "name": "晋安区"}, {"parent_id": "C159", "children": [ {"parent_id": "D466", "children": [], "type": "A", "id": "A4389", "name": "万达广场"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A790", "name": "成龙步行街"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A2433", "name": "公安局办证中心"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A3914", "name": "龙田镇"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A4172", "name": "南门"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A1823", "name": "东门"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A2888", "name": "好又多"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A80", "name": "西门"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A3284", "name": "宏路"}, {"parent_id": "D466", "children": [], "type": "A", "id": "A3620", "name": "街心公园"}], "type": "D", "id": "D466", "name": "福清市"}, {"parent_id": "C159", "children": [ {"parent_id": "D467", "children": [], "type": "A", "id": "A791", "name": "东街口"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A289", "name": "乌山西路"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A2434", "name": "鼓屏路/屏山公园"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A3915", "name": "铜盘路/软件园"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A4173", "name": "五一广场"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A738", "name": "左海/西湖公园"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A1824", "name": "五四路/福州广场"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A2889", "name": "金牛山/洪山桥"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A4390", "name": "乌山/冠亚广场"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A508", "name": "西禅寺"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A81", "name": "温泉公园/华林路"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A3285", "name": "蒙古营"}, {"parent_id": "D467", "children": [], "type": "A", "id": "A3621", "name": "省体/湖前"}], "type": "D", "id": "D467", "name": "鼓楼区"}, {"parent_id": "C159", "children": [ {"parent_id": "D465", "children": [], "type": "A", "id": "A4388", "name": "金山大润发"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A288", "name": "农林大学"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A2432", "name": "福湾"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A986", "name": "上渡建材"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A3913", "name": "红坊海峡创意产业园"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A4171", "name": "金山新华都"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A1822", "name": "仓山万达"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A2887", "name": "盖山"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A1278", "name": "新西客站"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A737", "name": "三叉街"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A1175", "name": "学生街"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A3619", "name": "黄山"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A789", "name": "白湖亭"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A507", "name": "榕城广场"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A3283", "name": "火车南站"}, {"parent_id": "D465", "children": [], "type": "A", "id": "A79", "name": "建新镇"}], "type": "D", "id": "D465", "name": "仓山区"}, {"parent_id": "C159", "children": [], "type": "D", "id": "D471", "name": "平潭县"}, {"parent_id": "C159", "children": [], "type": "D", "id": "D470", "name": "连江县"}, {"parent_id": "C159", "children": [ {"parent_id": "D473", "children": [], "type": "A", "id": "A795", "name": "步行街"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A2438", "name": "长山湖"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A3918", "name": "罗马花园"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A4176", "name": "闽运汽车站"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A1828", "name": "冰心公园"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A4393", "name": "南山"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A84", "name": "市标"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A291", "name": "西洋"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A3289", "name": "河下街"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A2893", "name": "东关"}, {"parent_id": "D473", "children": [], "type": "A", "id": "A3624", "name": "锦江花园"}], "type": "D", "id": "D473", "name": "长乐市"}, {"parent_id": "C159", "children": [ {"parent_id": "D472", "children": [], "type": "A", "id": "A794", "name": "万象城/宝龙广场"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A2437", "name": "工业路/茶亭"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A3917", "name": "台江万达"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A4175", "name": "台江广场/元洪城"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A1827", "name": "大利嘉/汽车南站"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A4392", "name": "中亭街"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A83", "name": "中亭街"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A3288", "name": "工业路/博美诗邦"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A2892", "name": "工业路/群升国际"}, {"parent_id": "D472", "children": [], "type": "A", "id": "A3623", "name": "黎明/小柳市场"}], "type": "D", "id": "D472", "name": "台江区"}], "type": "C", "id": "C159", "name": "福州"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C170", "name": "晋江"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C168", "name": "福清"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C169", "name": "长乐"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C166", "name": "龙岩"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C167", "name": "宁德"}, {"parent_id": "P5", "children": [ {"parent_id": "C164", "children": [], "type": "D", "id": "D498", "name": "东山县"}, {"parent_id": "C164", "children": [ {"parent_id": "D505", "children": [], "type": "A", "id": "A810", "name": "万新商业广场"}, {"parent_id": "D505", "children": [], "type": "A", "id": "A1839", "name": "永嘉天地"}], "type": "D", "id": "D505", "name": "漳浦县"}, {"parent_id": "C164", "children": [], "type": "D", "id": "D504", "name": "云霄县"}, {"parent_id": "C164", "children": [ {"parent_id": "D501", "children": [], "type": "A", "id": "A808", "name": "云水谣景区"}], "type": "D", "id": "D501", "name": "南靖县"}, {"parent_id": "C164", "children": [ {"parent_id": "D500", "children": [], "type": "A", "id": "A807", "name": "万达广场"}], "type": "D", "id": "D500", "name": "龙文区"}, {"parent_id": "C164", "children": [ {"parent_id": "D503", "children": [], "type": "A", "id": "A513", "name": "大通北路"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A809", "name": "中闽"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A3297", "name": "夜市"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A2901", "name": "商业城"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A4181", "name": "天下广场"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A2447", "name": "大学城"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A3631", "name": "闽师大"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A4398", "name": "世纪广场"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A88", "name": "延安广场"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A3924", "name": "大润发"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A295", "name": "沃尔玛"}, {"parent_id": "D503", "children": [], "type": "A", "id": "A1838", "name": "一七五商圈"}], "type": "D", "id": "D503", "name": "芗城区"}, {"parent_id": "C164", "children": [], "type": "D", "id": "D502", "name": "平和县"}, {"parent_id": "C164", "children": [ {"parent_id": "D499", "children": [], "type": "A", "id": "A806", "name": "角美"}, {"parent_id": "D499", "children": [], "type": "A", "id": "A1837", "name": "石码"}], "type": "D", "id": "D499", "name": "龙海市"}], "type": "C", "id": "C164", "name": "漳州"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C165", "name": "南平"}, {"parent_id": "P5", "children": [], "type": "C", "id": "C162", "name": "三明"}, {"parent_id": "P5", "children": [ {"parent_id": "C163", "children": [], "type": "D", "id": "D486", "name": "石狮市"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D487", "name": "德化县"}, {"parent_id": "C163", "children": [ {"parent_id": "D488", "children": [], "type": "A", "id": "A512", "name": "泉秀路"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A802", "name": "丰泽广场"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A3294", "name": "侨乡体育馆"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A4180", "name": "国贸商城"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A2444", "name": "六灌路"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A4397", "name": "中心客运站商圈"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A87", "name": "领SHOW天地"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A741", "name": "宝洲路"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A294", "name": "浦西万达广场"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A1834", "name": "东海"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A2898", "name": "大洋百货"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A3629", "name": "丰泽街"}, {"parent_id": "D488", "children": [], "type": "A", "id": "A3922", "name": "现代广场"}], "type": "D", "id": "D488", "name": "丰泽区"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D489", "name": "惠安县"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D495", "name": "泉港区"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D494", "name": "清濛开发区"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D497", "name": "永春县"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D496", "name": "安溪县"}, {"parent_id": "C163", "children": [], "type": "D", "id": "D493", "name": "南安市"}, {"parent_id": "C163", "children": [ {"parent_id": "D492", "children": [], "type": "A", "id": "A805", "name": "华侨大学"}], "type": "D", "id": "D492", "name": "洛江区"}, {"parent_id": "C163", "children": [ {"parent_id": "D491", "children": [], "type": "A", "id": "A804", "name": "美食街"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A3296", "name": "T淘园"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A2900", "name": "九一路"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A2446", "name": "文庙"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A3630", "name": "凯德广场"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A1836", "name": "中山路"}, {"parent_id": "D491", "children": [], "type": "A", "id": "A3923", "name": "文化宫"}], "type": "D", "id": "D491", "name": "鲤城区"}, {"parent_id": "C163", "children": [ {"parent_id": "D490", "children": [], "type": "A", "id": "A3295", "name": "阳光广场"}, {"parent_id": "D490", "children": [], "type": "A", "id": "A2445", "name": "万达广场"}, {"parent_id": "D490", "children": [], "type": "A", "id": "A803", "name": "晋江时代广场"}, {"parent_id": "D490", "children": [], "type": "A", "id": "A1835", "name": "池店"}, {"parent_id": "D490", "children": [], "type": "A", "id": "A2899", "name": "SM广场"}], "type": "D", "id": "D490", "name": "晋江市"}], "type": "C", "id": "C163", "name": "泉州"}, {"parent_id": "P5", "children": [ {"parent_id": "C160", "children": [], "type": "D", "id": "D480", "name": "翔安区"}, {"parent_id": "C160", "children": [], "type": "D", "id": "D479", "name": "同安区"}, {"parent_id": "C160", "children": [ {"parent_id": "D478", "children": [], "type": "A", "id": "A799", "name": "白鹭洲公园"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A510", "name": "文灶/火车站"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A987", "name": "仙岳路沿线"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A4178", "name": "莲花"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A739", "name": "卧龙晓城"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A3291", "name": "湖滨北路东段"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A2441", "name": "禾祥西路沿线"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A1176", "name": "中山路/轮渡"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A4395", "name": "罗宾森广场"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A85", "name": "瑞景"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A3920", "name": "莲前大道"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A292", "name": "厦门大学"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A1831", "name": "环岛路沿线"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A2895", "name": "湖滨北路西段"}, {"parent_id": "D478", "children": [], "type": "A", "id": "A3626", "name": "莲坂/火车站"}], "type": "D", "id": "D478", "name": "思明区"}, {"parent_id": "C160", "children": [ {"parent_id": "D475", "children": [], "type": "A", "id": "A796", "name": "阿罗海城市广场"}], "type": "D", "id": "D475", "name": "海沧区"}, {"parent_id": "C160", "children": [], "type": "D", "id": "D474", "name": "鼓浪屿"}, {"parent_id": "C160", "children": [ {"parent_id": "D477", "children": [], "type": "A", "id": "A798", "name": "集美学村"}, {"parent_id": "D477", "children": [], "type": "A", "id": "A2440", "name": "杏林"}, {"parent_id": "D477", "children": [], "type": "A", "id": "A1830", "name": "集美万达广场"}], "type": "D", "id": "D477", "name": "集美区"}, {"parent_id": "C160", "children": [ {"parent_id": "D476", "children": [], "type": "A", "id": "A797", "name": "东渡路"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A2439", "name": "江头"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A3919", "name": "塘边"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A4177", "name": "万达广场"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A3290", "name": "SM城市广场"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A1829", "name": "湖里公园"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A4394", "name": "五缘湾乐都汇"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A2894", "name": "金尚小区"}, {"parent_id": "D476", "children": [], "type": "A", "id": "A3625", "name": "TBK枋湖客运中心"}], "type": "D", "id": "D476", "name": "湖里区"}], "type": "C", "id": "C160", "name": "厦门"}, {"parent_id": "P5", "children": [ {"parent_id": "C161", "children": [], "type": "D", "id": "D482", "name": "涵江区"}, {"parent_id": "C161", "children": [ {"parent_id": "D483", "children": [], "type": "A", "id": "A801", "name": "新汽车站"}, {"parent_id": "D483", "children": [], "type": "A", "id": "A3293", "name": "金鼎广场"}, {"parent_id": "D483", "children": [], "type": "A", "id": "A2443", "name": "文献步行街"}, {"parent_id": "D483", "children": [], "type": "A", "id": "A1833", "name": "正荣时代广场"}, {"parent_id": "D483", "children": [], "type": "A", "id": "A2897", "name": "体育中心"}, {"parent_id": "D483", "children": [], "type": "A", "id": "A3628", "name": "天九湾"}], "type": "D", "id": "D483", "name": "荔城区"}, {"parent_id": "C161", "children": [], "type": "D", "id": "D484", "name": "仙游县"}, {"parent_id": "C161", "children": [ {"parent_id": "D481", "children": [], "type": "A", "id": "A511", "name": "南门"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A800", "name": "万达广场"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A4179", "name": "莆田学院"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A3292", "name": "市政府"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A2442", "name": "名店女人街"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A4396", "name": "大唐广场"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A86", "name": "荔城南大道"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A3921", "name": "荔城中大道"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A740", "name": "沟头圆圈"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A293", "name": "北磨"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A1832", "name": "田尾圆圈"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A2896", "name": "三信电子城"}, {"parent_id": "D481", "children": [], "type": "A", "id": "A3627", "name": "高楼"}], "type": "D", "id": "D481", "name": "城厢区"}, {"parent_id": "C161", "children": [], "type": "D", "id": "D485", "name": "秀屿区"}], "type": "C", "id": "C161", "name": "莆田"}], "type": "P", "id": "P5", "name": "福建"}, {"parent_id": "N1", "children": [ {"parent_id": "P12", "children": [ {"parent_id": "C215", "children": [ {"parent_id": "D633", "children": [], "type": "A", "id": "A3660", "name": "塘沽城区"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A3950", "name": "新港"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A2942", "name": "汉沽城区"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A2491", "name": "大港学府路"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A884", "name": "大港城区"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A1892", "name": "大港油田"}, {"parent_id": "D633", "children": [], "type": "A", "id": "A3331", "name": "经济开发区"}], "type": "D", "id": "D633", "name": "滨海新区"}, {"parent_id": "C215", "children": [ {"parent_id": "D637", "children": [], "type": "A", "id": "A4419", "name": "土城"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A3664", "name": "南楼"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A4206", "name": "图书大厦"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A770", "name": "新业广场"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A1188", "name": "永安道"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A3953", "name": "体院北"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A2946", "name": "乐园道"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A2495", "name": "尖山"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A1292", "name": "越秀路"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A888", "name": "宾西"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A108", "name": "佟楼"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A1016", "name": "友谊路"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A3335", "name": "梅江"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A529", "name": "下瓦房"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A1896", "name": "挂甲寺"}, {"parent_id": "D637", "children": [], "type": "A", "id": "A327", "name": "小海地"}], "type": "D", "id": "D637", "name": "河西区"}, {"parent_id": "C215", "children": [ {"parent_id": "D636", "children": [], "type": "A", "id": "A3952", "name": "西康路沿线"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A2945", "name": "鞍山道沿线"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A2494", "name": "南市"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A887", "name": "滨江道"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A3334", "name": "五大道"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A3663", "name": "小白楼"}, {"parent_id": "D636", "children": [], "type": "A", "id": "A1895", "name": "和平路"}], "type": "D", "id": "D636", "name": "和平区"}, {"parent_id": "C215", "children": [ {"parent_id": "D635", "children": [], "type": "A", "id": "A4418", "name": "卫国道"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A3662", "name": "河东万达广场"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A4205", "name": "天津站后广场"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A3951", "name": "万新村"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A2944", "name": "二宫"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A2493", "name": "大桥道"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A886", "name": "大王庄"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A3333", "name": "工业大学"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A107", "name": "中山门"}, {"parent_id": "D635", "children": [], "type": "A", "id": "A1894", "name": "大直沽"}], "type": "D", "id": "D635", "name": "河东区"}, {"parent_id": "C215", "children": [ {"parent_id": "D634", "children": [], "type": "A", "id": "A3661", "name": "中山路"}, {"parent_id": "D634", "children": [], "type": "A", "id": "A2943", "name": "王串场/民权门"}, {"parent_id": "D634", "children": [], "type": "A", "id": "A2492", "name": "天泰路/榆关道"}, {"parent_id": "D634", "children": [], "type": "A", "id": "A885", "name": "金钟河大街"}, {"parent_id": "D634", "children": [], "type": "A", "id": "A3332", "name": "意大利风情区/火车站"}, {"parent_id": "D634", "children": [], "type": "A", "id": "A1893", "name": "狮子林大街"}], "type": "D", "id": "D634", "name": "河北区"}, {"parent_id": "C215", "children": [ {"parent_id": "D639", "children": [], "type": "A", "id": "A4208", "name": "武清区"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A3955", "name": "宁河县"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A3666", "name": "蓟县"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A2948", "name": "津南区"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A2497", "name": "东丽区"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A3337", "name": "静海县"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A1898", "name": "宝坻区"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A890", "name": "北辰区"}, {"parent_id": "D639", "children": [], "type": "A", "id": "A4421", "name": "西青区"}], "type": "D", "id": "D639", "name": "近郊"}, {"parent_id": "C215", "children": [ {"parent_id": "D638", "children": [], "type": "A", "id": "A3665", "name": "凯莱赛/西沽"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A4207", "name": "邵公庄/创意街"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A3954", "name": "鹏欣水游城/大丰路"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A2947", "name": "大胡同/天津之眼"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A2496", "name": "丁字沽"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A889", "name": "本溪路"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A3336", "name": "芥园道/复兴路"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A4420", "name": "天津西站/欧亚达"}, {"parent_id": "D638", "children": [], "type": "A", "id": "A1897", "name": "水木天成"}], "type": "D", "id": "D638", "name": "红桥区"}, {"parent_id": "C215", "children": [ {"parent_id": "D158", "children": [], "type": "A", "id": "A2770", "name": "华南广场"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A3835", "name": "山东路沿线"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A1629", "name": "万达广场"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A3529", "name": "南关岭"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A4331", "name": "周水子"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A3180", "name": "凌水镇/理工大学"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A2293", "name": "高新园区"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A4101", "name": "小平岛"}, {"parent_id": "D158", "children": [], "type": "A", "id": "A406", "name": "春柳东特购物广场"}], "type": "D", "id": "D158", "name": "甘井子区"}, {"parent_id": "C215", "children": [ {"parent_id": "D159", "children": [], "type": "A", "id": "A2771", "name": "庄河市"}, {"parent_id": "D159", "children": [], "type": "A", "id": "A1630", "name": "普兰店市"}, {"parent_id": "D159", "children": [], "type": "A", "id": "A3181", "name": "长海县"}, {"parent_id": "D159", "children": [], "type": "A", "id": "A2294", "name": "瓦房店市"}, {"parent_id": "D159", "children": [], "type": "A", "id": "A407", "name": "金石滩"}], "type": "D", "id": "D159", "name": "近郊"}, {"parent_id": "C215", "children": [ {"parent_id": "D640", "children": [], "type": "A", "id": "A4209", "name": "南开大学/八里台"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A1189", "name": "咸阳路/黄河道"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A771", "name": "天拖地区"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A3956", "name": "海光寺/六里台"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A3667", "name": "老城厢/鼓楼"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A2949", "name": "大悦城"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A2498", "name": "长虹公园"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A109", "name": "时代奥城"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A1017", "name": "王顶堤/华苑"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A530", "name": "天佑城/西南角"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A3338", "name": "乐天/新世界/远东百货"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A1899", "name": "白堤路/风荷园"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A891", "name": "鞍山西道"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A328", "name": "水上/天塔"}, {"parent_id": "D640", "children": [], "type": "A", "id": "A4422", "name": "南开公园/中学/医院"}], "type": "D", "id": "D640", "name": "南开区"}, {"parent_id": "C215", "children": [ {"parent_id": "D165", "children": [], "type": "A", "id": "A2774", "name": "老虎滩"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A3837", "name": "胜利广场/青泥洼桥"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A410", "name": "二七广场"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A653", "name": "中南路"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A4333", "name": "天津街"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A1633", "name": "港湾广场"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A3184", "name": "民主广场"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A463", "name": "中山广场/延安路"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A2297", "name": "解放路沿线"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A4103", "name": "三八广场"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A3532", "name": "人民路"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A30", "name": "桃源"}, {"parent_id": "D165", "children": [], "type": "A", "id": "A222", "name": "友好广场"}], "type": "D", "id": "D165", "name": "中山区"}, {"parent_id": "C215", "children": [ {"parent_id": "D164", "children": [], "type": "A", "id": "A2773", "name": "大菜市/站北广场"}, {"parent_id": "D164", "children": [], "type": "A", "id": "A1632", "name": "八一路沿线"}, {"parent_id": "D164", "children": [], "type": "A", "id": "A3183", "name": "人民广场/新开路"}, {"parent_id": "D164", "children": [], "type": "A", "id": "A2296", "name": "北京街"}, {"parent_id": "D164", "children": [], "type": "A", "id": "A3531", "name": "五一广场"}, {"parent_id": "D164", "children": [], "type": "A", "id": "A409", "name": "奥林匹克广场"}], "type": "D", "id": "D164", "name": "西岗区"}, {"parent_id": "C215", "children": [ {"parent_id": "D163", "children": [], "type": "A", "id": "A2772", "name": "黑石礁"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A3836", "name": "软件园/数码广场"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A4332", "name": "西安路沿线"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A29", "name": "星海湾/星海广场"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A2295", "name": "黄河路沿线"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A1631", "name": "和平广场"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A3182", "name": "解放广场"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A4102", "name": "太原街沿线"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A462", "name": "星海公园"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A3530", "name": "马栏子"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A408", "name": "白山路"}, {"parent_id": "D163", "children": [], "type": "A", "id": "A221", "name": "星海湾"}], "type": "D", "id": "D163", "name": "沙河口区"}, {"parent_id": "C215", "children": [], "type": "D", "id": "D162", "name": "旅顺口区"}, {"parent_id": "C215", "children": [], "type": "D", "id": "D161", "name": "开发区"}, {"parent_id": "C215", "children": [], "type": "D", "id": "D160", "name": "金州区"}], "type": "C", "id": "C215", "name": "天津"}], "type": "P", "id": "P12", "name": "天津"}, {"parent_id": "N1", "children": [ {"parent_id": "P7", "children": [ {"parent_id": "C194", "children": [], "type": "D", "id": "D589", "name": "金乡县"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D588", "name": "嘉祥县"}, {"parent_id": "C194", "children": [ {"parent_id": "D592", "children": [], "type": "A", "id": "A1880", "name": "亿丰时代广场"}, {"parent_id": "D592", "children": [], "type": "A", "id": "A865", "name": "佳世客"}, {"parent_id": "D592", "children": [], "type": "A", "id": "A2480", "name": "济安桥路"}, {"parent_id": "D592", "children": [], "type": "A", "id": "A2932", "name": "车站西路"}], "type": "D", "id": "D592", "name": "任城区"}, {"parent_id": "C194", "children": [ {"parent_id": "D593", "children": [], "type": "A", "id": "A4410", "name": "科苑路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A99", "name": "车站东路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A4197", "name": "古槐路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A1881", "name": "火车站"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A521", "name": "江南春美食街"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A866", "name": "运河城"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A3651", "name": "新体育馆"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A748", "name": "秀水城"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A305", "name": "洸河路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A3942", "name": "大润发"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A2481", "name": "吴泰闸路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A2933", "name": "共青团路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A993", "name": "火炬路"}, {"parent_id": "D593", "children": [], "type": "A", "id": "A3322", "name": "东银座"}], "type": "D", "id": "D593", "name": "市中区"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D590", "name": "梁山县"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D591", "name": "曲阜市"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D596", "name": "汶上县"}, {"parent_id": "C194", "children": [ {"parent_id": "D597", "children": [], "type": "A", "id": "A4411", "name": "龙桥南路"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A4198", "name": "南护城河路"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A1182", "name": "贵和/银座"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A1882", "name": "体育馆"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A867", "name": "火车站"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A522", "name": "圣德国际酒店"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A1357", "name": "九州商厦"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A3652", "name": "北师范"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A749", "name": "九州方圆"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A306", "name": "少陵公园"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A3943", "name": "农高园"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A1416", "name": "兴隆庄镇"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A1284", "name": "广场商厦"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A2482", "name": "大禹像"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A2934", "name": "东关"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A994", "name": "九州大道"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A3323", "name": "鼓楼"}, {"parent_id": "D597", "children": [], "type": "A", "id": "A100", "name": "博物馆"}], "type": "D", "id": "D597", "name": "兖州区"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D594", "name": "泗水县"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D595", "name": "微山县"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D598", "name": "鱼台县"}, {"parent_id": "C194", "children": [], "type": "D", "id": "D599", "name": "邹城市"}], "type": "C", "id": "C194", "name": "济宁"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C214", "name": "新泰"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C210", "name": "文登"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C211", "name": "乳山"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C212", "name": "曲阜"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C213", "name": "邹平"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C197", "name": "日照"}, {"parent_id": "P7", "children": [ {"parent_id": "C196", "children": [ {"parent_id": "D606", "children": [], "type": "A", "id": "A4413", "name": "车管所"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A4200", "name": "新闻大厦"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A1184", "name": "幸福广场"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A1884", "name": "钦村"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A524", "name": "海悦国际"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A3654", "name": "寨子"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A872", "name": "自由东方"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A308", "name": "哈工大"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A3945", "name": "小商品"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A751", "name": "山大"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A2484", "name": "凤凰城"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A2936", "name": "张村"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A996", "name": "国际海水浴场"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A3325", "name": "田村"}, {"parent_id": "D606", "children": [], "type": "A", "id": "A102", "name": "利群商厦"}], "type": "D", "id": "D606", "name": "高区"}, {"parent_id": "C196", "children": [ {"parent_id": "D607", "children": [], "type": "A", "id": "A1959", "name": "远遥"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A4414", "name": "山花大厦"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A2123", "name": "银座商场"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A4201", "name": "会展中心"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1510", "name": "市政府"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1185", "name": "振华商厦"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1885", "name": "威胜"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A997", "name": "华联"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1579", "name": "实验中学"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1805", "name": "海港大厦"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A525", "name": "菊花顶"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1359", "name": "市立医院"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A3655", "name": "名座"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1679", "name": "财富广场"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A873", "name": "三联家电"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A309", "name": "威高广场"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A3946", "name": "骨科医院"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A752", "name": "华联购物"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1286", "name": "西门"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A2485", "name": "银座家居"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A2937", "name": "大润发"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1475", "name": "西北山"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A2070", "name": "振华奥特莱斯"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A3326", "name": "抱海"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A2161", "name": "韩国风情街"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A103", "name": "尚城国际"}, {"parent_id": "D607", "children": [], "type": "A", "id": "A1418", "name": "大世界"}], "type": "D", "id": "D607", "name": "环翠区"}, {"parent_id": "C196", "children": [ {"parent_id": "D608", "children": [], "type": "A", "id": "A4415", "name": "九隆大厦"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A4202", "name": "蒿泊"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A1886", "name": "威海公园"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A310", "name": "皇冠"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A526", "name": "乐天玛特"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A3656", "name": "长峰"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A874", "name": "佳世客"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A3947", "name": "百度城"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A753", "name": "九龙城"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A2486", "name": "羊亭"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A2938", "name": "新港"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A3327", "name": "凤林"}, {"parent_id": "D608", "children": [], "type": "A", "id": "A104", "name": "齐鲁商城"}], "type": "D", "id": "D608", "name": "经济开发区"}, {"parent_id": "C196", "children": [ {"parent_id": "D609", "children": [], "type": "A", "id": "A1887", "name": "义乌小商品"}, {"parent_id": "D609", "children": [], "type": "A", "id": "A3657", "name": "中信银行"}, {"parent_id": "D609", "children": [], "type": "A", "id": "A875", "name": "石岛管理区"}, {"parent_id": "D609", "children": [], "type": "A", "id": "A2487", "name": "威百商厦"}, {"parent_id": "D609", "children": [], "type": "A", "id": "A2939", "name": "大润发"}, {"parent_id": "D609", "children": [], "type": "A", "id": "A3328", "name": "振华商厦"}], "type": "D", "id": "D609", "name": "荣成市"}, {"parent_id": "C196", "children": [], "type": "D", "id": "D611", "name": "文登市"}, {"parent_id": "C196", "children": [], "type": "D", "id": "D610", "name": "乳山市"}], "type": "C", "id": "C196", "name": "威海"}, {"parent_id": "P7", "children": [ {"parent_id": "C195", "children": [ {"parent_id": "D604", "children": [], "type": "A", "id": "A1958", "name": "云海美食城"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A4412", "name": "岱道庵路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2122", "name": "擂鼓石大街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A4199", "name": "青年路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1183", "name": "迎胜路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2185", "name": "长途汽车站"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1883", "name": "齐鲁银座"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A523", "name": "长城路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A868", "name": "火车站广场"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1578", "name": "金桥服装城"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2215", "name": "泰山大街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1804", "name": "银泰中心"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2069", "name": "东湖公园"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1358", "name": "花园银座"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A3653", "name": "灵山大街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1678", "name": "宝龙城市广场"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2329", "name": "科山路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1509", "name": "市政广场"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A307", "name": "新汽车站"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A3944", "name": "龙潭路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1417", "name": "银座城市广场"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A750", "name": "南湖路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1285", "name": "银座奥特莱斯"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2483", "name": "上河桥"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2257", "name": "岱宗银座"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2935", "name": "校场街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2207", "name": "温州步行街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A1474", "name": "大润发"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A995", "name": "文化路"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A3324", "name": "财源街"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A2160", "name": "岱庙"}, {"parent_id": "D604", "children": [], "type": "A", "id": "A101", "name": "红门路"}], "type": "D", "id": "D604", "name": "泰山区"}, {"parent_id": "C195", "children": [], "type": "D", "id": "D605", "name": "新泰市"}, {"parent_id": "C195", "children": [], "type": "D", "id": "D602", "name": "肥城市"}, {"parent_id": "C195", "children": [], "type": "D", "id": "D603", "name": "宁阳县"}, {"parent_id": "C195", "children": [], "type": "D", "id": "D600", "name": "岱岳区"}, {"parent_id": "C195", "children": [], "type": "D", "id": "D601", "name": "东平县"}], "type": "C", "id": "C195", "name": "泰安"}, {"parent_id": "P7", "children": [ {"parent_id": "C193", "children": [ {"parent_id": "D585", "children": [], "type": "A", "id": "A2478", "name": "渤海路"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A863", "name": "东城全福元"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A3650", "name": "潍坊科技学院"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A3941", "name": "银座商城"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A2930", "name": "新汽车站"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A3321", "name": "正阳路"}, {"parent_id": "D585", "children": [], "type": "A", "id": "A1878", "name": "缤纷五洲"}], "type": "D", "id": "D585", "name": "寿光市"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D584", "name": "安丘市"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D587", "name": "诸城市"}, {"parent_id": "C193", "children": [ {"parent_id": "D586", "children": [], "type": "A", "id": "A2479", "name": "火车站"}, {"parent_id": "D586", "children": [], "type": "A", "id": "A864", "name": "中百"}, {"parent_id": "D586", "children": [], "type": "A", "id": "A2931", "name": "金沙广场"}, {"parent_id": "D586", "children": [], "type": "A", "id": "A1879", "name": "万家福"}], "type": "D", "id": "D586", "name": "潍城区"}, {"parent_id": "C193", "children": [ {"parent_id": "D581", "children": [], "type": "A", "id": "A3648", "name": "银座"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A2476", "name": "新华路佳乐家"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A861", "name": "泰华"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A2928", "name": "凯德广场"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A3319", "name": "东盛广场"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A3940", "name": "圣荣"}, {"parent_id": "D581", "children": [], "type": "A", "id": "A1876", "name": "振华"}], "type": "D", "id": "D581", "name": "奎文区"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D580", "name": "寒亭区"}, {"parent_id": "C193", "children": [ {"parent_id": "D583", "children": [], "type": "A", "id": "A3649", "name": "南环路"}, {"parent_id": "D583", "children": [], "type": "A", "id": "A2477", "name": "宋城"}, {"parent_id": "D583", "children": [], "type": "A", "id": "A862", "name": "海岱路"}, {"parent_id": "D583", "children": [], "type": "A", "id": "A2929", "name": "大润发/泰丰购物广场"}, {"parent_id": "D583", "children": [], "type": "A", "id": "A3320", "name": "青都"}, {"parent_id": "D583", "children": [], "type": "A", "id": "A1877", "name": "中都"}], "type": "D", "id": "D583", "name": "青州市"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D582", "name": "临朐县"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D578", "name": "高密市"}, {"parent_id": "C193", "children": [ {"parent_id": "D579", "children": [], "type": "A", "id": "A860", "name": "谷德"}], "type": "D", "id": "D579", "name": "高新区"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D575", "name": "昌乐县"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D576", "name": "昌邑市"}, {"parent_id": "C193", "children": [], "type": "D", "id": "D577", "name": "坊子区"}], "type": "C", "id": "C193", "name": "潍坊"}, {"parent_id": "P7", "children": [ {"parent_id": "C192", "children": [], "type": "D", "id": "D573", "name": "招远市"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D563", "name": "海阳市"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D562", "name": "高新区"}, {"parent_id": "C192", "children": [ {"parent_id": "D561", "children": [], "type": "A", "id": "A856", "name": "福海路"}], "type": "D", "id": "D561", "name": "福山区"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D567", "name": "莱州市"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D566", "name": "莱阳市"}, {"parent_id": "C192", "children": [ {"parent_id": "D564", "children": [], "type": "A", "id": "A2473", "name": "泰山路"}, {"parent_id": "D564", "children": [], "type": "A", "id": "A2925", "name": "珠江路"}, {"parent_id": "D564", "children": [], "type": "A", "id": "A857", "name": "彩云城"}, {"parent_id": "D564", "children": [], "type": "A", "id": "A1873", "name": "长江路"}], "type": "D", "id": "D564", "name": "开发区"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D569", "name": "牟平区"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D568", "name": "龙口市"}, {"parent_id": "C192", "children": [ {"parent_id": "D565", "children": [], "type": "A", "id": "A2474", "name": "万象城"}, {"parent_id": "D565", "children": [], "type": "A", "id": "A2926", "name": "迎春大街"}, {"parent_id": "D565", "children": [], "type": "A", "id": "A858", "name": "滨海路"}, {"parent_id": "D565", "children": [], "type": "A", "id": "A1874", "name": "佳世客"}], "type": "D", "id": "D565", "name": "莱山区"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D570", "name": "蓬莱市"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D571", "name": "栖霞市"}, {"parent_id": "C192", "children": [ {"parent_id": "D574", "children": [], "type": "A", "id": "A4409", "name": "南洪街"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A98", "name": "青年路"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A3647", "name": "环山路"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A4196", "name": "南大街"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A2475", "name": "东方巴黎"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A3939", "name": "鲁东大学"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A1181", "name": "幸福"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A520", "name": "世茂广场"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A2927", "name": "大海阳路"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A3318", "name": "二马路"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A747", "name": "三站"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A859", "name": "北马路"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A1356", "name": "振华商厦"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A304", "name": "上夼美食街"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A1283", "name": "阳光100"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A992", "name": "文化宫"}, {"parent_id": "D574", "children": [], "type": "A", "id": "A1875", "name": "百盛"}], "type": "D", "id": "D574", "name": "芝罘区"}, {"parent_id": "C192", "children": [], "type": "D", "id": "D572", "name": "长岛县"}], "type": "C", "id": "C192", "name": "烟台"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C198", "name": "莱芜"}, {"parent_id": "P7", "children": [ {"parent_id": "C187", "children": [], "type": "D", "id": "D528", "name": "章丘市"}, {"parent_id": "C187", "children": [ {"parent_id": "D527", "children": [], "type": "A", "id": "A842", "name": "北园大街"}, {"parent_id": "D527", "children": [], "type": "A", "id": "A1860", "name": "缤纷五洲"}, {"parent_id": "D527", "children": [], "type": "A", "id": "A2462", "name": "火车站/堤口路"}, {"parent_id": "D527", "children": [], "type": "A", "id": "A2914", "name": "泺口"}, {"parent_id": "D527", "children": [], "type": "A", "id": "A3308", "name": "无影山"}], "type": "D", "id": "D527", "name": "天桥区"}, {"parent_id": "C187", "children": [ {"parent_id": "D526", "children": [], "type": "A", "id": "A92", "name": "阳光新路"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A516", "name": "中华小吃城"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A4403", "name": "伟东新都"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A841", "name": "八一银座"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A4187", "name": "体育中心"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A3638", "name": "万达广场"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A2461", "name": "大众广场"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A298", "name": "中海环宇城"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A2913", "name": "杆石桥"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A3930", "name": "青龙小区"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A3307", "name": "济大/会展中心"}, {"parent_id": "D526", "children": [], "type": "A", "id": "A1859", "name": "大观园"}], "type": "D", "id": "D526", "name": "市中区"}, {"parent_id": "C187", "children": [ {"parent_id": "D525", "children": [], "type": "A", "id": "A91", "name": "山大南/北路"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A515", "name": "文化东/西路"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A4402", "name": "千佛山公园"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A840", "name": "奥体中心"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A3306", "name": "恒隆广场"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A989", "name": "玉函银座"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A4186", "name": "泉城广场"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A3637", "name": "解放路"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A1178", "name": "银座新天地"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A2460", "name": "芙蓉街"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A743", "name": "燕山地区"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A3929", "name": "泺源大街"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A297", "name": "山师东路"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A1280", "name": "朝山街"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A2912", "name": "佛山街"}, {"parent_id": "D525", "children": [], "type": "A", "id": "A1858", "name": "大明湖"}], "type": "D", "id": "D525", "name": "历下区"}, {"parent_id": "C187", "children": [ {"parent_id": "D523", "children": [], "type": "A", "id": "A2458", "name": "商河县"}, {"parent_id": "D523", "children": [], "type": "A", "id": "A838", "name": "济阳县"}, {"parent_id": "D523", "children": [], "type": "A", "id": "A1856", "name": "平阴县"}], "type": "D", "id": "D523", "name": "近郊"}, {"parent_id": "C187", "children": [ {"parent_id": "D522", "children": [], "type": "A", "id": "A837", "name": "和谐广场"}, {"parent_id": "D522", "children": [], "type": "A", "id": "A1855", "name": "西市场"}], "type": "D", "id": "D522", "name": "槐荫区"}, {"parent_id": "C187", "children": [ {"parent_id": "D521", "children": [], "type": "A", "id": "A836", "name": "银座"}], "type": "D", "id": "D521", "name": "高新区"}, {"parent_id": "C187", "children": [ {"parent_id": "D520", "children": [], "type": "A", "id": "A835", "name": "长清"}], "type": "D", "id": "D520", "name": "长清区"}, {"parent_id": "C187", "children": [ {"parent_id": "D524", "children": [], "type": "A", "id": "A2459", "name": "洪家楼"}, {"parent_id": "D524", "children": [], "type": "A", "id": "A839", "name": "二环东路"}, {"parent_id": "D524", "children": [], "type": "A", "id": "A2911", "name": "华龙路沿线"}, {"parent_id": "D524", "children": [], "type": "A", "id": "A1857", "name": "工业南路"}], "type": "D", "id": "D524", "name": "历城区"}], "type": "C", "id": "C187", "name": "济南"}, {"parent_id": "P7", "children": [ {"parent_id": "C188", "children": [ {"parent_id": "D538", "children": [], "type": "A", "id": "A3643", "name": "台东"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A4192", "name": "新业广场"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A3935", "name": "万达CBD"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A3313", "name": "市北家乐福"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A848", "name": "大港/小港"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A1866", "name": "科技街"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A2467", "name": "浮山后"}, {"parent_id": "D538", "children": [], "type": "A", "id": "A2919", "name": "南京路北段"}], "type": "D", "id": "D538", "name": "市北区"}, {"parent_id": "C188", "children": [ {"parent_id": "D540", "children": [], "type": "A", "id": "A2921", "name": "四方利群"}, {"parent_id": "D540", "children": [], "type": "A", "id": "A3315", "name": "小村庄"}, {"parent_id": "D540", "children": [], "type": "A", "id": "A1868", "name": "海琴广场"}, {"parent_id": "D540", "children": [], "type": "A", "id": "A2469", "name": "青岛理工大学"}, {"parent_id": "D540", "children": [], "type": "A", "id": "A850", "name": "海云庵"}], "type": "D", "id": "D540", "name": "四方区"}, {"parent_id": "C188", "children": [ {"parent_id": "D539", "children": [], "type": "A", "id": "A96", "name": "香港中路沿线"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A3644", "name": "海景花园大酒店"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A4193", "name": "闽江路"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A518", "name": "云霄路"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A4407", "name": "世贸中心"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A3936", "name": "麦凯乐"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A849", "name": "百丽广场"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A2920", "name": "火车站/团岛"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A3314", "name": "汇泉湾"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A1867", "name": "大润发"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A1179", "name": "湛山/太平角"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A1354", "name": "镇宁桥"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A2468", "name": "浮山所"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A745", "name": "远洋广场"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A302", "name": "心海广场"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A1281", "name": "中联广场"}, {"parent_id": "D539", "children": [], "type": "A", "id": "A990", "name": "银海大世界"}], "type": "D", "id": "D539", "name": "市南区"}, {"parent_id": "C188", "children": [ {"parent_id": "D536", "children": [], "type": "A", "id": "A95", "name": "维客广场"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A3642", "name": "李村"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A4191", "name": "山东外贸学院"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A4406", "name": "书院路"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A3934", "name": "李村公园"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A3312", "name": "李沧宝龙"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A847", "name": "沧口"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A1865", "name": "东李鞋城"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A2466", "name": "金水路"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A301", "name": "万年泉路"}, {"parent_id": "D536", "children": [], "type": "A", "id": "A2918", "name": "君峰路沿线"}], "type": "D", "id": "D536", "name": "李沧区"}, {"parent_id": "C188", "children": [], "type": "D", "id": "D537", "name": "平度市"}, {"parent_id": "C188", "children": [ {"parent_id": "D529", "children": [], "type": "A", "id": "A93", "name": "时代中心"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A3931", "name": "农业大学"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A843", "name": "宝龙城市广场"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A3309", "name": "华城路"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A4404", "name": "世纪公园"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A1861", "name": "春阳路"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A3639", "name": "流亭机场/重庆北路"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A4188", "name": "青特上豪/家佳源"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A2463", "name": "东方城"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A299", "name": "中城路"}, {"parent_id": "D529", "children": [], "type": "A", "id": "A2915", "name": "国货"}], "type": "D", "id": "D529", "name": "城阳区"}, {"parent_id": "C188", "children": [], "type": "D", "id": "D534", "name": "莱西市"}, {"parent_id": "C188", "children": [ {"parent_id": "D535", "children": [], "type": "A", "id": "A3641", "name": "麦岛"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A4190", "name": "香港东路沿线"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A3933", "name": "青岛大学"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A846", "name": "大拇指广场"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A3311", "name": "崂山风景区"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A1864", "name": "石老人海水浴场"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A2465", "name": "极地海洋世界"}, {"parent_id": "D535", "children": [], "type": "A", "id": "A2917", "name": "丽达购物广场"}], "type": "D", "id": "D535", "name": "崂山区"}, {"parent_id": "C188", "children": [], "type": "D", "id": "D530", "name": "胶南市"}, {"parent_id": "C188", "children": [], "type": "D", "id": "D531", "name": "胶州市"}, {"parent_id": "C188", "children": [ {"parent_id": "D532", "children": [], "type": "A", "id": "A844", "name": "宝龙城市广场"}, {"parent_id": "D532", "children": [], "type": "A", "id": "A1862", "name": "新利群商场"}], "type": "D", "id": "D532", "name": "即墨市"}, {"parent_id": "C188", "children": [ {"parent_id": "D533", "children": [], "type": "A", "id": "A94", "name": "石油大学"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A3640", "name": "金沙滩风景区"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A517", "name": "香江路"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A3932", "name": "科技大学"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A845", "name": "保税区"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A4405", "name": "马濠公园"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A3310", "name": "家佳源佳世客"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A1863", "name": "长江路沿线"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A4189", "name": "老黄岛"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A2464", "name": "丁家河"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A744", "name": "紫金山路"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A300", "name": "上流汇"}, {"parent_id": "D533", "children": [], "type": "A", "id": "A2916", "name": "官厅"}], "type": "D", "id": "D533", "name": "黄岛区"}], "type": "C", "id": "C188", "name": "青岛"}, {"parent_id": "P7", "children": [ {"parent_id": "C189", "children": [], "type": "D", "id": "D545", "name": "沂源县"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D544", "name": "临淄区"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D547", "name": "周村区"}, {"parent_id": "C189", "children": [ {"parent_id": "D546", "children": [], "type": "A", "id": "A4408", "name": "中润大道"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A97", "name": "植物园"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A3645", "name": "凯德广场"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A4194", "name": "尚美第三城"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A2470", "name": "联通路"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A519", "name": "步行街"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A3937", "name": "佳世客"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A1180", "name": "明清街"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A2922", "name": "潘南路"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A3316", "name": "世纪路"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A1869", "name": "茂业天地"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A1355", "name": "彩世界"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A746", "name": "美食街"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A851", "name": "义乌小商品城"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A303", "name": "火车站"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A1282", "name": "大润发"}, {"parent_id": "D546", "children": [], "type": "A", "id": "A991", "name": "王府井"}], "type": "D", "id": "D546", "name": "张店区"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D541", "name": "博山区"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D543", "name": "桓台县"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D542", "name": "高青县"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D549", "name": "邹平县"}, {"parent_id": "C189", "children": [], "type": "D", "id": "D548", "name": "淄川区"}], "type": "C", "id": "C189", "name": "淄博"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C207", "name": "寿光"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C206", "name": "龙口"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C205", "name": "章丘"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C204", "name": "兖州"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C203", "name": "菏泽"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C202", "name": "滨州"}, {"parent_id": "P7", "children": [ {"parent_id": "C201", "children": [], "type": "D", "id": "D632", "name": "阳谷县"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D631", "name": "莘县"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D630", "name": "临清市"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D624", "name": "茌平县"}, {"parent_id": "C201", "children": [ {"parent_id": "D625", "children": [], "type": "A", "id": "A1361", "name": "铁塔商场"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A4417", "name": "阿尔卡迪亚"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A4204", "name": "振兴西路"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A755", "name": "昌润路"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A1187", "name": "香江"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A2941", "name": "综合楼"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A312", "name": "专医院"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A3330", "name": "兴华西路"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A1420", "name": "中级法院"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A528", "name": "五星广场"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A3659", "name": "东昌湖"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A1890", "name": "聊大"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A879", "name": "市中心"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A3949", "name": "古楼"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A1288", "name": "闸口"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A2489", "name": "花园南路"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A999", "name": "凤凰台"}, {"parent_id": "D625", "children": [], "type": "A", "id": "A106", "name": "汽车总站"}], "type": "D", "id": "D625", "name": "东昌府区"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D626", "name": "东阿县"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D627", "name": "高唐县"}, {"parent_id": "C201", "children": [], "type": "D", "id": "D628", "name": "冠县"}, {"parent_id": "C201", "children": [ {"parent_id": "D629", "children": [], "type": "A", "id": "A2490", "name": "聊大花园"}, {"parent_id": "D629", "children": [], "type": "A", "id": "A880", "name": "大转盘"}, {"parent_id": "D629", "children": [], "type": "A", "id": "A1891", "name": "御润财富城"}], "type": "D", "id": "D629", "name": "开发区"}], "type": "C", "id": "C201", "name": "聊城"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C200", "name": "德州"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C209", "name": "荣成"}, {"parent_id": "P7", "children": [], "type": "C", "id": "C208", "name": "青州"}, {"parent_id": "P7", "children": [ {"parent_id": "C191", "children": [], "type": "D", "id": "D560", "name": "利津县"}, {"parent_id": "C191", "children": [ {"parent_id": "D556", "children": [], "type": "A", "id": "A855", "name": "东城"}, {"parent_id": "D556", "children": [], "type": "A", "id": "A1872", "name": "西城"}], "type": "D", "id": "D556", "name": "东营区"}, {"parent_id": "C191", "children": [], "type": "D", "id": "D557", "name": "广饶县"}, {"parent_id": "C191", "children": [], "type": "D", "id": "D558", "name": "河口区"}, {"parent_id": "C191", "children": [], "type": "D", "id": "D559", "name": "垦利县"}], "type": "C", "id": "C191", "name": "东营"}, {"parent_id": "P7", "children": [ {"parent_id": "C190", "children": [ {"parent_id": "D554", "children": [], "type": "A", "id": "A854", "name": "新城"}], "type": "D", "id": "D554", "name": "薛城区"}, {"parent_id": "C190", "children": [], "type": "D", "id": "D555", "name": "峄城区"}, {"parent_id": "C190", "children": [], "type": "D", "id": "D552", "name": "台儿庄区"}, {"parent_id": "C190", "children": [ {"parent_id": "D553", "children": [], "type": "A", "id": "A3646", "name": "善国路"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A4195", "name": "塔寺北路/翠湖"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A2472", "name": "大同路"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A2924", "name": "步行街"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A3317", "name": "火车站/问天广场"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A853", "name": "新兴路"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A3938", "name": "长途汽车站/伦达"}, {"parent_id": "D553", "children": [], "type": "A", "id": "A1871", "name": "龙泉广场美食城"}], "type": "D", "id": "D553", "name": "滕州市"}, {"parent_id": "C190", "children": [], "type": "D", "id": "D550", "name": "山亭区"}, {"parent_id": "C190", "children": [ {"parent_id": "D551", "children": [], "type": "A", "id": "A2471", "name": "三角花园/汽车总站"}, {"parent_id": "D551", "children": [], "type": "A", "id": "A2923", "name": "中天步行街"}, {"parent_id": "D551", "children": [], "type": "A", "id": "A852", "name": "振兴路"}, {"parent_id": "D551", "children": [], "type": "A", "id": "A1870", "name": "八大/吉品街"}], "type": "D", "id": "D551", "name": "市中区"}], "type": "C", "id": "C190", "name": "枣庄"}, {"parent_id": "P7", "children": [ {"parent_id": "C199", "children": [], "type": "D", "id": "D613", "name": "费县"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D612", "name": "苍山县"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D615", "name": "莒南县"}, {"parent_id": "C199", "children": [ {"parent_id": "D614", "children": [], "type": "A", "id": "A1888", "name": "九州购物中心"}, {"parent_id": "D614", "children": [], "type": "A", "id": "A876", "name": "五金城"}], "type": "D", "id": "D614", "name": "河东区"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D617", "name": "临沭县"}, {"parent_id": "C199", "children": [ {"parent_id": "D616", "children": [], "type": "A", "id": "A4416", "name": "沂州路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1360", "name": "通达路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A4203", "name": "涑河街"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1680", "name": "新汽车站"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1511", "name": "西街"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1186", "name": "滨河大道"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1889", "name": "北城新区"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A527", "name": "和谐广场"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A2940", "name": "东方不夜城"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A311", "name": "银雀山路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A998", "name": "临西五路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A105", "name": "砚池街"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A754", "name": "临西八路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1580", "name": "大学城"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A3658", "name": "人民广场"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A877", "name": "沂蒙路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A3948", "name": "解放路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1287", "name": "北园路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A2488", "name": "兰田步行街"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1476", "name": "育才路"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A3329", "name": "火车站"}, {"parent_id": "D616", "children": [], "type": "A", "id": "A1419", "name": "金雀山路"}], "type": "D", "id": "D616", "name": "兰山区"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D619", "name": "蒙阴县"}, {"parent_id": "C199", "children": [ {"parent_id": "D618", "children": [], "type": "A", "id": "A878", "name": "龙潭路"}], "type": "D", "id": "D618", "name": "罗庄区"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D620", "name": "平邑县"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D621", "name": "郯城县"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D622", "name": "沂南县"}, {"parent_id": "C199", "children": [], "type": "D", "id": "D623", "name": "沂水县"}], "type": "C", "id": "C199", "name": "临沂"}], "type": "P", "id": "P7", "name": "山东"}, {"parent_id": "N1", "children": [ {"parent_id": "P23", "children": [], "type": "C", "id": "C13", "name": "衡水"}, {"parent_id": "P23", "children": [ {"parent_id": "C12", "children": [], "type": "D", "id": "D73", "name": "三河市"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D71", "name": "固安县"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D75", "name": "文安县"}, {"parent_id": "C12", "children": [ {"parent_id": "D72", "children": [], "type": "A", "id": "A250", "name": "大学城"}], "type": "D", "id": "D72", "name": "开发区"}, {"parent_id": "C12", "children": [ {"parent_id": "D70", "children": [], "type": "A", "id": "A249", "name": "万达"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A2736", "name": "新源天街"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A3502", "name": "万庄商圈"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A2254", "name": "新朝阳"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A1566", "name": "步行街"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A3808", "name": "明珠美食城"}, {"parent_id": "D70", "children": [], "type": "A", "id": "A3151", "name": "阿尔卡迪亚"}], "type": "D", "id": "D70", "name": "广阳区"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D76", "name": "香河县"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D77", "name": "燕郊"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D74", "name": "胜芳"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D78", "name": "永清县"}, {"parent_id": "C12", "children": [], "type": "D", "id": "D69", "name": "大城县"}, {"parent_id": "C12", "children": [ {"parent_id": "D68", "children": [], "type": "A", "id": "A248", "name": "西小区"}, {"parent_id": "D68", "children": [], "type": "A", "id": "A1565", "name": "永华明珠"}], "type": "D", "id": "D68", "name": "安次区"}, {"parent_id": "C12", "children": [ {"parent_id": "D67", "children": [], "type": "A", "id": "A2735", "name": "茗汤温泉渡假村"}, {"parent_id": "D67", "children": [], "type": "A", "id": "A2253", "name": "霸州步行街"}, {"parent_id": "D67", "children": [], "type": "A", "id": "A247", "name": "李少春大剧院"}, {"parent_id": "D67", "children": [], "type": "A", "id": "A1564", "name": "霸州市政府"}], "type": "D", "id": "D67", "name": "霸州市"}], "type": "C", "id": "C12", "name": "廊坊"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C11", "name": "沧州"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C10", "name": "承德"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C15", "name": "迁安"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C14", "name": "武安"}, {"parent_id": "P23", "children": [ {"parent_id": "C430", "children": [ {"parent_id": "D234", "children": [], "type": "A", "id": "A2338", "name": "沙头角"}, {"parent_id": "D234", "children": [], "type": "A", "id": "A2803", "name": "盐田食街"}, {"parent_id": "D234", "children": [], "type": "A", "id": "A584", "name": "大小梅沙"}, {"parent_id": "D234", "children": [], "type": "A", "id": "A1699", "name": "东部华侨城"}], "type": "D", "id": "D234", "name": "盐田区"}, {"parent_id": "C430", "children": [ {"parent_id": "D233", "children": [], "type": "A", "id": "A2337", "name": "香港岛"}, {"parent_id": "D233", "children": [], "type": "A", "id": "A2802", "name": "新界"}, {"parent_id": "D233", "children": [], "type": "A", "id": "A583", "name": "九龙"}, {"parent_id": "D233", "children": [], "type": "A", "id": "A1698", "name": "离岛"}], "type": "D", "id": "D233", "name": "香港"}, {"parent_id": "C430", "children": [ {"parent_id": "D232", "children": [], "type": "A", "id": "A3852", "name": "南山中心区"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A246", "name": "蛇口"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A2336", "name": "华侨城"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A4117", "name": "南头"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A2801", "name": "花园城"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A582", "name": "白石洲"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A473", "name": "太古城"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A3206", "name": "欢乐海岸"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A1697", "name": "海岸城/保利"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A704", "name": "西丽"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A3550", "name": "科技园"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A39", "name": "前海"}, {"parent_id": "D232", "children": [], "type": "A", "id": "A4344", "name": "南油"}], "type": "D", "id": "D232", "name": "南山区"}, {"parent_id": "C430", "children": [ {"parent_id": "D231", "children": [], "type": "A", "id": "A581", "name": "南澳"}], "type": "D", "id": "D231", "name": "南澳大鹏新区"}, {"parent_id": "C430", "children": [ {"parent_id": "D230", "children": [], "type": "A", "id": "A3851", "name": "国贸"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A245", "name": "笋岗"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A2335", "name": "春风万佳/文锦渡"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A1155", "name": "新秀/罗芳"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A4116", "name": "黄贝岭"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A2800", "name": "翠竹路沿线"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A3549", "name": "地王大厦/KKmall"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A580", "name": "宝安南路沿线"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A962", "name": "喜荟城/水库"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A472", "name": "田贝/水贝"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A1696", "name": "布心/太白路"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A1262", "name": "银湖/泥岗"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A38", "name": "莲塘"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A3205", "name": "东门"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A4343", "name": "火车站"}, {"parent_id": "D230", "children": [], "type": "A", "id": "A703", "name": "万象城"}], "type": "D", "id": "D230", "name": "罗湖区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1064", "children": [], "type": "A", "id": "A1384", "name": "红旗大街"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A3468", "name": "南花园步行街"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A167", "name": "新石北路"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A573", "name": "西清公园"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A883", "name": "益友百货"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A4055", "name": "新百广场"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A3105", "name": "万象天成"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A2174", "name": "火车站"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A1112", "name": "中华大街槐安路"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A2683", "name": "海悦天地"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A4492", "name": "西里"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A3778", "name": "时光街"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A4293", "name": "新火车站"}, {"parent_id": "D1064", "children": [], "type": "A", "id": "A384", "name": "西三教"}], "type": "D", "id": "D1064", "name": "桥西区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1065", "children": [], "type": "A", "id": "A1385", "name": "石家庄北站"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A3469", "name": "友谊公园"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A4056", "name": "赵佗公园"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A3106", "name": "水上公园"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A2175", "name": "省二院"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A2684", "name": "三元"}, {"parent_id": "D1065", "children": [], "type": "A", "id": "A3779", "name": "益元百货"}], "type": "D", "id": "D1065", "name": "新华区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1066", "children": [], "type": "A", "id": "A1386", "name": "大马庄园"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A168", "name": "天山海世界"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A574", "name": "众美凤凰城"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A4057", "name": "空中花园"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A3780", "name": "红楼商圈"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A3107", "name": "怀特商城"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A2176", "name": "大石门"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A3470", "name": "华夏家园"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A2685", "name": "国际城"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A4493", "name": "世纪公园"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A4294", "name": "欧韵公园"}, {"parent_id": "D1066", "children": [], "type": "A", "id": "A385", "name": "万达广场"}], "type": "D", "id": "D1066", "name": "裕华区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1067", "children": [], "type": "A", "id": "A1387", "name": "北国商城"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A4058", "name": "盛世长安"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A3781", "name": "省博物馆"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A3108", "name": "方北"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A2177", "name": "北国东尚"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A3471", "name": "建华百货"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A2686", "name": "白佛"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A4494", "name": "先天下"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A169", "name": "运河桥客运站"}, {"parent_id": "D1067", "children": [], "type": "A", "id": "A4295", "name": "谈固"}], "type": "D", "id": "D1067", "name": "长安区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1061", "children": [], "type": "A", "id": "A1382", "name": "藁城市"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A3467", "name": "鹿泉市"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A3777", "name": "栾城县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A166", "name": "无极县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A1322", "name": "赵县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A572", "name": "行唐县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A882", "name": "新乐市"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A4054", "name": "灵寿县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A3103", "name": "晋州市"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A2172", "name": "高邑县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A1392", "name": "赞皇县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A1111", "name": "元氏县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A2681", "name": "井陉县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A4491", "name": "深泽县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A4292", "name": "平山县"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A383", "name": "辛集市"}, {"parent_id": "D1061", "children": [], "type": "A", "id": "A1220", "name": "正定县"}], "type": "D", "id": "D1061", "name": "近郊"}, {"parent_id": "C430", "children": [], "type": "D", "id": "D1062", "name": "开发区"}, {"parent_id": "C430", "children": [ {"parent_id": "D1063", "children": [], "type": "A", "id": "A1383", "name": "乐汇城"}, {"parent_id": "D1063", "children": [], "type": "A", "id": "A3104", "name": "桃园"}, {"parent_id": "D1063", "children": [], "type": "A", "id": "A2173", "name": "勒泰中心"}, {"parent_id": "D1063", "children": [], "type": "A", "id": "A2682", "name": "棉五"}], "type": "D", "id": "D1063", "name": "桥东区"}, {"parent_id": "C430", "children": [ {"parent_id": "D228", "children": [], "type": "A", "id": "A3850", "name": "平湖"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A578", "name": "布吉"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A2333", "name": "大运"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A4115", "name": "坪地"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A3547", "name": "坪山"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A3203", "name": "龙岗中心区"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A1694", "name": "坂田"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A2798", "name": "横岗"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A37", "name": "双龙/南联"}, {"parent_id": "D228", "children": [], "type": "A", "id": "A4342", "name": "求水山度假区"}], "type": "D", "id": "D228", "name": "龙岗区"}, {"parent_id": "C430", "children": [ {"parent_id": "D229", "children": [], "type": "A", "id": "A579", "name": "大浪"}, {"parent_id": "D229", "children": [], "type": "A", "id": "A2334", "name": "锦绣江南"}, {"parent_id": "D229", "children": [], "type": "A", "id": "A3548", "name": "梅林关"}, {"parent_id": "D229", "children": [], "type": "A", "id": "A3204", "name": "民治"}, {"parent_id": "D229", "children": [], "type": "A", "id": "A1695", "name": "观澜"}, {"parent_id": "D229", "children": [], "type": "A", "id": "A2799", "name": "龙华"}], "type": "D", "id": "D229", "name": "龙华新区"}, {"parent_id": "C430", "children": [ {"parent_id": "D226", "children": [], "type": "A", "id": "A576", "name": "宝安中心区"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A2331", "name": "公明"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A4113", "name": "松岗"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A470", "name": "新安"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A3545", "name": "海雅缤纷城"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A243", "name": "西乡"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A3848", "name": "沙井"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A3201", "name": "固戍"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A1692", "name": "福永"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A2796", "name": "港隆城"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A35", "name": "桃源居"}, {"parent_id": "D226", "children": [], "type": "A", "id": "A4340", "name": "石岩"}], "type": "D", "id": "D226", "name": "宝安区"}, {"parent_id": "C430", "children": [ {"parent_id": "D227", "children": [], "type": "A", "id": "A702", "name": "新洲/石厦"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A577", "name": "八卦岭/园岭"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A2332", "name": "车公庙"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A1154", "name": "香蜜湖"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A4114", "name": "华强南"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A471", "name": "市民中心"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A3546", "name": "华强北"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A961", "name": "新城市广场"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A3849", "name": "皇岗"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A1693", "name": "CBD中心区"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A1261", "name": "竹子林"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A2797", "name": "福田保税区"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A36", "name": "梅林"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A3202", "name": "岗厦"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A4341", "name": "景田"}, {"parent_id": "D227", "children": [], "type": "A", "id": "A244", "name": "上沙/下沙"}], "type": "D", "id": "D227", "name": "福田区"}], "type": "C", "id": "C430", "name": "石家庄"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C9", "name": "张家口"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C8", "name": "保定"}, {"parent_id": "P23", "children": [], "type": "C", "id": "C7", "name": "邢台"}, {"parent_id": "P23", "children": [ {"parent_id": "C6", "children": [], "type": "D", "id": "D66", "name": "永年县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D58", "name": "馆陶县"}, {"parent_id": "C6", "children": [ {"parent_id": "D59", "children": [], "type": "A", "id": "A240", "name": "黄粱梦"}, {"parent_id": "D59", "children": [], "type": "A", "id": "A1561", "name": "雪驰"}], "type": "D", "id": "D59", "name": "邯郸县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D50", "name": "成安县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D51", "name": "磁县"}, {"parent_id": "C6", "children": [ {"parent_id": "D52", "children": [], "type": "A", "id": "A911", "name": "行政大厅"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A2731", "name": "鑫港国际"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A592", "name": "新春美食林"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1559", "name": "滏春美食林"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A4077", "name": "龙湖"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A435", "name": "新丹兰商场"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A4312", "name": "市委"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1440", "name": "中华北"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A238", "name": "丛台公园"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A3498", "name": "康德"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1396", "name": "樱花新天地"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1129", "name": "星城国际"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1333", "name": "亚太劳模广场"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A3804", "name": "联纺"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A1248", "name": "鑫岭电脑城"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A2249", "name": "高开区"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A12", "name": "万达广场"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A3147", "name": "稽山新天地"}, {"parent_id": "D52", "children": [], "type": "A", "id": "A206", "name": "新世纪广场"}], "type": "D", "id": "D52", "name": "丛台区"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D53", "name": "大名县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D54", "name": "肥乡县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D55", "name": "峰峰矿区"}, {"parent_id": "C6", "children": [ {"parent_id": "D56", "children": [], "type": "A", "id": "A2732", "name": "彭家寨政府"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A2250", "name": "复兴区政府"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A239", "name": "百家村商圈"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A3499", "name": "赵苑"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A3148", "name": "樱花会馆"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A1560", "name": "复兴商贸城"}, {"parent_id": "D56", "children": [], "type": "A", "id": "A3805", "name": "制氧机厂"}], "type": "D", "id": "D56", "name": "复兴区"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D57", "name": "广平县"}, {"parent_id": "C6", "children": [ {"parent_id": "D65", "children": [], "type": "A", "id": "A2734", "name": "汽车站"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A2252", "name": "富强街中段"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A4078", "name": "武安新世纪广场"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A3501", "name": "图书馆"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A4313", "name": "武安广场"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A3807", "name": "体育馆"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A1563", "name": "百货大楼"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A3150", "name": "市政府"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A13", "name": "向阳路"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A242", "name": "白鹤公园"}, {"parent_id": "D65", "children": [], "type": "A", "id": "A207", "name": "中兴路双马"}], "type": "D", "id": "D65", "name": "武安市"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D64", "name": "魏县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D61", "name": "临漳县"}, {"parent_id": "C6", "children": [ {"parent_id": "D60", "children": [], "type": "A", "id": "A2733", "name": "汽车西站"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A3500", "name": "赵都新城"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A241", "name": "春天百货商场"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A3806", "name": "中华南"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A3149", "name": "文化宫"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A1562", "name": "罗城头"}, {"parent_id": "D60", "children": [], "type": "A", "id": "A2251", "name": "明珠广场"}], "type": "D", "id": "D60", "name": "邯山区"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D63", "name": "涉县"}, {"parent_id": "C6", "children": [], "type": "D", "id": "D62", "name": "曲周县"}], "type": "C", "id": "C6", "name": "邯郸"}, {"parent_id": "P23", "children": [ {"parent_id": "C5", "children": [ {"parent_id": "D49", "children": [], "type": "A", "id": "A237", "name": "山海关"}], "type": "D", "id": "D49", "name": "山海关区"}, {"parent_id": "C5", "children": [ {"parent_id": "D48", "children": [], "type": "A", "id": "A236", "name": "青龙"}], "type": "D", "id": "D48", "name": "青龙县"}, {"parent_id": "C5", "children": [], "type": "D", "id": "D43", "name": "抚宁县"}, {"parent_id": "C5", "children": [ {"parent_id": "D42", "children": [], "type": "A", "id": "A232", "name": "昌黎"}], "type": "D", "id": "D42", "name": "昌黎县"}, {"parent_id": "C5", "children": [ {"parent_id": "D41", "children": [], "type": "A", "id": "A231", "name": "北戴河"}], "type": "D", "id": "D41", "name": "北戴河区"}, {"parent_id": "C5", "children": [], "type": "D", "id": "D47", "name": "南戴河"}, {"parent_id": "C5", "children": [ {"parent_id": "D46", "children": [], "type": "A", "id": "A235", "name": "卢龙"}], "type": "D", "id": "D46", "name": "卢龙县"}, {"parent_id": "C5", "children": [ {"parent_id": "D45", "children": [], "type": "A", "id": "A2730", "name": "泰山路"}, {"parent_id": "D45", "children": [], "type": "A", "id": "A1558", "name": "东北大学"}, {"parent_id": "D45", "children": [], "type": "A", "id": "A234", "name": "孟营"}, {"parent_id": "D45", "children": [], "type": "A", "id": "A2248", "name": "燕山大学"}, {"parent_id": "D45", "children": [], "type": "A", "id": "A3146", "name": "长江中道"}], "type": "D", "id": "D45", "name": "开发区"}, {"parent_id": "C5", "children": [ {"parent_id": "D44", "children": [], "type": "A", "id": "A910", "name": "民族路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2108", "name": "人民广场"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1649", "name": "建国路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1910", "name": "迎宾路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1128", "name": "红旗路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1491", "name": "世纪星园小区"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1700", "name": "道南"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A591", "name": "友谊路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1557", "name": "东环路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A4076", "name": "东港路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A434", "name": "西港路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2041", "name": "东山浴场"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A4311", "name": "秦皇西大街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2247", "name": "海阳路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A233", "name": "太阳城"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2178", "name": "秦皇小区"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A3803", "name": "河北大街东段"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A3497", "name": "河北大街西段"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1395", "name": "和平大街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2151", "name": "秦皇东大街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A2729", "name": "新宝街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1332", "name": "建设大街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1548", "name": "文化路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1247", "name": "金三角"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A11", "name": "先锋路"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A3145", "name": "河北大街中段"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A1439", "name": "燕山大街"}, {"parent_id": "D44", "children": [], "type": "A", "id": "A205", "name": "金街"}], "type": "D", "id": "D44", "name": "海港区"}], "type": "C", "id": "C5", "name": "秦皇岛"}, {"parent_id": "P23", "children": [ {"parent_id": "C4", "children": [], "type": "D", "id": "D38", "name": "曹妃甸区"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D39", "name": "玉田县"}, {"parent_id": "C4", "children": [ {"parent_id": "D36", "children": [], "type": "A", "id": "A1556", "name": "家乐"}, {"parent_id": "D36", "children": [], "type": "A", "id": "A2246", "name": "黄台山"}, {"parent_id": "D36", "children": [], "type": "A", "id": "A2728", "name": "明珠街"}, {"parent_id": "D36", "children": [], "type": "A", "id": "A3144", "name": "燕山大路"}, {"parent_id": "D36", "children": [], "type": "A", "id": "A229", "name": "三元街"}], "type": "D", "id": "D36", "name": "迁安市"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D37", "name": "迁西县"}, {"parent_id": "C4", "children": [ {"parent_id": "D34", "children": [], "type": "A", "id": "A590", "name": "唐人街"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A1554", "name": "凤城国际"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A4074", "name": "火炬路"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A2244", "name": "大里北路"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A3495", "name": "兴源道"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A909", "name": "八方"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A1127", "name": "远洋城"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A2726", "name": "友谊北路"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A1246", "name": "中环广场"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A4309", "name": "煤医道"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A10", "name": "尚座"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A3801", "name": "北新道"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A3142", "name": "长宁道"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A227", "name": "百货大楼"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A433", "name": "龙泽路"}, {"parent_id": "D34", "children": [], "type": "A", "id": "A204", "name": "鹭港"}], "type": "D", "id": "D34", "name": "路北区"}, {"parent_id": "C4", "children": [ {"parent_id": "D35", "children": [], "type": "A", "id": "A1555", "name": "新街"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A4075", "name": "荷花坑"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A4310", "name": "宝升昌广场"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A2245", "name": "银泰百货"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A3802", "name": "新华道"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A3496", "name": "福乐园"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A2727", "name": "南湖公园"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A3143", "name": "南湖美食广场"}, {"parent_id": "D35", "children": [], "type": "A", "id": "A228", "name": "万达"}], "type": "D", "id": "D35", "name": "路南区"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D32", "name": "滦南县"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D33", "name": "滦县"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D30", "name": "开平区"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D31", "name": "乐亭县"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D40", "name": "遵化市"}, {"parent_id": "C4", "children": [], "type": "D", "id": "D29", "name": "古冶区"}, {"parent_id": "C4", "children": [ {"parent_id": "D28", "children": [], "type": "A", "id": "A1553", "name": "丰润新区"}, {"parent_id": "D28", "children": [], "type": "A", "id": "A226", "name": "曹雪芹东道"}], "type": "D", "id": "D28", "name": "丰润区"}, {"parent_id": "C4", "children": [ {"parent_id": "D27", "children": [], "type": "A", "id": "A225", "name": "运河唐人街"}], "type": "D", "id": "D27", "name": "丰南区"}], "type": "C", "id": "C4", "name": "唐山"}], "type": "P", "id": "P23", "name": "河北"}, {"parent_id": "N1", "children": [ {"parent_id": "P29", "children": [], "type": "C", "id": "C19", "name": "阳泉"}, {"parent_id": "P29", "children": [ {"parent_id": "C18", "children": [], "type": "D", "id": "D94", "name": "矿区"}, {"parent_id": "C18", "children": [], "type": "D", "id": "D95", "name": "南郊区"}, {"parent_id": "C18", "children": [], "type": "D", "id": "D96", "name": "新荣区"}, {"parent_id": "C18", "children": [], "type": "D", "id": "D97", "name": "阳高县"}, {"parent_id": "C18", "children": [ {"parent_id": "D93", "children": [], "type": "A", "id": "A1592", "name": "南环路"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A4318", "name": "火车站"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A2745", "name": "教场街"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A211", "name": "华林新天地"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A324", "name": "西门外"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A4085", "name": "东关"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A3510", "name": "仿古街"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A2266", "name": "东信"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A18", "name": "南关"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A3159", "name": "大南街/小南街"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A439", "name": "百盛/沃尔玛"}, {"parent_id": "D93", "children": [], "type": "A", "id": "A3816", "name": "大富翁"}], "type": "D", "id": "D93", "name": "城区"}, {"parent_id": "C18", "children": [], "type": "D", "id": "D98", "name": "左云县"}], "type": "C", "id": "C18", "name": "大同"}, {"parent_id": "P29", "children": [ {"parent_id": "C17", "children": [ {"parent_id": "D92", "children": [], "type": "A", "id": "A913", "name": "水西门街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1591", "name": "大营盘"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A3509", "name": "建设北路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1493", "name": "新建路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1701", "name": "钟楼街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A594", "name": "双塔东街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1250", "name": "桃园路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A4317", "name": "南海街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1442", "name": "五一广场"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A2744", "name": "火车站"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A210", "name": "双塔西街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1398", "name": "五一路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1131", "name": "铜锣湾"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1650", "name": "羊市街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1335", "name": "体育馆"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A1549", "name": "迎泽大街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A323", "name": "朝阳街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A4084", "name": "柳巷商业区"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A2265", "name": "鼓楼街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A17", "name": "青年路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A3158", "name": "解放路"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A438", "name": "水西关街"}, {"parent_id": "D92", "children": [], "type": "A", "id": "A3815", "name": "开化寺街"}], "type": "D", "id": "D92", "name": "迎泽区"}, {"parent_id": "C17", "children": [ {"parent_id": "D90", "children": [], "type": "A", "id": "A912", "name": "通达街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1492", "name": "真武路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A593", "name": "太榆路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A437", "name": "体育路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A3507", "name": "南中环街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A4315", "name": "亲贤街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1441", "name": "长治路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A2742", "name": "建设南路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1397", "name": "长风街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1589", "name": "昌盛西街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1130", "name": "坞城路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1334", "name": "学府街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A321", "name": "并州路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A4082", "name": "平阳路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A3156", "name": "康宁街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A1249", "name": "王村南街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A2263", "name": "高新科技产业区"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A15", "name": "人民路"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A3813", "name": "南内环街"}, {"parent_id": "D90", "children": [], "type": "A", "id": "A209", "name": "省体育中心"}], "type": "D", "id": "D90", "name": "小店区"}, {"parent_id": "C17", "children": [ {"parent_id": "D91", "children": [], "type": "A", "id": "A1590", "name": "北肖墙"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A3508", "name": "府东街"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A4316", "name": "胜利街"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A2743", "name": "府西街"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A322", "name": "北大街"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A4083", "name": "龙潭商业中心"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A3157", "name": "府东府西商业街"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A2264", "name": "东辑虎营"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A3814", "name": "旱西关"}, {"parent_id": "D91", "children": [], "type": "A", "id": "A16", "name": "西辑虎营"}], "type": "D", "id": "D91", "name": "杏花岭区"}, {"parent_id": "C17", "children": [ {"parent_id": "D89", "children": [], "type": "A", "id": "A3506", "name": "漪汾街"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A2741", "name": "下元商业中心"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A1588", "name": "晋祠路"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A320", "name": "和平路"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A3155", "name": "迎泽西大街"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A2262", "name": "千峰路"}, {"parent_id": "D89", "children": [], "type": "A", "id": "A3812", "name": "长风西街"}], "type": "D", "id": "D89", "name": "万柏林区"}, {"parent_id": "C17", "children": [], "type": "D", "id": "D88", "name": "晋源区"}, {"parent_id": "C17", "children": [ {"parent_id": "D87", "children": [], "type": "A", "id": "A319", "name": "古交市"}, {"parent_id": "D87", "children": [], "type": "A", "id": "A1587", "name": "阳曲县"}], "type": "D", "id": "D87", "name": "近郊"}, {"parent_id": "C17", "children": [ {"parent_id": "D86", "children": [], "type": "A", "id": "A318", "name": "恒山路"}, {"parent_id": "D86", "children": [], "type": "A", "id": "A1586", "name": "兴华街"}], "type": "D", "id": "D86", "name": "尖草坪区"}], "type": "C", "id": "C17", "name": "太原"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C22", "name": "朔州"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C23", "name": "晋中"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C20", "name": "长治"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C21", "name": "晋城"}, {"parent_id": "P29", "children": [ {"parent_id": "C26", "children": [], "type": "D", "id": "D116", "name": "蒲县"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D117", "name": "曲沃县"}, {"parent_id": "C26", "children": [ {"parent_id": "D114", "children": [], "type": "A", "id": "A330", "name": "霍州"}], "type": "D", "id": "D114", "name": "霍州市"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D115", "name": "吉县"}, {"parent_id": "C26", "children": [ {"parent_id": "D113", "children": [], "type": "A", "id": "A1594", "name": "世纪广场"}, {"parent_id": "D113", "children": [], "type": "A", "id": "A329", "name": "新田广场"}], "type": "D", "id": "D113", "name": "侯马市"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D118", "name": "襄汾县"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D119", "name": "乡宁县"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D112", "name": "洪洞县"}, {"parent_id": "C26", "children": [], "type": "D", "id": "D121", "name": "翼城县"}, {"parent_id": "C26", "children": [ {"parent_id": "D120", "children": [], "type": "A", "id": "A914", "name": "滨河路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1595", "name": "煤化巷"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2109", "name": "临纺"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1911", "name": "平阳街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2312", "name": "迎春街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1494", "name": "平阳广场"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2339", "name": "建设路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2189", "name": "北外环"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1702", "name": "向阳路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A595", "name": "三和家园"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1550", "name": "解放路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2211", "name": "南外环"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A331", "name": "鼓楼广场"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2042", "name": "新东城"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1251", "name": "锦悦城"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2242", "name": "鼓楼东大街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1443", "name": "鼓楼西大街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2508", "name": "贡院街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1132", "name": "教授花园"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2747", "name": "华州路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A3161", "name": "尧贤街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2179", "name": "鼓楼北"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A212", "name": "河汾路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2605", "name": "中大街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1399", "name": "鼓楼南大街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2152", "name": "屯里"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1651", "name": "五一路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A1336", "name": "尧庙"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A440", "name": "车站路"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A4087", "name": "财神楼"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A3512", "name": "临钢"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A4320", "name": "青狮街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A2268", "name": "福利巷"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A19", "name": "体育街"}, {"parent_id": "D120", "children": [], "type": "A", "id": "A3818", "name": "洪家楼"}], "type": "D", "id": "D120", "name": "尧都区"}], "type": "C", "id": "C26", "name": "临汾"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C27", "name": "吕梁"}, {"parent_id": "P29", "children": [ {"parent_id": "C24", "children": [], "type": "D", "id": "D110", "name": "垣曲县"}, {"parent_id": "C24", "children": [ {"parent_id": "D111", "children": [], "type": "A", "id": "A326", "name": "禹都市场"}], "type": "D", "id": "D111", "name": "禹都开发区"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D99", "name": "河津市"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D101", "name": "空港开发区"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D100", "name": "绛县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D103", "name": "平陆县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D102", "name": "临猗县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D105", "name": "万荣县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D104", "name": "芮城县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D107", "name": "夏县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D106", "name": "闻喜县"}, {"parent_id": "C24", "children": [], "type": "D", "id": "D109", "name": "永济市"}, {"parent_id": "C24", "children": [ {"parent_id": "D108", "children": [], "type": "A", "id": "A1593", "name": "沃尔玛"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A4319", "name": "西城"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A2746", "name": "北郊"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A3160", "name": "东星时代广场"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A325", "name": "南风广场"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A4086", "name": "解放路"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A3511", "name": "体育馆"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A2267", "name": "中银大道"}, {"parent_id": "D108", "children": [], "type": "A", "id": "A3817", "name": "禹香苑"}], "type": "D", "id": "D108", "name": "盐湖区"}], "type": "C", "id": "C24", "name": "运城"}, {"parent_id": "P29", "children": [], "type": "C", "id": "C25", "name": "忻州"}], "type": "P", "id": "P29", "name": "山西"}, {"parent_id": "N1", "children": [ {"parent_id": "P30", "children": [ {"parent_id": "C16", "children": [ {"parent_id": "D79", "children": [], "type": "A", "id": "A2738", "name": "旧城北门"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A313", "name": "附院"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A4079", "name": "中山西路"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A3503", "name": "文化宫街"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A2258", "name": "金蓝港"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A1581", "name": "海亮"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A3809", "name": "西龙王庙"}, {"parent_id": "D79", "children": [], "type": "A", "id": "A3152", "name": "牛街"}], "type": "D", "id": "D79", "name": "回民区"}, {"parent_id": "C16", "children": [ {"parent_id": "D85", "children": [], "type": "A", "id": "A317", "name": "大召"}, {"parent_id": "D85", "children": [], "type": "A", "id": "A1585", "name": "南茶坊"}, {"parent_id": "D85", "children": [], "type": "A", "id": "A2261", "name": "五塔寺"}], "type": "D", "id": "D85", "name": "玉泉区"}, {"parent_id": "C16", "children": [ {"parent_id": "D84", "children": [], "type": "A", "id": "A316", "name": "阿尔泰"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A3505", "name": "内蒙古图书馆"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A2740", "name": "火车站"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A1584", "name": "八一"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A4081", "name": "万达"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A3154", "name": "呼和佳地"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A2260", "name": "鼓楼"}, {"parent_id": "D84", "children": [], "type": "A", "id": "A3811", "name": "润宇"}], "type": "D", "id": "D84", "name": "新城区"}, {"parent_id": "C16", "children": [], "type": "D", "id": "D83", "name": "土默特左旗"}, {"parent_id": "C16", "children": [ {"parent_id": "D82", "children": [], "type": "A", "id": "A315", "name": "长乐宫"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A436", "name": "仕奇公园"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A3504", "name": "金隅时代城"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A2259", "name": "金桥"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A4314", "name": "桥华"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A1583", "name": "发展小区"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A2739", "name": "金宇文苑"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A4080", "name": "内大"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A3153", "name": "嘉茂"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A14", "name": "乌兰察布东街"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A3810", "name": "摩尔城"}, {"parent_id": "D82", "children": [], "type": "A", "id": "A208", "name": "师大"}], "type": "D", "id": "D82", "name": "赛罕区"}, {"parent_id": "C16", "children": [ {"parent_id": "D81", "children": [], "type": "A", "id": "A314", "name": "和林格尔县"}, {"parent_id": "D81", "children": [], "type": "A", "id": "A1582", "name": "托克托县"}], "type": "D", "id": "D81", "name": "近郊"}, {"parent_id": "C16", "children": [], "type": "D", "id": "D80", "name": "金川开发区"}], "type": "C", "id": "C16", "name": "呼和浩特"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C38", "name": "阿拉善"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C35", "name": "乌兰察布"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C34", "name": "巴彦淖尔"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C37", "name": "锡林郭勒"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C36", "name": "兴安"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C31", "name": "通辽"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C30", "name": "赤峰"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C33", "name": "呼伦贝尔"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C32", "name": "鄂尔多斯"}, {"parent_id": "P30", "children": [ {"parent_id": "C28", "children": [], "type": "D", "id": "D129", "name": "土默特右旗"}, {"parent_id": "C28", "children": [ {"parent_id": "D128", "children": [], "type": "A", "id": "A1603", "name": "富强路美食街"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A2272", "name": "劳动路"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A359", "name": "大连开发区"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A3164", "name": "青山华联"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A3821", "name": "万达"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A3515", "name": "青山保利"}, {"parent_id": "D128", "children": [], "type": "A", "id": "A2750", "name": "娜琳王府井"}], "type": "D", "id": "D128", "name": "青山区"}, {"parent_id": "C28", "children": [ {"parent_id": "D123", "children": [], "type": "A", "id": "A1601", "name": "二宫"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A2270", "name": "工业路"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A357", "name": "包八中"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A2748", "name": "红星"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A3162", "name": "环城路"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A4088", "name": "铁西"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A3513", "name": "乔家金街"}, {"parent_id": "D123", "children": [], "type": "A", "id": "A3819", "name": "通顺商贸、环西"}], "type": "D", "id": "D123", "name": "东河区"}, {"parent_id": "C28", "children": [], "type": "D", "id": "D122", "name": "滨河新区"}, {"parent_id": "C28", "children": [ {"parent_id": "D127", "children": [], "type": "A", "id": "A1602", "name": "火车站"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A2271", "name": "昆区华联"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A358", "name": "包百"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A2749", "name": "乐园"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A3163", "name": "民族东路"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A3820", "name": "市府东路"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A4089", "name": "松石雅居"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A3514", "name": "三八路"}, {"parent_id": "D127", "children": [], "type": "A", "id": "A4321", "name": "太阳城"}], "type": "D", "id": "D127", "name": "昆都仑区"}, {"parent_id": "C28", "children": [], "type": "D", "id": "D126", "name": "九原区"}, {"parent_id": "C28", "children": [], "type": "D", "id": "D125", "name": "固阳县"}, {"parent_id": "C28", "children": [], "type": "D", "id": "D124", "name": "高新区"}], "type": "C", "id": "C28", "name": "包头"}, {"parent_id": "P30", "children": [], "type": "C", "id": "C29", "name": "乌海"}], "type": "P", "id": "P30", "name": "内蒙古"}, {"parent_id": "N1", "children": [ {"parent_id": "P31", "children": [ {"parent_id": "C426", "children": [ {"parent_id": "D1037", "children": [], "type": "A", "id": "A3449", "name": "东北大马路"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A3761", "name": "吉祥市场"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A3084", "name": "大东路/东塔"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A4039", "name": "滂江街"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A2138", "name": "大东广场"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A2661", "name": "东站"}, {"parent_id": "D1037", "children": [], "type": "A", "id": "A1312", "name": "东中街"}], "type": "D", "id": "D1037", "name": "大东区"}, {"parent_id": "C426", "children": [ {"parent_id": "D1039", "children": [], "type": "A", "id": "A3763", "name": "明廉"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A4281", "name": "塔湾/小白楼"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A3086", "name": "皇姑屯"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A3451", "name": "龙江广场"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A2663", "name": "长客总站"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A1314", "name": "北行/辽大"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A4041", "name": "怒江北街/陵西"}, {"parent_id": "D1039", "children": [], "type": "A", "id": "A2140", "name": "北陵"}], "type": "D", "id": "D1039", "name": "皇姑区"}, {"parent_id": "C426", "children": [ {"parent_id": "D1038", "children": [], "type": "A", "id": "A4481", "name": "新华广场"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A3762", "name": "太原街"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A2139", "name": "彩电塔"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A4280", "name": "西塔/北市场"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A3085", "name": "三好街"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A3450", "name": "沙山"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A1313", "name": "长白地区"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A2662", "name": "南市/马路湾"}, {"parent_id": "D1038", "children": [], "type": "A", "id": "A4040", "name": "五里河/南湖公园"}], "type": "D", "id": "D1038", "name": "和平区"}, {"parent_id": "C426", "children": [ {"parent_id": "D1042", "children": [], "type": "A", "id": "A3765", "name": "铁西广场"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A4283", "name": "重工街沿线"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A3454", "name": "沈辽路"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A2666", "name": "北一路万达"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A1317", "name": "北二马路"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A4043", "name": "铁西万达"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A3089", "name": "滑翔小区"}, {"parent_id": "D1042", "children": [], "type": "A", "id": "A2143", "name": "保工街"}], "type": "D", "id": "D1042", "name": "铁西区"}, {"parent_id": "C426", "children": [], "type": "D", "id": "D1043", "name": "于洪区"}, {"parent_id": "C426", "children": [ {"parent_id": "D1040", "children": [], "type": "A", "id": "A3087", "name": "苏家屯区"}, {"parent_id": "D1040", "children": [], "type": "A", "id": "A3452", "name": "新民市"}, {"parent_id": "D1040", "children": [], "type": "A", "id": "A2664", "name": "沈北新区"}, {"parent_id": "D1040", "children": [], "type": "A", "id": "A1315", "name": "东陵区"}, {"parent_id": "D1040", "children": [], "type": "A", "id": "A2141", "name": "辽中县"}], "type": "D", "id": "D1040", "name": "近郊"}, {"parent_id": "C426", "children": [ {"parent_id": "D1041", "children": [], "type": "A", "id": "A4482", "name": "中街/故宫"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A3764", "name": "文艺路/文化路"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A4282", "name": "小河沿"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A3088", "name": "奉天街沿线"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A3453", "name": "怀远门"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A2665", "name": "长青街"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A159", "name": "展览馆"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A1316", "name": "奥体中心"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A4042", "name": "五爱市场"}, {"parent_id": "D1041", "children": [], "type": "A", "id": "A2142", "name": "北站/市府"}], "type": "D", "id": "D1041", "name": "沈河区"}], "type": "C", "id": "C426", "name": "沈阳"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C53", "name": "海城"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C52", "name": "葫芦岛"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C51", "name": "朝阳"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C50", "name": "铁岭"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C44", "name": "丹东"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C45", "name": "锦州"}, {"parent_id": "P31", "children": [ {"parent_id": "C46", "children": [ {"parent_id": "D196", "children": [], "type": "A", "id": "A1648", "name": "营口大学"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1341", "name": "大润发"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1497", "name": "公汽公司"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A3192", "name": "渤海明珠"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A654", "name": "大商新玛特"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A4336", "name": "十六中学"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1461", "name": "东风市场"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1256", "name": "南湖公园"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A2784", "name": "陶瓷城"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A3842", "name": "第一高中"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A465", "name": "盼盼路北"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A2311", "name": "客运站"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1147", "name": "东升市场"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A4107", "name": "万有街"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A3537", "name": "中心街"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A1403", "name": "火车站"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A428", "name": "体育场/万达"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A32", "name": "红旗小学"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A224", "name": "楞严寺"}, {"parent_id": "D196", "children": [], "type": "A", "id": "A937", "name": "营口兴隆"}], "type": "D", "id": "D196", "name": "站前区"}, {"parent_id": "C46", "children": [], "type": "D", "id": "D194", "name": "老边区"}, {"parent_id": "C46", "children": [ {"parent_id": "D195", "children": [], "type": "A", "id": "A3191", "name": "老街"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A1647", "name": "得胜市场"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A427", "name": "相和"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A2783", "name": "镜湖公园"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A3841", "name": "食品公司"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A2310", "name": "通惠门"}, {"parent_id": "D195", "children": [], "type": "A", "id": "A3536", "name": "月光园"}], "type": "D", "id": "D195", "name": "西市区"}, {"parent_id": "C46", "children": [ {"parent_id": "D192", "children": [], "type": "A", "id": "A1646", "name": "大石桥兴隆"}, {"parent_id": "D192", "children": [], "type": "A", "id": "A426", "name": "大石桥"}], "type": "D", "id": "D192", "name": "大石桥市"}, {"parent_id": "C46", "children": [], "type": "D", "id": "D193", "name": "盖州市"}, {"parent_id": "C46", "children": [ {"parent_id": "D191", "children": [], "type": "A", "id": "A1645", "name": "世纪广场"}, {"parent_id": "D191", "children": [], "type": "A", "id": "A3190", "name": "鲅鱼圈一高"}, {"parent_id": "D191", "children": [], "type": "A", "id": "A2782", "name": "月亮湖公园"}, {"parent_id": "D191", "children": [], "type": "A", "id": "A2309", "name": "商业大厦"}, {"parent_id": "D191", "children": [], "type": "A", "id": "A425", "name": "青龙山公园"}], "type": "D", "id": "D191", "name": "鲅鱼圈区"}], "type": "C", "id": "C46", "name": "营口"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C47", "name": "阜新"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C40", "name": "大连"}, {"parent_id": "P31", "children": [ {"parent_id": "C41", "children": [], "type": "D", "id": "D170", "name": "台安县"}, {"parent_id": "C41", "children": [ {"parent_id": "D171", "children": [], "type": "A", "id": "A2777", "name": "湖南"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A3838", "name": "人民公园"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A413", "name": "站前"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A4334", "name": "新兴"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A1636", "name": "山南"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A3185", "name": "明达"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A2300", "name": "解放路"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A4104", "name": "长大"}, {"parent_id": "D171", "children": [], "type": "A", "id": "A3533", "name": "园林路/绿化街"}], "type": "D", "id": "D171", "name": "铁东区"}, {"parent_id": "C41", "children": [ {"parent_id": "D172", "children": [], "type": "A", "id": "A414", "name": "千龙户"}, {"parent_id": "D172", "children": [], "type": "A", "id": "A1637", "name": "人民路沿线"}, {"parent_id": "D172", "children": [], "type": "A", "id": "A2301", "name": "永乐公园"}], "type": "D", "id": "D172", "name": "铁西区"}, {"parent_id": "C41", "children": [], "type": "D", "id": "D173", "name": "岫岩满族自治县"}, {"parent_id": "C41", "children": [ {"parent_id": "D167", "children": [], "type": "A", "id": "A2775", "name": "东关"}, {"parent_id": "D167", "children": [], "type": "A", "id": "A411", "name": "新东"}, {"parent_id": "D167", "children": [], "type": "A", "id": "A2298", "name": "北关"}, {"parent_id": "D167", "children": [], "type": "A", "id": "A1634", "name": "站前"}], "type": "D", "id": "D167", "name": "海城市"}, {"parent_id": "C41", "children": [], "type": "D", "id": "D166", "name": "高新区"}, {"parent_id": "C41", "children": [], "type": "D", "id": "D169", "name": "千山区"}, {"parent_id": "C41", "children": [ {"parent_id": "D168", "children": [], "type": "A", "id": "A2776", "name": "立山"}, {"parent_id": "D168", "children": [], "type": "A", "id": "A412", "name": "胜利路沿线"}, {"parent_id": "D168", "children": [], "type": "A", "id": "A2299", "name": "深沟寺"}, {"parent_id": "D168", "children": [], "type": "A", "id": "A1635", "name": "太平"}], "type": "D", "id": "D168", "name": "立山区"}], "type": "C", "id": "C41", "name": "鞍山"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C42", "name": "抚顺"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C43", "name": "本溪"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C48", "name": "辽阳"}, {"parent_id": "P31", "children": [], "type": "C", "id": "C49", "name": "盘锦"}], "type": "P", "id": "P31", "name": "辽宁"}, {"parent_id": "N1", "children": [ {"parent_id": "P32", "children": [], "type": "C", "id": "C57", "name": "辽源"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C56", "name": "四平"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C55", "name": "吉林"}, {"parent_id": "P32", "children": [ {"parent_id": "C54", "children": [], "type": "D", "id": "D208", "name": "汽车开发区"}, {"parent_id": "C54", "children": [], "type": "D", "id": "D209", "name": "双阳区"}, {"parent_id": "C54", "children": [ {"parent_id": "D202", "children": [], "type": "A", "id": "A2316", "name": "净月公园"}, {"parent_id": "D202", "children": [], "type": "A", "id": "A1657", "name": "净月大学城"}, {"parent_id": "D202", "children": [], "type": "A", "id": "A450", "name": "长影世纪城"}], "type": "D", "id": "D202", "name": "净月开发区"}, {"parent_id": "C54", "children": [], "type": "D", "id": "D200", "name": "高新区"}, {"parent_id": "C54", "children": [ {"parent_id": "D201", "children": [], "type": "A", "id": "A2315", "name": "天地十二坊"}, {"parent_id": "D201", "children": [], "type": "A", "id": "A449", "name": "临河街"}, {"parent_id": "D201", "children": [], "type": "A", "id": "A1656", "name": "赛德广场"}], "type": "D", "id": "D201", "name": "经济开发区"}, {"parent_id": "C54", "children": [ {"parent_id": "D206", "children": [], "type": "A", "id": "A3195", "name": "南关区政府"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A3540", "name": "人民广场"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A454", "name": "全安广场"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A4338", "name": "新天地购物公园"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A2788", "name": "工大南门"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A3844", "name": "卫星广场"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A1659", "name": "东南湖大路"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A4109", "name": "五环体育场"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A2318", "name": "东广场"}, {"parent_id": "D206", "children": [], "type": "A", "id": "A33", "name": "重庆路"}], "type": "D", "id": "D206", "name": "南关区"}, {"parent_id": "C54", "children": [ {"parent_id": "D207", "children": [], "type": "A", "id": "A1660", "name": "飞跃广场"}, {"parent_id": "D207", "children": [], "type": "A", "id": "A455", "name": "车百"}, {"parent_id": "D207", "children": [], "type": "A", "id": "A2319", "name": "天茂城中央"}], "type": "D", "id": "D207", "name": "汽车产业开发区"}, {"parent_id": "C54", "children": [ {"parent_id": "D204", "children": [], "type": "A", "id": "A3194", "name": "一匡街"}, {"parent_id": "D204", "children": [], "type": "A", "id": "A2317", "name": "胜利公园"}, {"parent_id": "D204", "children": [], "type": "A", "id": "A452", "name": "火车站"}, {"parent_id": "D204", "children": [], "type": "A", "id": "A2787", "name": "西广场"}, {"parent_id": "D204", "children": [], "type": "A", "id": "A1658", "name": "凯旋路"}, {"parent_id": "D204", "children": [], "type": "A", "id": "A3539", "name": "雁鸣湖"}], "type": "D", "id": "D204", "name": "宽城区"}, {"parent_id": "C54", "children": [ {"parent_id": "D205", "children": [], "type": "A", "id": "A453", "name": "锦江广场/电影城"}], "type": "D", "id": "D205", "name": "绿园区"}, {"parent_id": "C54", "children": [ {"parent_id": "D203", "children": [], "type": "A", "id": "A451", "name": "农安县"}], "type": "D", "id": "D203", "name": "近郊"}, {"parent_id": "C54", "children": [ {"parent_id": "D198", "children": [], "type": "A", "id": "A1655", "name": "东站"}, {"parent_id": "D198", "children": [], "type": "A", "id": "A447", "name": "东盛"}], "type": "D", "id": "D198", "name": "二道区"}, {"parent_id": "C54", "children": [ {"parent_id": "D199", "children": [], "type": "A", "id": "A448", "name": "吉大南校"}], "type": "D", "id": "D199", "name": "高新开发区"}, {"parent_id": "C54", "children": [ {"parent_id": "D197", "children": [], "type": "A", "id": "A3193", "name": "辉南街"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A2314", "name": "红旗街"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A4337", "name": "文化广场"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A2786", "name": "湖西路"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A3843", "name": "南湖公园"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A1654", "name": "朝阳桥"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A4108", "name": "欧亚卖场"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A446", "name": "朝阳公园/桂林路"}, {"parent_id": "D197", "children": [], "type": "A", "id": "A3538", "name": "建设街"}], "type": "D", "id": "D197", "name": "朝阳区"}], "type": "C", "id": "C54", "name": "长春"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C59", "name": "白山"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C58", "name": "通化"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C62", "name": "延边"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C63", "name": "桦甸"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C60", "name": "松原"}, {"parent_id": "P32", "children": [], "type": "C", "id": "C61", "name": "白城"}], "type": "P", "id": "P32", "name": "吉林"}, {"parent_id": "N1", "children": [ {"parent_id": "P33", "children": [], "type": "C", "id": "C71", "name": "七台河"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C70", "name": "佳木斯"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C73", "name": "黑河"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C72", "name": "牡丹江"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C75", "name": "大兴安岭"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C74", "name": "绥化"}, {"parent_id": "P33", "children": [ {"parent_id": "C3", "children": [ {"parent_id": "D4", "children": [], "type": "A", "id": "A3123", "name": "双城市"}, {"parent_id": "D4", "children": [], "type": "A", "id": "A1525", "name": "阿城市"}, {"parent_id": "D4", "children": [], "type": "A", "id": "A2705", "name": "尚志市"}, {"parent_id": "D4", "children": [], "type": "A", "id": "A174", "name": "宾县"}, {"parent_id": "D4", "children": [], "type": "A", "id": "A2221", "name": "方正县"}, {"parent_id": "D4", "children": [], "type": "A", "id": "A3480", "name": "五常市"}], "type": "D", "id": "D4", "name": "近郊"}, {"parent_id": "C3", "children": [ {"parent_id": "D8", "children": [], "type": "A", "id": "A3125", "name": "珠江路/公滨路"}, {"parent_id": "D8", "children": [], "type": "A", "id": "A2707", "name": "香坊大街/通乡街"}, {"parent_id": "D8", "children": [], "type": "A", "id": "A177", "name": "乐松广场"}, {"parent_id": "D8", "children": [], "type": "A", "id": "A1528", "name": "三大动力/三合路"}, {"parent_id": "D8", "children": [], "type": "A", "id": "A2224", "name": "通乡街/果园街"}], "type": "D", "id": "D8", "name": "香坊区"}, {"parent_id": "C3", "children": [], "type": "D", "id": "D6", "name": "平房区"}, {"parent_id": "C3", "children": [ {"parent_id": "D7", "children": [], "type": "A", "id": "A176", "name": "世茂大道"}, {"parent_id": "D7", "children": [], "type": "A", "id": "A1527", "name": "盛恒基广场"}, {"parent_id": "D7", "children": [], "type": "A", "id": "A2223", "name": "太阳岛"}], "type": "D", "id": "D7", "name": "松北区"}, {"parent_id": "C3", "children": [ {"parent_id": "D5", "children": [], "type": "A", "id": "A3788", "name": "花园街"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A3124", "name": "会展中心"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1", "name": "开发区"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1393", "name": "香坊万达广场"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A2706", "name": "果戈里/革新街"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1122", "name": "秋林地区"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1330", "name": "西客站"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A175", "name": "博物馆"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A4298", "name": "教化广场"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A585", "name": "李范五花园"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1526", "name": "船舶/军工"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A2222", "name": "服装城"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A899", "name": "民生路"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A4062", "name": "哈尔滨火车站"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A420", "name": "芦家街/宣化街"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1243", "name": "文昌街"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A196", "name": "凯德广场"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A1437", "name": "征仪路/保健路"}, {"parent_id": "D5", "children": [], "type": "A", "id": "A3481", "name": "和兴路沿线"}], "type": "D", "id": "D5", "name": "南岗区"}, {"parent_id": "C3", "children": [ {"parent_id": "D2", "children": [], "type": "A", "id": "A3122", "name": "太平桥"}, {"parent_id": "D2", "children": [], "type": "A", "id": "A2704", "name": "南直路/宏伟路"}, {"parent_id": "D2", "children": [], "type": "A", "id": "A3479", "name": "太古街"}, {"parent_id": "D2", "children": [], "type": "A", "id": "A172", "name": "北环路"}, {"parent_id": "D2", "children": [], "type": "A", "id": "A1524", "name": "哈尔滨东站"}, {"parent_id": "D2", "children": [], "type": "A", "id": "A2220", "name": "景阳街/南极街"}], "type": "D", "id": "D2", "name": "道外区"}, {"parent_id": "C3", "children": [ {"parent_id": "D3", "children": [], "type": "A", "id": "A173", "name": "学院路"}], "type": "D", "id": "D3", "name": "呼兰区"}, {"parent_id": "C3", "children": [ {"parent_id": "D1", "children": [], "type": "A", "id": "A2219", "name": "公路大桥"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A3787", "name": "新阳路"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A3121", "name": "建国公园"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A1523", "name": "顾乡"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A2703", "name": "关东古巷"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A3478", "name": "群力地区"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A171", "name": "爱建社区"}, {"parent_id": "D1", "children": [], "type": "A", "id": "A4061", "name": "中央大街"}], "type": "D", "id": "D1", "name": "道里区"}], "type": "C", "id": "C3", "name": "哈尔滨"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C68", "name": "大庆"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C69", "name": "伊春"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C66", "name": "鹤岗"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C67", "name": "双鸭山"}, {"parent_id": "P33", "children": [ {"parent_id": "C64", "children": [], "type": "D", "id": "D219", "name": "拜泉县"}, {"parent_id": "C64", "children": [], "type": "D", "id": "D224", "name": "泰来县"}, {"parent_id": "C64", "children": [ {"parent_id": "D225", "children": [], "type": "A", "id": "A1667", "name": "火车站"}, {"parent_id": "D225", "children": [], "type": "A", "id": "A2326", "name": "和平厂西门"}, {"parent_id": "D225", "children": [], "type": "A", "id": "A469", "name": "百花园"}, {"parent_id": "D225", "children": [], "type": "A", "id": "A2795", "name": "附属三院"}], "type": "D", "id": "D225", "name": "铁锋区"}, {"parent_id": "C64", "children": [], "type": "D", "id": "D220", "name": "富拉尔基区"}, {"parent_id": "C64", "children": [ {"parent_id": "D221", "children": [], "type": "A", "id": "A3199", "name": "齐齐哈尔大学东区"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A1665", "name": "沃尔玛"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A4112", "name": "三中"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A3543", "name": "齐齐哈尔大学西区"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A3847", "name": "龙北街"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A2324", "name": "东四道街"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A467", "name": "大商新玛特"}, {"parent_id": "D221", "children": [], "type": "A", "id": "A2793", "name": "大润发二店"}], "type": "D", "id": "D221", "name": "建华区"}, {"parent_id": "C64", "children": [], "type": "D", "id": "D222", "name": "龙江县"}, {"parent_id": "C64", "children": [ {"parent_id": "D223", "children": [], "type": "A", "id": "A1666", "name": "大润发一店"}, {"parent_id": "D223", "children": [], "type": "A", "id": "A3544", "name": "以马内利教堂"}, {"parent_id": "D223", "children": [], "type": "A", "id": "A2325", "name": "龙南街"}, {"parent_id": "D223", "children": [], "type": "A", "id": "A3200", "name": "百花红楼"}, {"parent_id": "D223", "children": [], "type": "A", "id": "A468", "name": "合意路"}, {"parent_id": "D223", "children": [], "type": "A", "id": "A2794", "name": "民航路"}], "type": "D", "id": "D223", "name": "龙沙区"}], "type": "C", "id": "C64", "name": "齐齐哈尔"}, {"parent_id": "P33", "children": [], "type": "C", "id": "C65", "name": "鸡西"}], "type": "P", "id": "P33", "name": "黑龙江"}, {"parent_id": "N1", "children": [ {"parent_id": "P4", "children": [], "type": "C", "id": "C153", "name": "宿州"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C152", "name": "阜阳"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C151", "name": "滁州"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C150", "name": "黄山"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C157", "name": "池州"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C156", "name": "亳州"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C155", "name": "六安"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C154", "name": "巢湖"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C158", "name": "宣城"}, {"parent_id": "P4", "children": [ {"parent_id": "C142", "children": [ {"parent_id": "D448", "children": [], "type": "A", "id": "A4385", "name": "花冲公园"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A3277", "name": "大通路"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A285", "name": "汽车东站"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A984", "name": "长江东路"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A2881", "name": "大东门"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A734", "name": "元一广场"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A3614", "name": "火车站"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A504", "name": "生态公园"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A762", "name": "宝业东城广场"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A4167", "name": "合裕路"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A2425", "name": "东二环"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A3908", "name": "和平路"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A1810", "name": "长江批发市场"}, {"parent_id": "D448", "children": [], "type": "A", "id": "A76", "name": "临泉路"}], "type": "D", "id": "D448", "name": "瑶海区"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D449", "name": "长丰县"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D444", "name": "庐江县"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D440", "name": "肥东县"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D441", "name": "肥西县"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D442", "name": "高新区"}, {"parent_id": "C142", "children": [ {"parent_id": "D443", "children": [], "type": "A", "id": "A3274", "name": "明珠广场"}, {"parent_id": "D443", "children": [], "type": "A", "id": "A758", "name": "奥体中心"}, {"parent_id": "D443", "children": [], "type": "A", "id": "A1807", "name": "大学城"}, {"parent_id": "D443", "children": [], "type": "A", "id": "A3611", "name": "中环城"}, {"parent_id": "D443", "children": [], "type": "A", "id": "A2422", "name": "翡翠路"}, {"parent_id": "D443", "children": [], "type": "A", "id": "A2878", "name": "港澳广场"}], "type": "D", "id": "D443", "name": "经开区"}, {"parent_id": "C142", "children": [ {"parent_id": "D445", "children": [], "type": "A", "id": "A1955", "name": "逍遥津"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A4383", "name": "阜南路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A3275", "name": "财富广场"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A759", "name": "步行街"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A283", "name": "欢乐颂"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A982", "name": "老报馆"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A732", "name": "黄山大厦"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1575", "name": "市府广场"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1808", "name": "白水坝"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1801", "name": "杏花公园"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A2066", "name": "颍上路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1275", "name": "女人街"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1172", "name": "蒙城北路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A2157", "name": "沿河路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A3612", "name": "城隍庙"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1350", "name": "双岗"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A2119", "name": "银泰百货"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A502", "name": "淮河路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1412", "name": "三孝口"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1675", "name": "四牌楼"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A4165", "name": "豆瓣汇步行街"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A2423", "name": "亳州路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1506", "name": "宿州路"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A3906", "name": "电子16所"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A2879", "name": "百花井"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A1470", "name": "四里河"}, {"parent_id": "D445", "children": [], "type": "A", "id": "A74", "name": "红星路"}], "type": "D", "id": "D445", "name": "庐阳区"}, {"parent_id": "C142", "children": [ {"parent_id": "D446", "children": [], "type": "A", "id": "A4384", "name": "黄金广场"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A3276", "name": "国购广场"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A284", "name": "清溪路大润发"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A3613", "name": "根据地美食广场"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A983", "name": "省体育场"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1809", "name": "长江西路华联"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A2880", "name": "大唐国际乐购"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1276", "name": "皖河支路美食街"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A733", "name": "松芝万象城"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1173", "name": "望潜交口"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1351", "name": "新华学院"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A503", "name": "三里庵"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A760", "name": "1912街区"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A4166", "name": "黄潜交口"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A2424", "name": "大铺头"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A3907", "name": "贵池路美食街"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1471", "name": "中科大"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A1413", "name": "之心城"}, {"parent_id": "D446", "children": [], "type": "A", "id": "A75", "name": "青阳路"}], "type": "D", "id": "D446", "name": "蜀山区"}, {"parent_id": "C142", "children": [ {"parent_id": "D447", "children": [], "type": "A", "id": "A761", "name": "胜利广场"}], "type": "D", "id": "D447", "name": "新站区"}, {"parent_id": "C142", "children": [ {"parent_id": "D437", "children": [], "type": "A", "id": "A4382", "name": "南七"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A4164", "name": "宁国路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A3273", "name": "九华山路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A282", "name": "太湖路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A981", "name": "宣城路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A1806", "name": "包河花园"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A731", "name": "望江东路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A1171", "name": "周谷堆"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A3610", "name": "马鞍山路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A501", "name": "桐城路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A2421", "name": "徽州大道"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A3905", "name": "万达广场"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A756", "name": "百脑汇"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A2877", "name": "芜湖路"}, {"parent_id": "D437", "children": [], "type": "A", "id": "A73", "name": "南二环路"}], "type": "D", "id": "D437", "name": "包河区"}, {"parent_id": "C142", "children": [], "type": "D", "id": "D439", "name": "巢湖市"}, {"parent_id": "C142", "children": [ {"parent_id": "D438", "children": [], "type": "A", "id": "A757", "name": "滨湖世纪城"}], "type": "D", "id": "D438", "name": "滨湖区"}, {"parent_id": "C142", "children": [ {"parent_id": "D450", "children": [], "type": "A", "id": "A763", "name": "绿地蓝海"}, {"parent_id": "D450", "children": [], "type": "A", "id": "A2426", "name": "新地中心"}, {"parent_id": "D450", "children": [], "type": "A", "id": "A1811", "name": "天鹅湖万达广场"}], "type": "D", "id": "D450", "name": "政务区"}], "type": "C", "id": "C142", "name": "合肥"}, {"parent_id": "P4", "children": [ {"parent_id": "C143", "children": [ {"parent_id": "D458", "children": [], "type": "A", "id": "A4387", "name": "南瑞"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A287", "name": "瑞丰商博城"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A3911", "name": "江岸明珠"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A4170", "name": "鲁港新镇"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A2884", "name": "汇成名郡"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A736", "name": "中央城财富街"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A3617", "name": "黄山园"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A506", "name": "新时代商业街"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A767", "name": "柏庄时代广场"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A2429", "name": "大砻坊"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A3280", "name": "火龙岗"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A1815", "name": "长江长"}, {"parent_id": "D458", "children": [], "type": "A", "id": "A78", "name": "欧尚超市"}], "type": "D", "id": "D458", "name": "弋江区"}, {"parent_id": "C143", "children": [], "type": "D", "id": "D453", "name": "南陵县"}, {"parent_id": "C143", "children": [ {"parent_id": "D452", "children": [], "type": "A", "id": "A3279", "name": "凤凰城"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A3910", "name": "金湾"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A2883", "name": "方特二期"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A3616", "name": "经济技术开发区"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A765", "name": "波尔卡"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A4169", "name": "银湖小区"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A2428", "name": "东部星城"}, {"parent_id": "D452", "children": [], "type": "A", "id": "A1813", "name": "大桥新城"}], "type": "D", "id": "D452", "name": "鸠江区"}, {"parent_id": "C143", "children": [ {"parent_id": "D451", "children": [], "type": "A", "id": "A1956", "name": "新市口"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A4386", "name": "二街"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2120", "name": "星隆国际"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A3278", "name": "第九中学"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A286", "name": "汇金广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A985", "name": "凯德广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2183", "name": "小九华商业街"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A735", "name": "黄山西路"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1576", "name": "神山口"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1802", "name": "五一广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2067", "name": "新芜路"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2882", "name": "大润发"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1277", "name": "绿地世纪城"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1174", "name": "联盛广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2158", "name": "香格里拉"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A3615", "name": "第八中学"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1352", "name": "两站广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A505", "name": "华强城"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1414", "name": "银湖路欧尚"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1676", "name": "万达广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A764", "name": "步行街"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A4168", "name": "东方龙城"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2427", "name": "北门"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1507", "name": "融汇中江广场"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A3909", "name": "第三中学"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A2205", "name": "左岸生活"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1472", "name": "侨鸿国际"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A1812", "name": "滨江世茂"}, {"parent_id": "D451", "children": [], "type": "A", "id": "A77", "name": "凤凰美食街"}], "type": "D", "id": "D451", "name": "镜湖区"}, {"parent_id": "C143", "children": [], "type": "D", "id": "D457", "name": "无为县"}, {"parent_id": "C143", "children": [], "type": "D", "id": "D456", "name": "芜湖县"}, {"parent_id": "C143", "children": [ {"parent_id": "D455", "children": [], "type": "A", "id": "A766", "name": "碧桂园"}, {"parent_id": "D455", "children": [], "type": "A", "id": "A1814", "name": "三华路"}], "type": "D", "id": "D455", "name": "三山区"}, {"parent_id": "C143", "children": [], "type": "D", "id": "D454", "name": "繁昌县"}], "type": "C", "id": "C143", "name": "芜湖"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C144", "name": "蚌埠"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C145", "name": "淮南"}, {"parent_id": "P4", "children": [ {"parent_id": "C146", "children": [ {"parent_id": "D464", "children": [], "type": "A", "id": "A2431", "name": "润翔购物广场"}, {"parent_id": "D464", "children": [], "type": "A", "id": "A2886", "name": "市政广场"}, {"parent_id": "D464", "children": [], "type": "A", "id": "A769", "name": "中冶华天"}, {"parent_id": "D464", "children": [], "type": "A", "id": "A3282", "name": "花雨广场"}, {"parent_id": "D464", "children": [], "type": "A", "id": "A1817", "name": "华润苏果"}], "type": "D", "id": "D464", "name": "雨山区"}, {"parent_id": "C146", "children": [], "type": "D", "id": "D462", "name": "和县"}, {"parent_id": "C146", "children": [ {"parent_id": "D463", "children": [], "type": "A", "id": "A2430", "name": "大华"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A3912", "name": "新亚"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A2885", "name": "欧尚"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A3618", "name": "新一城"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A768", "name": "大润发"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A3281", "name": "明都财富广场"}, {"parent_id": "D463", "children": [], "type": "A", "id": "A1816", "name": "解放路"}], "type": "D", "id": "D463", "name": "花山区"}, {"parent_id": "C146", "children": [], "type": "D", "id": "D460", "name": "当涂县"}, {"parent_id": "C146", "children": [], "type": "D", "id": "D461", "name": "含山县"}, {"parent_id": "C146", "children": [], "type": "D", "id": "D459", "name": "博望区"}], "type": "C", "id": "C146", "name": "马鞍山"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C147", "name": "淮北"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C148", "name": "铜陵"}, {"parent_id": "P4", "children": [], "type": "C", "id": "C149", "name": "安庆"}], "type": "P", "id": "P4", "name": "安徽"}, {"parent_id": "N1", "children": [ {"parent_id": "P6", "children": [], "type": "C", "id": "C179", "name": "宜春"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C178", "name": "吉安"}, {"parent_id": "P6", "children": [ {"parent_id": "C171", "children": [ {"parent_id": "D507", "children": [], "type": "A", "id": "A825", "name": "红谷滩"}, {"parent_id": "D507", "children": [], "type": "A", "id": "A3299", "name": "安义县"}, {"parent_id": "D507", "children": [], "type": "A", "id": "A2903", "name": "新建县"}, {"parent_id": "D507", "children": [], "type": "A", "id": "A2450", "name": "南昌县"}, {"parent_id": "D507", "children": [], "type": "A", "id": "A1847", "name": "进贤县"}], "type": "D", "id": "D507", "name": "近郊"}, {"parent_id": "C171", "children": [ {"parent_id": "D506", "children": [], "type": "A", "id": "A824", "name": "八一广场/省府"}, {"parent_id": "D506", "children": [], "type": "A", "id": "A3298", "name": "中山路"}, {"parent_id": "D506", "children": [], "type": "A", "id": "A2902", "name": "胜利路"}, {"parent_id": "D506", "children": [], "type": "A", "id": "A1846", "name": "叠山路"}, {"parent_id": "D506", "children": [], "type": "A", "id": "A2449", "name": "青山路沿线"}], "type": "D", "id": "D506", "name": "东湖区"}, {"parent_id": "C171", "children": [ {"parent_id": "D509", "children": [], "type": "A", "id": "A827", "name": "昌南"}, {"parent_id": "D509", "children": [], "type": "A", "id": "A2905", "name": "象湖"}, {"parent_id": "D509", "children": [], "type": "A", "id": "A2452", "name": "江铃桥"}, {"parent_id": "D509", "children": [], "type": "A", "id": "A1849", "name": "洪都"}], "type": "D", "id": "D509", "name": "青云谱区"}, {"parent_id": "C171", "children": [ {"parent_id": "D508", "children": [], "type": "A", "id": "A826", "name": "北京东路"}, {"parent_id": "D508", "children": [], "type": "A", "id": "A2904", "name": "南京东路"}, {"parent_id": "D508", "children": [], "type": "A", "id": "A2451", "name": "南昌大学"}, {"parent_id": "D508", "children": [], "type": "A", "id": "A1848", "name": "京东大道"}, {"parent_id": "D508", "children": [], "type": "A", "id": "A3632", "name": "下罗"}, {"parent_id": "D508", "children": [], "type": "A", "id": "A3300", "name": "上海路"}], "type": "D", "id": "D508", "name": "青山湖区"}, {"parent_id": "C171", "children": [], "type": "D", "id": "D510", "name": "湾里区"}, {"parent_id": "C171", "children": [ {"parent_id": "D511", "children": [], "type": "A", "id": "A828", "name": "丁公路"}, {"parent_id": "D511", "children": [], "type": "A", "id": "A2906", "name": "绳金塔"}, {"parent_id": "D511", "children": [], "type": "A", "id": "A2453", "name": "孺子路"}, {"parent_id": "D511", "children": [], "type": "A", "id": "A3301", "name": "桃源/司马庙"}, {"parent_id": "D511", "children": [], "type": "A", "id": "A1850", "name": "火车站"}], "type": "D", "id": "D511", "name": "西湖区"}], "type": "C", "id": "C171", "name": "南昌"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C173", "name": "萍乡"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C172", "name": "景德镇"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C175", "name": "新余"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C174", "name": "九江"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C177", "name": "赣州"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C176", "name": "鹰潭"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C184", "name": "庐山"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C185", "name": "井冈山"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C186", "name": "三清山"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C181", "name": "抚州"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C182", "name": "上饶"}, {"parent_id": "P6", "children": [], "type": "C", "id": "C183", "name": "婺源"}], "type": "P", "id": "P6", "name": "江西"}, {"parent_id": "N1", "children": [ {"parent_id": "P8", "children": [ {"parent_id": "C429", "children": [ {"parent_id": "D1057", "children": [], "type": "A", "id": "A1364", "name": "登封市"}, {"parent_id": "D1057", "children": [], "type": "A", "id": "A3464", "name": "荥阳市"}, {"parent_id": "D1057", "children": [], "type": "A", "id": "A2678", "name": "新郑市"}, {"parent_id": "D1057", "children": [], "type": "A", "id": "A3100", "name": "新密市"}, {"parent_id": "D1057", "children": [], "type": "A", "id": "A3774", "name": "中牟县"}, {"parent_id": "D1057", "children": [], "type": "A", "id": "A2164", "name": "巩义市"}], "type": "D", "id": "D1057", "name": "近郊"}, {"parent_id": "C429", "children": [], "type": "D", "id": "D1056", "name": "惠济区"}, {"parent_id": "C429", "children": [ {"parent_id": "D1059", "children": [], "type": "A", "id": "A1366", "name": "铝城公园"}], "type": "D", "id": "D1059", "name": "上街区"}, {"parent_id": "C429", "children": [ {"parent_id": "D1058", "children": [], "type": "A", "id": "A1365", "name": "宝龙城市广场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A3465", "name": "国贸360"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A165", "name": "科技市场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1321", "name": "天旺广场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A2679", "name": "东建材"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A571", "name": "普罗旺世"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A881", "name": "大石桥/体育场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A4052", "name": "经三路沿线"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A3101", "name": "丰业广场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1219", "name": "省电视台"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1391", "name": "文化路陈寨"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1110", "name": "金水路/省政府"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1489", "name": "郑州东站"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A4490", "name": "金城国际广场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A3775", "name": "花园路柳林"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A4291", "name": "建文新世界"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A382", "name": "曼哈顿广场"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A1436", "name": "郑东新区"}, {"parent_id": "D1058", "children": [], "type": "A", "id": "A2165", "name": "北大学城"}], "type": "D", "id": "D1058", "name": "金水区"}, {"parent_id": "C429", "children": [ {"parent_id": "D1055", "children": [], "type": "A", "id": "A1363", "name": "大上海城"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A3463", "name": "西大街"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A2677", "name": "经开区"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A4051", "name": "新世界百货/紫荆山"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A3773", "name": "康桥商务广场"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A3099", "name": "人民路"}, {"parent_id": "D1055", "children": [], "type": "A", "id": "A2163", "name": "富田太阳城"}], "type": "D", "id": "D1055", "name": "管城回族区"}, {"parent_id": "C429", "children": [], "type": "D", "id": "D1054", "name": "高新区"}, {"parent_id": "C429", "children": [ {"parent_id": "D1053", "children": [], "type": "A", "id": "A1362", "name": "长城康桥华城"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A3462", "name": "升龙广场"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A2676", "name": "二七路/火车站"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A4489", "name": "郑州大学"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A4050", "name": "郑铁体育中心"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A3772", "name": "鑫苑美适中心"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A4290", "name": "长江路沿线"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A3098", "name": "人民公园"}, {"parent_id": "D1053", "children": [], "type": "A", "id": "A2162", "name": "二七万达"}], "type": "D", "id": "D1053", "name": "二七区"}, {"parent_id": "C429", "children": [ {"parent_id": "D1060", "children": [], "type": "A", "id": "A1367", "name": "碧沙岗"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A3466", "name": "凯旋门"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A3776", "name": "绿城广场"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A4053", "name": "中原万达"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A3102", "name": "锦艺城"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A2680", "name": "儿童公园"}, {"parent_id": "D1060", "children": [], "type": "A", "id": "A2166", "name": "大学路"}], "type": "D", "id": "D1060", "name": "中原区"}], "type": "C", "id": "C429", "name": "郑州"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C216", "name": "开封"}, {"parent_id": "P8", "children": [ {"parent_id": "C217", "children": [], "type": "D", "id": "D656", "name": "宜阳县"}, {"parent_id": "C217", "children": [ {"parent_id": "D651", "children": [], "type": "A", "id": "A2501", "name": "九都路美食街"}, {"parent_id": "D651", "children": [], "type": "A", "id": "A1902", "name": "凯旋广场/大商新玛特"}, {"parent_id": "D651", "children": [], "type": "A", "id": "A3340", "name": "火车站"}, {"parent_id": "D651", "children": [], "type": "A", "id": "A2952", "name": "道北"}, {"parent_id": "D651", "children": [], "type": "A", "id": "A896", "name": "新都汇/王府井"}], "type": "D", "id": "D651", "name": "西工区"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D650", "name": "嵩县"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D653", "name": "新安县"}, {"parent_id": "C217", "children": [ {"parent_id": "D652", "children": [], "type": "A", "id": "A1903", "name": "大学城"}, {"parent_id": "D652", "children": [], "type": "A", "id": "A897", "name": "宝龙城市广场"}], "type": "D", "id": "D652", "name": "新区"}, {"parent_id": "C217", "children": [ {"parent_id": "D655", "children": [], "type": "A", "id": "A3669", "name": "八一路南段"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A3958", "name": "八一路北段"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A2502", "name": "北花坛/新车站"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A1904", "name": "大张盛德美"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A2953", "name": "文化南路"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A898", "name": "南花坛"}, {"parent_id": "D655", "children": [], "type": "A", "id": "A3341", "name": "文化北路"}], "type": "D", "id": "D655", "name": "伊川县"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D645", "name": "栾川县"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D648", "name": "孟津县"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D649", "name": "汝阳县"}, {"parent_id": "C217", "children": [ {"parent_id": "D642", "children": [], "type": "A", "id": "A3668", "name": "建设路沿线"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A3957", "name": "香港城/武汉路"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A2499", "name": "万达广场"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A3339", "name": "珠江路美食街"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A1900", "name": "广州市场/牡丹广场"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A4210", "name": "嵩山路沿线"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A2950", "name": "南昌路丹尼斯"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A893", "name": "上海市场"}, {"parent_id": "D642", "children": [], "type": "A", "id": "A4423", "name": "高新区"}], "type": "D", "id": "D642", "name": "涧西区"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D643", "name": "吉利区"}, {"parent_id": "C217", "children": [ {"parent_id": "D641", "children": [], "type": "A", "id": "A892", "name": "东花坛"}], "type": "D", "id": "D641", "name": "瀍河回族区"}, {"parent_id": "C217", "children": [ {"parent_id": "D646", "children": [], "type": "A", "id": "A2500", "name": "泉舜广场"}, {"parent_id": "D646", "children": [], "type": "A", "id": "A1901", "name": "安乐/师范学院"}, {"parent_id": "D646", "children": [], "type": "A", "id": "A2951", "name": "关林"}, {"parent_id": "D646", "children": [], "type": "A", "id": "A895", "name": "政和路美食街"}], "type": "D", "id": "D646", "name": "洛龙区"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D647", "name": "洛宁县"}, {"parent_id": "C217", "children": [ {"parent_id": "D644", "children": [], "type": "A", "id": "A894", "name": "老城"}], "type": "D", "id": "D644", "name": "老城区"}, {"parent_id": "C217", "children": [], "type": "D", "id": "D654", "name": "偃师市"}], "type": "C", "id": "C217", "name": "洛阳"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C218", "name": "平顶山"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C219", "name": "安阳"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C232", "name": "伊川"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C233", "name": "济源"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C230", "name": "周口"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C231", "name": "驻马店"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C229", "name": "信阳"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C228", "name": "商丘"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C225", "name": "漯河"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C224", "name": "许昌"}, {"parent_id": "P8", "children": [ {"parent_id": "C227", "children": [], "type": "D", "id": "D679", "name": "西峡县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D678", "name": "新野县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D677", "name": "淅川县"}, {"parent_id": "C227", "children": [ {"parent_id": "D676", "children": [], "type": "A", "id": "A532", "name": "金玛特"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A772", "name": "师院"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A334", "name": "鸿德"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A2507", "name": "滨河中路"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A112", "name": "梅溪路"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A908", "name": "火车站"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A3673", "name": "大统"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A4213", "name": "府衙"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A1909", "name": "裕华商城"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A3346", "name": "人民北路"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A3962", "name": "天桥"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A2958", "name": "滨河西路"}, {"parent_id": "D676", "children": [], "type": "A", "id": "A4426", "name": "新华城市广场"}], "type": "D", "id": "D676", "name": "卧龙区"}, {"parent_id": "C227", "children": [ {"parent_id": "D675", "children": [], "type": "A", "id": "A907", "name": "第二人民医院"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A2506", "name": "南阳五中"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A3672", "name": "枣林"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A1908", "name": "医圣祠"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A3345", "name": "南航大厦"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A3961", "name": "独山大道"}, {"parent_id": "D675", "children": [], "type": "A", "id": "A2957", "name": "钢材市场"}], "type": "D", "id": "D675", "name": "宛城区"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D674", "name": "桐柏县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D673", "name": "唐河县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D672", "name": "社旗县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D671", "name": "内乡县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D670", "name": "南召县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D680", "name": "镇平县"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D668", "name": "邓州市"}, {"parent_id": "C227", "children": [], "type": "D", "id": "D669", "name": "方城县"}], "type": "C", "id": "C227", "name": "南阳"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C226", "name": "三门峡"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C220", "name": "鹤壁"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C223", "name": "濮阳"}, {"parent_id": "P8", "children": [ {"parent_id": "C222", "children": [], "type": "D", "id": "D657", "name": "博爱县"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D664", "name": "温县"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D665", "name": "武陟县"}, {"parent_id": "C222", "children": [ {"parent_id": "D666", "children": [], "type": "A", "id": "A903", "name": "云台山"}], "type": "D", "id": "D666", "name": "修武县"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D667", "name": "中站区"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D660", "name": "马村区"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D661", "name": "孟州市"}, {"parent_id": "C222", "children": [], "type": "D", "id": "D662", "name": "沁阳市"}, {"parent_id": "C222", "children": [ {"parent_id": "D663", "children": [], "type": "A", "id": "A902", "name": "体院馆"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A333", "name": "新东"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A2505", "name": "新新家园"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A111", "name": "东方红"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A3671", "name": "艺新"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A1907", "name": "九一医院"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A4212", "name": "壹里洋场"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A3344", "name": "南北苑"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A3960", "name": "龙源湖"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A2956", "name": "太极景润"}, {"parent_id": "D663", "children": [], "type": "A", "id": "A4425", "name": "摩登街"}], "type": "D", "id": "D663", "name": "山阳区"}, {"parent_id": "C222", "children": [ {"parent_id": "D659", "children": [], "type": "A", "id": "A901", "name": "时代购物中心"}, {"parent_id": "D659", "children": [], "type": "A", "id": "A2504", "name": "信尧城市广场"}, {"parent_id": "D659", "children": [], "type": "A", "id": "A1906", "name": "源园广场"}, {"parent_id": "D659", "children": [], "type": "A", "id": "A2955", "name": "大商新世纪广场"}, {"parent_id": "D659", "children": [], "type": "A", "id": "A3343", "name": "凯旋城"}], "type": "D", "id": "D659", "name": "济源市"}, {"parent_id": "C222", "children": [ {"parent_id": "D658", "children": [], "type": "A", "id": "A531", "name": "万基商务中心"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A900", "name": "三维"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A3959", "name": "三维广场"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A332", "name": "大杨树"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A2503", "name": "学生路"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A110", "name": "新华街"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A3670", "name": "锦江现代城"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A1905", "name": "月季公园"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A4211", "name": "政二街"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A3342", "name": "香港城"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A2954", "name": "铜马尚品街"}, {"parent_id": "D658", "children": [], "type": "A", "id": "A4424", "name": "锦祥商业街"}], "type": "D", "id": "D658", "name": "解放区"}], "type": "C", "id": "C222", "name": "焦作"}, {"parent_id": "P8", "children": [], "type": "C", "id": "C221", "name": "新乡"}], "type": "P", "id": "P8", "name": "河南"}, {"parent_id": "N1", "children": [ {"parent_id": "P13", "children": [], "type": "C", "id": "C309", "name": "崇左"}, {"parent_id": "P13", "children": [ {"parent_id": "C298", "children": [], "type": "D", "id": "D879", "name": "全州县"}, {"parent_id": "C298", "children": [ {"parent_id": "D878", "children": [], "type": "A", "id": "A2007", "name": "理工大学"}, {"parent_id": "D878", "children": [], "type": "A", "id": "A1071", "name": "甲天下广场"}, {"parent_id": "D878", "children": [], "type": "A", "id": "A2579", "name": "三里店广场"}], "type": "D", "id": "D878", "name": "七星区"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D875", "name": "临桂县"}, {"parent_id": "C298", "children": [ {"parent_id": "D874", "children": [], "type": "A", "id": "A1070", "name": "八里街"}], "type": "D", "id": "D874", "name": "灵川县"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D877", "name": "龙胜各族自治县"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D876", "name": "荔浦县"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D873", "name": "恭城瑶族自治县"}, {"parent_id": "C298", "children": [ {"parent_id": "D872", "children": [], "type": "A", "id": "A1069", "name": "北极广场"}], "type": "D", "id": "D872", "name": "叠彩区"}, {"parent_id": "C298", "children": [ {"parent_id": "D880", "children": [], "type": "A", "id": "A2008", "name": "红街商业街"}, {"parent_id": "D880", "children": [], "type": "A", "id": "A1072", "name": "联达商业广场"}, {"parent_id": "D880", "children": [], "type": "A", "id": "A2580", "name": "西城路步行街"}, {"parent_id": "D880", "children": [], "type": "A", "id": "A3016", "name": "火车南站"}], "type": "D", "id": "D880", "name": "象山区"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D881", "name": "兴安县"}, {"parent_id": "C298", "children": [ {"parent_id": "D882", "children": [], "type": "A", "id": "A2009", "name": "阳桥"}, {"parent_id": "D882", "children": [], "type": "A", "id": "A1073", "name": "中心广场"}], "type": "D", "id": "D882", "name": "秀峰区"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D883", "name": "阳朔县"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D884", "name": "雁山区"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D885", "name": "永福县"}, {"parent_id": "C298", "children": [], "type": "D", "id": "D886", "name": "资源县"}], "type": "C", "id": "C298", "name": "桂林"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C299", "name": "梧州"}, {"parent_id": "P13", "children": [ {"parent_id": "C296", "children": [ {"parent_id": "D859", "children": [], "type": "A", "id": "A2127", "name": "万象城"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1599", "name": "七星路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A3990", "name": "凤岭南"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1684", "name": "青秀山"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1515", "name": "南湖公园"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2186", "name": "新竹路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A3705", "name": "凤岭北"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2000", "name": "茶花园路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1297", "name": "柳沙半岛"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2216", "name": "园湖路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1820", "name": "七星新民"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A350", "name": "航洋国际"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1988", "name": "双拥路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A4446", "name": "东葛望园"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1372", "name": "民族大道"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A784", "name": "金湖"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1424", "name": "民歌湖"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1480", "name": "民族广场"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A4237", "name": "凤翔路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1195", "name": "琅西"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A3010", "name": "东盟商务区"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A130", "name": "古城民族"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A3384", "name": "东葛古城"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2208", "name": "星湖路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1061", "name": "长湖路"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2269", "name": "竹溪大道"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2071", "name": "桃源天桃路口"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A1045", "name": "金花茶公园"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A544", "name": "会展中心"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2167", "name": "仙葫"}, {"parent_id": "D859", "children": [], "type": "A", "id": "A2573", "name": "东葛路"}], "type": "D", "id": "D859", "name": "青秀区"}, {"parent_id": "C296", "children": [ {"parent_id": "D858", "children": [], "type": "A", "id": "A3009", "name": "上林县"}, {"parent_id": "D858", "children": [], "type": "A", "id": "A3704", "name": "邕宁区"}, {"parent_id": "D858", "children": [], "type": "A", "id": "A3383", "name": "武鸣县"}, {"parent_id": "D858", "children": [], "type": "A", "id": "A1060", "name": "宾阳县"}, {"parent_id": "D858", "children": [], "type": "A", "id": "A1999", "name": "横县"}, {"parent_id": "D858", "children": [], "type": "A", "id": "A2572", "name": "良庆区"}], "type": "D", "id": "D858", "name": "近郊"}, {"parent_id": "C296", "children": [ {"parent_id": "D857", "children": [], "type": "A", "id": "A3008", "name": "五一路"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A1059", "name": "10+1商业大道"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A3703", "name": "星光大道"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A3989", "name": "香格里拉广场"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A3382", "name": "星光淡村"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A1998", "name": "白沙大道"}, {"parent_id": "D857", "children": [], "type": "A", "id": "A2571", "name": "大沙田"}], "type": "D", "id": "D857", "name": "江南区"}, {"parent_id": "C296", "children": [ {"parent_id": "D860", "children": [], "type": "A", "id": "A2001", "name": "朝阳广场"}, {"parent_id": "D860", "children": [], "type": "A", "id": "A3706", "name": "万达"}, {"parent_id": "D860", "children": [], "type": "A", "id": "A3011", "name": "人民公园"}, {"parent_id": "D860", "children": [], "type": "A", "id": "A3385", "name": "水街"}, {"parent_id": "D860", "children": [], "type": "A", "id": "A1062", "name": "朝阳"}, {"parent_id": "D860", "children": [], "type": "A", "id": "A2574", "name": "民主路"}], "type": "D", "id": "D860", "name": "兴宁区"}, {"parent_id": "C296", "children": [ {"parent_id": "D861", "children": [], "type": "A", "id": "A3991", "name": "火车站"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A4447", "name": "明秀路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A3707", "name": "衡阳路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A2002", "name": "北大路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A351", "name": "南棉商业街"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A785", "name": "相思湖"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A4238", "name": "鲁班路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A1196", "name": "友爱路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A3012", "name": "广西大学"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A131", "name": "南铁"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A3386", "name": "高新区"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A1063", "name": "北湖"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A1046", "name": "新阳路"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A545", "name": "五里亭"}, {"parent_id": "D861", "children": [], "type": "A", "id": "A2575", "name": "大学路"}], "type": "D", "id": "D861", "name": "西乡塘区"}], "type": "C", "id": "C296", "name": "南宁"}, {"parent_id": "P13", "children": [ {"parent_id": "C297", "children": [ {"parent_id": "D871", "children": [], "type": "A", "id": "A1068", "name": "谷埠街"}], "type": "D", "id": "D871", "name": "鱼峰区"}, {"parent_id": "C297", "children": [], "type": "D", "id": "D870", "name": "三江侗族自治县"}, {"parent_id": "C297", "children": [], "type": "D", "id": "D868", "name": "融水苗族自治县"}, {"parent_id": "C297", "children": [], "type": "D", "id": "D869", "name": "融安县"}, {"parent_id": "C297", "children": [ {"parent_id": "D862", "children": [], "type": "A", "id": "A3708", "name": "步步高"}, {"parent_id": "D862", "children": [], "type": "A", "id": "A2003", "name": "阳光100"}, {"parent_id": "D862", "children": [], "type": "A", "id": "A3013", "name": "南亚名邸"}, {"parent_id": "D862", "children": [], "type": "A", "id": "A3387", "name": "高新区"}, {"parent_id": "D862", "children": [], "type": "A", "id": "A1064", "name": "市中心"}, {"parent_id": "D862", "children": [], "type": "A", "id": "A2576", "name": "桂中"}], "type": "D", "id": "D862", "name": "城中区"}, {"parent_id": "C297", "children": [ {"parent_id": "D863", "children": [], "type": "A", "id": "A2004", "name": "柳北文化广场"}, {"parent_id": "D863", "children": [], "type": "A", "id": "A3014", "name": "欧雅城市广场"}, {"parent_id": "D863", "children": [], "type": "A", "id": "A1065", "name": "大润发"}, {"parent_id": "D863", "children": [], "type": "A", "id": "A2577", "name": "黄村"}], "type": "D", "id": "D863", "name": "柳北区"}, {"parent_id": "C297", "children": [ {"parent_id": "D866", "children": [], "type": "A", "id": "A2006", "name": "五菱"}, {"parent_id": "D866", "children": [], "type": "A", "id": "A3015", "name": "航银"}, {"parent_id": "D866", "children": [], "type": "A", "id": "A1067", "name": "河西"}, {"parent_id": "D866", "children": [], "type": "A", "id": "A2578", "name": "飞鹅"}], "type": "D", "id": "D866", "name": "柳南区"}, {"parent_id": "C297", "children": [], "type": "D", "id": "D867", "name": "鹿寨县"}, {"parent_id": "C297", "children": [], "type": "D", "id": "D864", "name": "柳城县"}, {"parent_id": "C297", "children": [ {"parent_id": "D865", "children": [], "type": "A", "id": "A2005", "name": "基隆"}, {"parent_id": "D865", "children": [], "type": "A", "id": "A1066", "name": "拉堡"}], "type": "D", "id": "D865", "name": "柳江县"}], "type": "C", "id": "C297", "name": "柳州"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C308", "name": "来宾"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C305", "name": "百色"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C310", "name": "阳朔"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C304", "name": "玉林"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C306", "name": "贺州"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C307", "name": "河池"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C302", "name": "钦州"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C303", "name": "贵港"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C300", "name": "北海"}, {"parent_id": "P13", "children": [], "type": "C", "id": "C301", "name": "防城港"}], "type": "P", "id": "P13", "name": "广西"}, {"parent_id": "N1", "children": [ {"parent_id": "P14", "children": [ {"parent_id": "C311", "children": [ {"parent_id": "D909", "children": [], "type": "A", "id": "A1098", "name": "铜鼓岭"}], "type": "D", "id": "D909", "name": "文昌市"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D908", "name": "屯昌县"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D901", "name": "定安县"}, {"parent_id": "C311", "children": [ {"parent_id": "D900", "children": [], "type": "A", "id": "A1093", "name": "洋浦"}], "type": "D", "id": "D900", "name": "儋州市"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D899", "name": "澄迈县"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D898", "name": "昌江县"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D897", "name": "白沙县"}, {"parent_id": "C311", "children": [ {"parent_id": "D910", "children": [], "type": "A", "id": "A2592", "name": "南沙城市广场/万瑞广场"}, {"parent_id": "D910", "children": [], "type": "A", "id": "A3398", "name": "西站"}, {"parent_id": "D910", "children": [], "type": "A", "id": "A3027", "name": "时代广场"}, {"parent_id": "D910", "children": [], "type": "A", "id": "A2026", "name": "假日海滩/西海岸"}, {"parent_id": "D910", "children": [], "type": "A", "id": "A1099", "name": "火山口"}], "type": "D", "id": "D910", "name": "秀英区"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D903", "name": "临高县"}, {"parent_id": "C311", "children": [], "type": "D", "id": "D902", "name": "东方市"}, {"parent_id": "C311", "children": [ {"parent_id": "D905", "children": [], "type": "A", "id": "A4247", "name": "名门广场"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A2590", "name": "复兴城"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A3396", "name": "国兴大道"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A3025", "name": "国兴大润发"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A2024", "name": "滨江路"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A356", "name": "望海国际广场"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A1058", "name": "新埠岛"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A4455", "name": "明珠广场"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A1095", "name": "白龙路沿线"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A788", "name": "新港/长堤路"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A549", "name": "文明路/和平路"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A1198", "name": "亿圣和广场"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A137", "name": "南亚广场"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A3717", "name": "海甸岛"}, {"parent_id": "D905", "children": [], "type": "A", "id": "A4000", "name": "灵山镇"}], "type": "D", "id": "D905", "name": "美兰区"}, {"parent_id": "C311", "children": [ {"parent_id": "D904", "children": [], "type": "A", "id": "A4246", "name": "金山广场"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A3999", "name": "金盘"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A3395", "name": "解放西/泰龙城"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A3024", "name": "金牛岭公园"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A2023", "name": "东湖"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A3716", "name": "京华城"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A355", "name": "南站/南海大道"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A1094", "name": "滨海大道东段"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A787", "name": "宜欣广场"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A2589", "name": "金龙路/国贸大道"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A4454", "name": "龙昆北路"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A548", "name": "万国大都会"}, {"parent_id": "D904", "children": [], "type": "A", "id": "A136", "name": "南沙路"}], "type": "D", "id": "D904", "name": "龙华区"}, {"parent_id": "C311", "children": [ {"parent_id": "D907", "children": [], "type": "A", "id": "A2591", "name": "红城湖"}, {"parent_id": "D907", "children": [], "type": "A", "id": "A3397", "name": "中山路/中介路"}, {"parent_id": "D907", "children": [], "type": "A", "id": "A2025", "name": "高铁东站/凤翔路"}, {"parent_id": "D907", "children": [], "type": "A", "id": "A3026", "name": "龙昆南路"}, {"parent_id": "D907", "children": [], "type": "A", "id": "A1097", "name": "城西"}], "type": "D", "id": "D907", "name": "琼山区"}, {"parent_id": "C311", "children": [ {"parent_id": "D906", "children": [], "type": "A", "id": "A1096", "name": "博鳌"}], "type": "D", "id": "D906", "name": "琼海市"}], "type": "C", "id": "C311", "name": "海口"}, {"parent_id": "P14", "children": [], "type": "C", "id": "C313", "name": "琼海"}, {"parent_id": "P14", "children": [ {"parent_id": "C312", "children": [], "type": "D", "id": "D920", "name": "琼中县"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D911", "name": "保亭县"}, {"parent_id": "C312", "children": [ {"parent_id": "D923", "children": [], "type": "A", "id": "A1104", "name": "兴隆"}], "type": "D", "id": "D923", "name": "万宁市"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D922", "name": "天涯镇"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D927", "name": "育才镇"}, {"parent_id": "C312", "children": [ {"parent_id": "D926", "children": [], "type": "A", "id": "A1105", "name": "亚龙湾百花谷"}], "type": "D", "id": "D926", "name": "亚龙湾度假区"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D925", "name": "崖城镇"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D924", "name": "五指山市"}, {"parent_id": "C312", "children": [ {"parent_id": "D916", "children": [], "type": "A", "id": "A4248", "name": "渔人码头"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A1102", "name": "步行街"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A2594", "name": "第一市场"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A3399", "name": "河西路"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A3029", "name": "国际购物中心"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A2028", "name": "春园海鲜广场"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A3718", "name": "解放路"}, {"parent_id": "D916", "children": [], "type": "A", "id": "A4001", "name": "明珠广场"}], "type": "D", "id": "D916", "name": "河西区"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D917", "name": "吉阳镇"}, {"parent_id": "C312", "children": [ {"parent_id": "D914", "children": [], "type": "A", "id": "A1100", "name": "海棠湾国家海岸旅游区"}], "type": "D", "id": "D914", "name": "海棠湾区"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D913", "name": "凤凰镇"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D918", "name": "乐东县"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D919", "name": "陵水县"}, {"parent_id": "C312", "children": [ {"parent_id": "D915", "children": [], "type": "A", "id": "A2593", "name": "商品街"}, {"parent_id": "D915", "children": [], "type": "A", "id": "A3028", "name": "下洋田"}, {"parent_id": "D915", "children": [], "type": "A", "id": "A2027", "name": "酒吧一条街"}, {"parent_id": "D915", "children": [], "type": "A", "id": "A1101", "name": "金鸡岭"}], "type": "D", "id": "D915", "name": "河东区"}, {"parent_id": "C312", "children": [], "type": "D", "id": "D912", "name": "大东海度假区"}, {"parent_id": "C312", "children": [ {"parent_id": "D921", "children": [], "type": "A", "id": "A1103", "name": "凤凰岛"}, {"parent_id": "D921", "children": [], "type": "A", "id": "A2029", "name": "海坡度假区"}], "type": "D", "id": "D921", "name": "三亚湾"}], "type": "C", "id": "C312", "name": "三亚"}], "type": "P", "id": "P14", "name": "海南"}, {"parent_id": "N1", "children": [ {"parent_id": "P15", "children": [ {"parent_id": "C295", "children": [ {"parent_id": "D893", "children": [], "type": "A", "id": "A4242", "name": "四公里"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A3995", "name": "上海城"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A3712", "name": "南岸区府"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A3391", "name": "南滨路"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A3020", "name": "黄桷垭/南山"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A353", "name": "协信星光时代广场"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A4451", "name": "万达广场"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A2585", "name": "回龙湾"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A134", "name": "五公里"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A2019", "name": "弹子石"}, {"parent_id": "D893", "children": [], "type": "A", "id": "A1089", "name": "南坪"}], "type": "D", "id": "D893", "name": "南岸区"}, {"parent_id": "C295", "children": [ {"parent_id": "D891", "children": [], "type": "A", "id": "A1600", "name": "巫山县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A2128", "name": "长寿区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A4240", "name": "合川区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1516", "name": "武隆县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A3993", "name": "丰都县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A4449", "name": "江津区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1685", "name": "秀山土家族苗族自治县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1298", "name": "黔江区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A3710", "name": "涪陵区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1821", "name": "永川区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A352", "name": "梁平县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1057", "name": "彭水苗族土家族自治县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1425", "name": "铜梁县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1373", "name": "荣昌县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A786", "name": "南川区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A2583", "name": "大足区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1481", "name": "潼南县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1197", "name": "綦江区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A3018", "name": "垫江县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A133", "name": "开县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A3389", "name": "石柱土家族自治县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A2017", "name": "城口县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A2072", "name": "酉阳土家族苗族自治县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A546", "name": "万州区"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1997", "name": "云阳县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A2168", "name": "忠县"}, {"parent_id": "D891", "children": [], "type": "A", "id": "A1087", "name": "璧山县"}], "type": "D", "id": "D891", "name": "近郊"}, {"parent_id": "C295", "children": [ {"parent_id": "D890", "children": [], "type": "A", "id": "A3992", "name": "五里店/江北嘴"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A3709", "name": "家乐福/华新街"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A4448", "name": "小苑/鸿恩寺"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A2582", "name": "大庙/红旗河沟"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A4239", "name": "建新东路/大兴村"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A3017", "name": "大石坝/盘溪/南桥寺"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A132", "name": "洋河"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A3388", "name": "观音桥"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A2016", "name": "北滨路/金源/星悦荟"}, {"parent_id": "D890", "children": [], "type": "A", "id": "A1086", "name": "北城天街/星光68/九街"}], "type": "D", "id": "D890", "name": "江北区"}, {"parent_id": "C295", "children": [ {"parent_id": "D896", "children": [], "type": "A", "id": "A4245", "name": "临江门"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A3394", "name": "化龙桥/重庆天地"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A3023", "name": "大礼堂"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A3998", "name": "较场口"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A2022", "name": "长滨路"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A3715", "name": "解放碑"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A354", "name": "上清寺"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A4453", "name": "两路口"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A1092", "name": "菜园坝"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A2588", "name": "大坪"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A135", "name": "七星岗"}, {"parent_id": "D896", "children": [], "type": "A", "id": "A547", "name": "朝天门"}], "type": "D", "id": "D896", "name": "渝中区"}, {"parent_id": "C295", "children": [ {"parent_id": "D895", "children": [], "type": "A", "id": "A4244", "name": "人和"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A3393", "name": "龙头寺"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A3022", "name": "龙溪"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A3997", "name": "冉家坝"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A2021", "name": "黄泥塝"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A3714", "name": "汽博中心"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A1091", "name": "大竹林"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A2587", "name": "两路"}, {"parent_id": "D895", "children": [], "type": "A", "id": "A4452", "name": "新牌坊/龙湖"}], "type": "D", "id": "D895", "name": "渝北区"}, {"parent_id": "C295", "children": [ {"parent_id": "D894", "children": [], "type": "A", "id": "A4243", "name": "小龙坎"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A3996", "name": "天星桥"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A3392", "name": "烈士墓"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A3021", "name": "歌乐山"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A3713", "name": "三峡广场"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A2020", "name": "磁器口"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A1090", "name": "重庆大学"}, {"parent_id": "D894", "children": [], "type": "A", "id": "A2586", "name": "大学城"}], "type": "D", "id": "D894", "name": "沙坪坝区"}, {"parent_id": "C295", "children": [ {"parent_id": "D892", "children": [], "type": "A", "id": "A4241", "name": "杨家坪"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A3994", "name": "谢家湾"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A3390", "name": "开发区"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A4450", "name": "袁家岗"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A2584", "name": "动物园"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A3019", "name": "黄桷坪"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A3711", "name": "石桥铺"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A2018", "name": "陈家坪"}, {"parent_id": "D892", "children": [], "type": "A", "id": "A1088", "name": "巴国城"}], "type": "D", "id": "D892", "name": "九龙坡区"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D190", "name": "义县"}, {"parent_id": "C295", "children": [ {"parent_id": "D888", "children": [], "type": "A", "id": "A2581", "name": "天生桥"}, {"parent_id": "D888", "children": [], "type": "A", "id": "A2015", "name": "老城区/天奇广场"}, {"parent_id": "D888", "children": [], "type": "A", "id": "A1084", "name": "城北"}], "type": "D", "id": "D888", "name": "北碚区"}, {"parent_id": "C295", "children": [ {"parent_id": "D889", "children": [], "type": "A", "id": "A1085", "name": "大渡口公园"}], "type": "D", "id": "D889", "name": "大渡口区"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D887", "name": "巴南区"}, {"parent_id": "C295", "children": [ {"parent_id": "D189", "children": [], "type": "A", "id": "A1644", "name": "锦阳高中"}, {"parent_id": "D189", "children": [], "type": "A", "id": "A2308", "name": "典逸心洲"}, {"parent_id": "D189", "children": [], "type": "A", "id": "A424", "name": "渤海大学"}], "type": "D", "id": "D189", "name": "太和区"}, {"parent_id": "C295", "children": [ {"parent_id": "D188", "children": [], "type": "A", "id": "A1643", "name": "宝地曼哈顿"}, {"parent_id": "D188", "children": [], "type": "A", "id": "A2307", "name": "市府广场"}, {"parent_id": "D188", "children": [], "type": "A", "id": "A423", "name": "锦绣天第"}], "type": "D", "id": "D188", "name": "松山新区"}, {"parent_id": "C295", "children": [ {"parent_id": "D183", "children": [], "type": "A", "id": "A3839", "name": "单洞批发市场"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A1641", "name": "辽工"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A2780", "name": "化工学校"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A3188", "name": "红星楼"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A2305", "name": "人民街金陵"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A4105", "name": "西安街蔬菜市场"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A3534", "name": "医学院"}, {"parent_id": "D183", "children": [], "type": "A", "id": "A421", "name": "大润发"}], "type": "D", "id": "D183", "name": "古塔区"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D182", "name": "北镇市"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D185", "name": "经济开发区"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D184", "name": "黑山县"}, {"parent_id": "C295", "children": [ {"parent_id": "D187", "children": [], "type": "A", "id": "A1642", "name": "体育场"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A4335", "name": "中央大街三角地"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A2781", "name": "百货大楼"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A3840", "name": "啤酒厂"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A3189", "name": "火车站"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A2306", "name": "大商B座"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A464", "name": "家乐汇"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A4106", "name": "白楼"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A3535", "name": "五里"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A422", "name": "马家"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A31", "name": "千盛广场"}, {"parent_id": "D187", "children": [], "type": "A", "id": "A223", "name": "北湖公园"}], "type": "D", "id": "D187", "name": "凌河区"}, {"parent_id": "C295", "children": [], "type": "D", "id": "D186", "name": "凌海市"}], "type": "C", "id": "C295", "name": "重庆"}], "type": "P", "id": "P15", "name": "重庆"}, {"parent_id": "N1", "children": [ {"parent_id": "P16", "children": [ {"parent_id": "C375", "children": [ {"parent_id": "D1019", "children": [], "type": "A", "id": "A3441", "name": "马超路"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A2107", "name": "电子路"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A4034", "name": "天缘路"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A4275", "name": "新城市广场"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A2647", "name": "桂湖"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A3075", "name": "静安路"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A1242", "name": "大丰"}, {"parent_id": "D1019", "children": [], "type": "A", "id": "A3753", "name": "蜀龙大道中段"}], "type": "D", "id": "D1019", "name": "新都区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1018", "children": [], "type": "A", "id": "A1609", "name": "石羊场"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1381", "name": "倪家桥"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A3440", "name": "高棚大道"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2106", "name": "玉林"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A823", "name": "科华路王府井"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A4476", "name": "华西坝"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A374", "name": "九茹村"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A4033", "name": "红瓦寺"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1845", "name": "外双楠"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2171", "name": "小南街"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2137", "name": "新南门"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A4274", "name": "火车南站"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1487", "name": "耍都"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A564", "name": "科华北路"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1691", "name": "桐梓林"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A156", "name": "航空路"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2646", "name": "大石路"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1522", "name": "省体育馆"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2014", "name": "武侯祠"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A3074", "name": "高升桥"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1311", "name": "磨子桥"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1241", "name": "簇桥"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A2077", "name": "五大花园"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A3752", "name": "红牌楼"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1206", "name": "鹭岛国际"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1432", "name": "双楠"}, {"parent_id": "D1018", "children": [], "type": "A", "id": "A1083", "name": "龙腾路"}], "type": "D", "id": "D1018", "name": "武侯区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1011", "children": [], "type": "A", "id": "A1607", "name": "西安北路"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A2100", "name": "北门大桥"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1689", "name": "营门口"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1309", "name": "蜀汉路"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A3749", "name": "花牌坊"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A821", "name": "驷马桥"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A4474", "name": "金牛万达广场"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A372", "name": "李家沱"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A4030", "name": "欢乐谷"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1843", "name": "一品天下"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1235", "name": "北较场"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1379", "name": "沙湾"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A4272", "name": "火车北站"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1485", "name": "五块石"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A562", "name": "梁家巷"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A154", "name": "凯德广场·金牛"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A2642", "name": "茶店子"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1520", "name": "西南交大"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A2013", "name": "羊西线"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A3070", "name": "抚琴"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A2076", "name": "中海国际"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1204", "name": "人民北路"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1430", "name": "同盛路"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A1081", "name": "马家花园"}, {"parent_id": "D1011", "children": [], "type": "A", "id": "A3436", "name": "高笋塘"}], "type": "D", "id": "D1011", "name": "金牛区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1010", "children": [], "type": "A", "id": "A3748", "name": "蒲江县"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A3069", "name": "金堂县"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A1234", "name": "崇州市"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A4271", "name": "新津县"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A2099", "name": "都江堰市"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A3435", "name": "彭州市"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A2641", "name": "大邑县"}, {"parent_id": "D1010", "children": [], "type": "A", "id": "A4029", "name": "邛崃市"}], "type": "D", "id": "D1010", "name": "近郊"}, {"parent_id": "C375", "children": [ {"parent_id": "D1013", "children": [], "type": "A", "id": "A2102", "name": "红光"}, {"parent_id": "D1013", "children": [], "type": "A", "id": "A1237", "name": "高新西区"}, {"parent_id": "D1013", "children": [], "type": "A", "id": "A2643", "name": "郫筒"}, {"parent_id": "D1013", "children": [], "type": "A", "id": "A3071", "name": "团结"}, {"parent_id": "D1013", "children": [], "type": "A", "id": "A3437", "name": "犀浦"}], "type": "D", "id": "D1013", "name": "郫县"}, {"parent_id": "C375", "children": [ {"parent_id": "D1012", "children": [], "type": "A", "id": "A2101", "name": "十陵镇"}, {"parent_id": "D1012", "children": [], "type": "A", "id": "A1236", "name": "龙都南路"}], "type": "D", "id": "D1012", "name": "龙泉驿区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1015", "children": [], "type": "A", "id": "A1608", "name": "天府广场"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1380", "name": "仁和春天"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A2103", "name": "草市街"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A822", "name": "清江西路"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A4475", "name": "宽窄巷子"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A373", "name": "青羊宫"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A4031", "name": "光华村"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1844", "name": "优品道"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1238", "name": "八宝街"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A4273", "name": "金沙遗址"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1486", "name": "顺城大街"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A563", "name": "清江东路"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A3750", "name": "府南新区"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A3438", "name": "杜甫草堂"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1690", "name": "文殊院"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A155", "name": "骡马市"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A2644", "name": "成温立交"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1521", "name": "太升路"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A3072", "name": "成飞大道"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1310", "name": "清水河公园"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1205", "name": "青龙街"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1431", "name": "人民公园"}, {"parent_id": "D1015", "children": [], "type": "A", "id": "A1082", "name": "琴台"}], "type": "D", "id": "D1015", "name": "青羊区"}, {"parent_id": "C375", "children": [], "type": "D", "id": "D1014", "name": "青白江区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1017", "children": [], "type": "A", "id": "A2105", "name": "南浦盛宴"}, {"parent_id": "D1017", "children": [], "type": "A", "id": "A1240", "name": "城市公园"}], "type": "D", "id": "D1017", "name": "温江区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1016", "children": [], "type": "A", "id": "A2104", "name": "东升镇"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A4032", "name": "双流机场"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A1239", "name": "奥特莱斯"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A3439", "name": "戛纳湾"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A2645", "name": "伏龙小区"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A3073", "name": "华阳"}, {"parent_id": "D1016", "children": [], "type": "A", "id": "A3751", "name": "蛟龙港"}], "type": "D", "id": "D1016", "name": "双流县"}, {"parent_id": "C375", "children": [ {"parent_id": "D1008", "children": [], "type": "A", "id": "A3746", "name": "天府长城"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A2639", "name": "九方购物中心"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A4472", "name": "紫荆"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A3067", "name": "神仙树"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A4269", "name": "肖家河"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A1232", "name": "孵化园"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A2097", "name": "芳草街"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A3433", "name": "天府二街"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A152", "name": "中和"}, {"parent_id": "D1008", "children": [], "type": "A", "id": "A4027", "name": "新会展中心"}], "type": "D", "id": "D1008", "name": "高新区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1009", "children": [], "type": "A", "id": "A1606", "name": "三圣乡"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1688", "name": "四川师大"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1308", "name": "莲桂南路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1519", "name": "仁恒置地"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2188", "name": "盐市口"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A820", "name": "静居寺"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A4473", "name": "河滨路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A3068", "name": "东大街"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2210", "name": "远东百货"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2218", "name": "总府路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A371", "name": "合江亭"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1429", "name": "牛王庙"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1842", "name": "水碾河"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2170", "name": "香槟广场"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1233", "name": "滨江路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1378", "name": "兰桂坊"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2136", "name": "万达广场"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A4270", "name": "红星路四段"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1484", "name": "牛市口"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A561", "name": "九眼桥"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2098", "name": "春熙路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A3434", "name": "东光小区"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A153", "name": "洪河大道"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2640", "name": "财富中心"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A3747", "name": "海椒市"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2012", "name": "书院街"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A2075", "name": "塔子山公园"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A4028", "name": "红星路"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1203", "name": "琉璃场"}, {"parent_id": "D1009", "children": [], "type": "A", "id": "A1080", "name": "锦江宾馆"}], "type": "D", "id": "D1009", "name": "锦江区"}, {"parent_id": "C375", "children": [ {"parent_id": "D1007", "children": [], "type": "A", "id": "A3745", "name": "凯德广场"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A2638", "name": "东郊记忆"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A4471", "name": "SM广场"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A3066", "name": "欢乐颂"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A1079", "name": "新华公园"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A4268", "name": "龙潭寺"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A370", "name": "双林路"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A1231", "name": "八里庄"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A560", "name": "万象城"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A2096", "name": "财富又一城"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A819", "name": "望平街"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A151", "name": "十里店"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A4026", "name": "龙湖三千集"}, {"parent_id": "D1007", "children": [], "type": "A", "id": "A3432", "name": "建设路"}], "type": "D", "id": "D1007", "name": "成华区"}], "type": "C", "id": "C375", "name": "成都"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C319", "name": "绵阳"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C318", "name": "德阳"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C315", "name": "自贡"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C317", "name": "泸州"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C316", "name": "攀枝花"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C332", "name": "阿坝"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C331", "name": "资阳"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C330", "name": "巴中"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C336", "name": "九寨沟"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C335", "name": "峨眉山"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C334", "name": "凉山"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C333", "name": "甘孜"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C320", "name": "广元"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C321", "name": "遂宁"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C322", "name": "内江"}, {"parent_id": "P16", "children": [ {"parent_id": "C323", "children": [], "type": "D", "id": "D945", "name": "沙湾区"}, {"parent_id": "C323", "children": [], "type": "D", "id": "D947", "name": "五通桥区"}, {"parent_id": "C323", "children": [ {"parent_id": "D946", "children": [], "type": "A", "id": "A1604", "name": "梅西百货"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A553", "name": "阳光广场"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A4460", "name": "房屋管理中心"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A4254", "name": "嘉兴路美食街"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1126", "name": "滨江路/王浩儿街"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A3407", "name": "翡翠国际"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1686", "name": "青果山"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A142", "name": "乐山中心汽车站"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1304", "name": "肖坝"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1517", "name": "市体育中心"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A3726", "name": "乐山大佛景区"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A2040", "name": "财富广场/沃尔玛"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1075", "name": "岷江二桥"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1426", "name": "长江市场"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A3038", "name": "乐山师范学院"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1840", "name": "竹公溪街"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A2604", "name": "沫若广场"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1374", "name": "通江"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A2134", "name": "高新技术区"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1482", "name": "乐山新广场"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A1199", "name": "电信广场"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A2010", "name": "人人乐百货"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A363", "name": "盘龙银座/西城国际"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A2073", "name": "张公桥"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A812", "name": "岷江一桥"}, {"parent_id": "D946", "children": [], "type": "A", "id": "A4009", "name": "联运站/莱佛士帝景"}], "type": "D", "id": "D946", "name": "市中区"}, {"parent_id": "C323", "children": [], "type": "D", "id": "D943", "name": "井研县"}, {"parent_id": "C323", "children": [], "type": "D", "id": "D944", "name": "犍为县"}, {"parent_id": "C323", "children": [], "type": "D", "id": "D942", "name": "夹江县"}, {"parent_id": "C323", "children": [], "type": "D", "id": "D940", "name": "峨边彝族自治县"}, {"parent_id": "C323", "children": [ {"parent_id": "D941", "children": [], "type": "A", "id": "A4253", "name": "峨山镇"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A1125", "name": "绥山镇"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A3406", "name": "象城"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A3725", "name": "报国寺风景区"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A2603", "name": "峨眉院子/峨秀湖度假区"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A3037", "name": "大佛禅院"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A2039", "name": "峨眉山旅游风景区"}, {"parent_id": "D941", "children": [], "type": "A", "id": "A4008", "name": "汽车站/火车站"}], "type": "D", "id": "D941", "name": "峨眉山市"}], "type": "C", "id": "C323", "name": "乐山"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C324", "name": "南充"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C325", "name": "眉山"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C326", "name": "宜宾"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C327", "name": "广安"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C328", "name": "达州"}, {"parent_id": "P16", "children": [], "type": "C", "id": "C329", "name": "雅安"}], "type": "P", "id": "P16", "name": "四川"}, {"parent_id": "N1", "children": [ {"parent_id": "P17", "children": [], "type": "C", "id": "C342", "name": "黔西南"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C343", "name": "毕节"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C340", "name": "安顺"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C341", "name": "铜仁"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C346", "name": "凯里"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C347", "name": "仁怀"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C344", "name": "黔东南"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C345", "name": "黔南"}, {"parent_id": "P17", "children": [ {"parent_id": "C339", "children": [ {"parent_id": "D958", "children": [], "type": "A", "id": "A556", "name": "海尔大道"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A146", "name": "外环路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A1307", "name": "解放路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A3047", "name": "大兴路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A4464", "name": "东欣大道"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A1078", "name": "新华路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A2614", "name": "碧云路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A4014", "name": "官井"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A4258", "name": "洗马路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A1377", "name": "合众路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A3414", "name": "白杨洞"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A815", "name": "中华路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A1145", "name": "丁字口"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A3731", "name": "沿江路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A2053", "name": "万里路"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A366", "name": "老城区"}, {"parent_id": "D958", "children": [], "type": "A", "id": "A1202", "name": "杨柳街"}], "type": "D", "id": "D958", "name": "红花岗区"}, {"parent_id": "C339", "children": [ {"parent_id": "D959", "children": [], "type": "A", "id": "A557", "name": "澳门路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A147", "name": "苏州路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A3048", "name": "香港路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A2615", "name": "上海路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A4015", "name": "深圳路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A4465", "name": "北海路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A4259", "name": "天津路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A3415", "name": "珠海路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A816", "name": "北京路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A3732", "name": "广州路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A2054", "name": "人民路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A367", "name": "南京路"}, {"parent_id": "D959", "children": [], "type": "A", "id": "A1146", "name": "宁波路"}], "type": "D", "id": "D959", "name": "汇川区"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D960", "name": "湄潭县"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D965", "name": "遵义县"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D964", "name": "正安县"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D963", "name": "桐梓县"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D962", "name": "绥阳县"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D961", "name": "仁怀市"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D956", "name": "赤水市"}, {"parent_id": "C339", "children": [], "type": "D", "id": "D957", "name": "凤冈县"}], "type": "C", "id": "C339", "name": "遵义"}, {"parent_id": "P17", "children": [], "type": "C", "id": "C338", "name": "六盘水"}, {"parent_id": "P17", "children": [ {"parent_id": "C337", "children": [ {"parent_id": "D948", "children": [], "type": "A", "id": "A2045", "name": "云峰大道"}, {"parent_id": "D948", "children": [], "type": "A", "id": "A1137", "name": "白云南路"}], "type": "D", "id": "D948", "name": "白云区"}, {"parent_id": "C337", "children": [ {"parent_id": "D953", "children": [], "type": "A", "id": "A3044", "name": "航天路"}, {"parent_id": "D953", "children": [], "type": "A", "id": "A2611", "name": "火炬大道"}, {"parent_id": "D953", "children": [], "type": "A", "id": "A3411", "name": "新添寨"}, {"parent_id": "D953", "children": [], "type": "A", "id": "A2050", "name": "东风镇"}, {"parent_id": "D953", "children": [], "type": "A", "id": "A1142", "name": "保利温泉新城"}], "type": "D", "id": "D953", "name": "乌当区"}, {"parent_id": "C337", "children": [ {"parent_id": "D954", "children": [], "type": "A", "id": "A2612", "name": "浦江路"}, {"parent_id": "D954", "children": [], "type": "A", "id": "A3045", "name": "黔江路"}, {"parent_id": "D954", "children": [], "type": "A", "id": "A3412", "name": "珠江路"}, {"parent_id": "D954", "children": [], "type": "A", "id": "A2051", "name": "海纳广场"}, {"parent_id": "D954", "children": [], "type": "A", "id": "A1143", "name": "黄河路"}], "type": "D", "id": "D954", "name": "小河区"}, {"parent_id": "C337", "children": [ {"parent_id": "D955", "children": [], "type": "A", "id": "A1605", "name": "市北路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A4257", "name": "富水北路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1687", "name": "三桥"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2330", "name": "紫林庵"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A145", "name": "公园路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1306", "name": "煤矿村"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A555", "name": "恒峰步行街"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2187", "name": "云岩广场"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2613", "name": "八角岩路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A3046", "name": "大十字"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2217", "name": "延安西路(老客车站)"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A4463", "name": "飞山街"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2273", "name": "友谊路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1077", "name": "花香村"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A4013", "name": "二桥"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1841", "name": "浣沙路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1376", "name": "喷水池"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2135", "name": "威清路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1428", "name": "黔灵公园"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2448", "name": "中山东路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1483", "name": "师大"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A3413", "name": "大营坡"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A814", "name": "红边门"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A3730", "name": "大营路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1518", "name": "陕西路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2011", "name": "头桥"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2209", "name": "盐务街"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2052", "name": "宝山北路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A365", "name": "贵开路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2074", "name": "文昌北路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1144", "name": "北京路"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A1201", "name": "六广门"}, {"parent_id": "D955", "children": [], "type": "A", "id": "A2169", "name": "小十字"}], "type": "D", "id": "D955", "name": "云岩区"}, {"parent_id": "C337", "children": [ {"parent_id": "D949", "children": [], "type": "A", "id": "A4461", "name": "学士路"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A4255", "name": "徐家冲"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A3408", "name": "农院"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A143", "name": "新区"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A3040", "name": "老牛马市"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A3727", "name": "平桥"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A2046", "name": "花溪公园"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A4010", "name": "十字街"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A1138", "name": "朝阳村"}, {"parent_id": "D949", "children": [], "type": "A", "id": "A2607", "name": "兰馨桂馥"}], "type": "D", "id": "D949", "name": "花溪区"}, {"parent_id": "C337", "children": [ {"parent_id": "D952", "children": [], "type": "A", "id": "A554", "name": "水口寺"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A144", "name": "甲秀楼"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A3043", "name": "鸿通城"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A3729", "name": "花果园"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A4462", "name": "箭道街"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A2049", "name": "都司路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1076", "name": "沙冲南路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A2610", "name": "大南门"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A4012", "name": "河滨公园"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1427", "name": "中华南路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A4256", "name": "花果园购物中心"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1375", "name": "遵义路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A3410", "name": "亨特City"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A364", "name": "沙冲中路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1141", "name": "博爱路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A813", "name": "市南路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1200", "name": "新华路"}, {"parent_id": "D952", "children": [], "type": "A", "id": "A1305", "name": "油榨街"}], "type": "D", "id": "D952", "name": "南明区"}, {"parent_id": "C337", "children": [ {"parent_id": "D950", "children": [], "type": "A", "id": "A3041", "name": "息烽县"}, {"parent_id": "D950", "children": [], "type": "A", "id": "A2047", "name": "清镇市"}, {"parent_id": "D950", "children": [], "type": "A", "id": "A1139", "name": "开阳县"}, {"parent_id": "D950", "children": [], "type": "A", "id": "A2608", "name": "修文县"}], "type": "D", "id": "D950", "name": "近郊"}, {"parent_id": "C337", "children": [ {"parent_id": "D951", "children": [], "type": "A", "id": "A3409", "name": "龙泉苑街"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A3042", "name": "金阳客车站"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A3728", "name": "世纪金源购物中心"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A2048", "name": "福州街"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A4011", "name": "金阳新区世纪城"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A2609", "name": "红街"}, {"parent_id": "D951", "children": [], "type": "A", "id": "A1140", "name": "诚信南路"}], "type": "D", "id": "D951", "name": "金阳新区"}], "type": "C", "id": "C337", "name": "贵阳"}], "type": "P", "id": "P17", "name": "贵州"}, {"parent_id": "N1", "children": [ {"parent_id": "P18", "children": [ {"parent_id": "C360", "children": [], "type": "D", "id": "D978", "name": "巍山彝族回族自治县"}, {"parent_id": "C360", "children": [ {"parent_id": "D979", "children": [], "type": "A", "id": "A1163", "name": "市中心"}, {"parent_id": "D979", "children": [], "type": "A", "id": "A2063", "name": "开发区"}, {"parent_id": "D979", "children": [], "type": "A", "id": "A2621", "name": "惠丰新城"}, {"parent_id": "D979", "children": [], "type": "A", "id": "A3054", "name": "北市区"}, {"parent_id": "D979", "children": [], "type": "A", "id": "A3421", "name": "感通寺"}], "type": "D", "id": "D979", "name": "下关"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D974", "name": "宾川县"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D975", "name": "洱源县"}, {"parent_id": "C360", "children": [ {"parent_id": "D976", "children": [], "type": "A", "id": "A1162", "name": "古城区"}], "type": "D", "id": "D976", "name": "古城区"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D977", "name": "南涧彝族自治县"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D982", "name": "云龙县"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D981", "name": "永平县"}, {"parent_id": "C360", "children": [], "type": "D", "id": "D980", "name": "祥云县"}], "type": "C", "id": "C360", "name": "大理"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C361", "name": "德宏"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C362", "name": "怒江"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C363", "name": "迪庆"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C355", "name": "临沧"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C354", "name": "普洱"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C357", "name": "红河"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C356", "name": "楚雄"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C351", "name": "保山"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C350", "name": "玉溪"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C353", "name": "丽江"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C352", "name": "昭通"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C359", "name": "西双版纳"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C358", "name": "文山"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C364", "name": "腾冲"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C365", "name": "香格里拉"}, {"parent_id": "P18", "children": [ {"parent_id": "C348", "children": [], "type": "D", "id": "D970", "name": "安宁市"}, {"parent_id": "C348", "children": [ {"parent_id": "D971", "children": [], "type": "A", "id": "A4261", "name": "世博园"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A148", "name": "新迎小区"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A1151", "name": "北市区"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A2618", "name": "白龙寺"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A4466", "name": "拓东路"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A4017", "name": "七彩俊园"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A3418", "name": "鼓楼片区"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A3735", "name": "金星小区"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A3051", "name": "凤凰新村"}, {"parent_id": "D971", "children": [], "type": "A", "id": "A2057", "name": "白塔路"}], "type": "D", "id": "D971", "name": "盘龙区"}, {"parent_id": "C348", "children": [ {"parent_id": "D972", "children": [], "type": "A", "id": "A4262", "name": "建设路"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A149", "name": "南屏片区"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A558", "name": "小西门"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A368", "name": "三市街"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A1152", "name": "北教场"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A2619", "name": "丰宁小区"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A4467", "name": "经开区"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A4018", "name": "金马碧鸡坊片区"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A3419", "name": "黄土坡"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A817", "name": "圆通山"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A3736", "name": "和谐世纪"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A3052", "name": "高新区"}, {"parent_id": "D972", "children": [], "type": "A", "id": "A2058", "name": "翠湖公园"}], "type": "D", "id": "D972", "name": "五华区"}, {"parent_id": "C348", "children": [ {"parent_id": "D973", "children": [], "type": "A", "id": "A4263", "name": "西山区政府"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A3420", "name": "大观楼"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A4019", "name": "十里长街"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A2620", "name": "大商汇"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A3737", "name": "南亚第一城"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A3053", "name": "滇池"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A1153", "name": "白马"}, {"parent_id": "D973", "children": [], "type": "A", "id": "A2059", "name": "滇池路"}], "type": "D", "id": "D973", "name": "西山区"}, {"parent_id": "C348", "children": [ {"parent_id": "D966", "children": [], "type": "A", "id": "A1148", "name": "呈贡大学城"}], "type": "D", "id": "D966", "name": "呈贡区"}, {"parent_id": "C348", "children": [ {"parent_id": "D969", "children": [], "type": "A", "id": "A1150", "name": "石林彝族自治县"}, {"parent_id": "D969", "children": [], "type": "A", "id": "A2617", "name": "禄劝彝族苗族自治县"}, {"parent_id": "D969", "children": [], "type": "A", "id": "A3417", "name": "寻甸回族彝族自治县"}, {"parent_id": "D969", "children": [], "type": "A", "id": "A3734", "name": "宜良县"}, {"parent_id": "D969", "children": [], "type": "A", "id": "A3050", "name": "嵩明县"}, {"parent_id": "D969", "children": [], "type": "A", "id": "A2056", "name": "富民县"}], "type": "D", "id": "D969", "name": "近郊"}, {"parent_id": "C348", "children": [ {"parent_id": "D968", "children": [], "type": "A", "id": "A4260", "name": "新亚洲体育城"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A3049", "name": "昆明站"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A2616", "name": "汇都国际"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A4016", "name": "万象城"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A3416", "name": "世纪城"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A3733", "name": "上东城"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A2055", "name": "官南大道"}, {"parent_id": "D968", "children": [], "type": "A", "id": "A1149", "name": "关上"}], "type": "D", "id": "D968", "name": "官渡区"}, {"parent_id": "C348", "children": [], "type": "D", "id": "D967", "name": "东川区"}], "type": "C", "id": "C348", "name": "昆明"}, {"parent_id": "P18", "children": [], "type": "C", "id": "C349", "name": "曲靖"}], "type": "P", "id": "P18", "name": "云南"}, {"parent_id": "N1", "children": [ {"parent_id": "P19", "children": [], "type": "C", "id": "C368", "name": "山南"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C369", "name": "日喀则"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C366", "name": "拉萨"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C367", "name": "昌都"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C372", "name": "林芝"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C371", "name": "阿里"}, {"parent_id": "P19", "children": [], "type": "C", "id": "C370", "name": "那曲"}], "type": "P", "id": "P19", "name": "西藏"}, {"parent_id": "N1", "children": [ {"parent_id": "P20", "children": [ {"parent_id": "C234", "children": [ {"parent_id": "D730", "children": [], "type": "A", "id": "A1937", "name": "电子城"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A4221", "name": "太白立交"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A3685", "name": "南二环东段"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A3972", "name": "曲江新区"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A2529", "name": "大雁塔"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A118", "name": "雁翔路"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A3359", "name": "南二环西段"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A948", "name": "长安路"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A2977", "name": "明德门"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A340", "name": "朱雀大街"}, {"parent_id": "D730", "children": [], "type": "A", "id": "A4433", "name": "小寨/南郊"}], "type": "D", "id": "D730", "name": "雁塔区"}, {"parent_id": "C234", "children": [ {"parent_id": "D174", "children": [], "type": "A", "id": "A415", "name": "东洲商场"}], "type": "D", "id": "D174", "name": "东洲区"}, {"parent_id": "C234", "children": [], "type": "D", "id": "D175", "name": "抚顺县"}, {"parent_id": "C234", "children": [ {"parent_id": "D176", "children": [], "type": "A", "id": "A416", "name": "紫龙商场"}], "type": "D", "id": "D176", "name": "高湾经济开发区"}, {"parent_id": "C234", "children": [], "type": "D", "id": "D177", "name": "李石经济开发区"}, {"parent_id": "C234", "children": [], "type": "D", "id": "D178", "name": "清原满族自治县"}, {"parent_id": "C234", "children": [ {"parent_id": "D179", "children": [], "type": "A", "id": "A2778", "name": "河东"}, {"parent_id": "D179", "children": [], "type": "A", "id": "A417", "name": "北站"}, {"parent_id": "D179", "children": [], "type": "A", "id": "A1638", "name": "新华乐购"}, {"parent_id": "D179", "children": [], "type": "A", "id": "A3186", "name": "雷锋体育场"}, {"parent_id": "D179", "children": [], "type": "A", "id": "A2302", "name": "将军"}], "type": "D", "id": "D179", "name": "顺城区"}, {"parent_id": "C234", "children": [], "type": "D", "id": "D729", "name": "阎良区"}, {"parent_id": "C234", "children": [ {"parent_id": "D728", "children": [], "type": "A", "id": "A1936", "name": "韩森寨"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A3684", "name": "民乐园"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A3971", "name": "新城广场"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A2528", "name": "互助立交"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A3358", "name": "金花路"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A947", "name": "胡家庙"}, {"parent_id": "D728", "children": [], "type": "A", "id": "A2976", "name": "解放路/火车站"}], "type": "D", "id": "D728", "name": "新城区"}, {"parent_id": "C234", "children": [ {"parent_id": "D725", "children": [], "type": "A", "id": "A1933", "name": "东三岔"}, {"parent_id": "D725", "children": [], "type": "A", "id": "A2525", "name": "华清池"}, {"parent_id": "D725", "children": [], "type": "A", "id": "A944", "name": "兵马俑"}, {"parent_id": "D725", "children": [], "type": "A", "id": "A2973", "name": "人民路/文化路"}], "type": "D", "id": "D725", "name": "临潼区"}, {"parent_id": "C234", "children": [ {"parent_id": "D724", "children": [], "type": "A", "id": "A1932", "name": "北关正街"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A3681", "name": "莲湖公园"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A338", "name": "西稍门"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A116", "name": "西大街"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A3355", "name": "汉城路沿线"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A943", "name": "北大街"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A4431", "name": "土门"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A4219", "name": "劳动公园"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A2524", "name": "丰庆公园"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A3969", "name": "劳动南路"}, {"parent_id": "D724", "children": [], "type": "A", "id": "A2972", "name": "广济街"}], "type": "D", "id": "D724", "name": "莲湖区"}, {"parent_id": "C234", "children": [ {"parent_id": "D727", "children": [], "type": "A", "id": "A1935", "name": "秦都"}, {"parent_id": "D727", "children": [], "type": "A", "id": "A3683", "name": "杨陵"}, {"parent_id": "D727", "children": [], "type": "A", "id": "A2527", "name": "渭城"}, {"parent_id": "D727", "children": [], "type": "A", "id": "A3357", "name": "兴平"}, {"parent_id": "D727", "children": [], "type": "A", "id": "A946", "name": "泾阳"}, {"parent_id": "D727", "children": [], "type": "A", "id": "A2975", "name": "武功"}], "type": "D", "id": "D727", "name": "咸阳市"}, {"parent_id": "C234", "children": [ {"parent_id": "D726", "children": [], "type": "A", "id": "A1934", "name": "城市运动公园"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A4220", "name": "赛高街区"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A3682", "name": "龙首村"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A3970", "name": "明光路"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A339", "name": "文景路"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A536", "name": "辛家庙"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A117", "name": "未央路"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A3356", "name": "红旗厂"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A945", "name": "北大学城"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A776", "name": "朱宏路"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A2526", "name": "大明宫万达"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A2974", "name": "大明宫"}, {"parent_id": "D726", "children": [], "type": "A", "id": "A4432", "name": "太华路"}], "type": "D", "id": "D726", "name": "未央区"}, {"parent_id": "C234", "children": [], "type": "D", "id": "D721", "name": "高陵县"}, {"parent_id": "C234", "children": [ {"parent_id": "D720", "children": [], "type": "A", "id": "A2521", "name": "秦岭沿线"}, {"parent_id": "D720", "children": [], "type": "A", "id": "A940", "name": "郭杜"}, {"parent_id": "D720", "children": [], "type": "A", "id": "A2970", "name": "韦曲"}, {"parent_id": "D720", "children": [], "type": "A", "id": "A1929", "name": "南大学城"}], "type": "D", "id": "D720", "name": "长安区"}, {"parent_id": "C234", "children": [ {"parent_id": "D723", "children": [], "type": "A", "id": "A1931", "name": "蓝田县"}, {"parent_id": "D723", "children": [], "type": "A", "id": "A2523", "name": "周至县"}, {"parent_id": "D723", "children": [], "type": "A", "id": "A942", "name": "户县"}], "type": "D", "id": "D723", "name": "近郊"}, {"parent_id": "C234", "children": [ {"parent_id": "D722", "children": [], "type": "A", "id": "A1930", "name": "光华路"}, {"parent_id": "D722", "children": [], "type": "A", "id": "A3354", "name": "唐延路"}, {"parent_id": "D722", "children": [], "type": "A", "id": "A941", "name": "高新路"}, {"parent_id": "D722", "children": [], "type": "A", "id": "A2522", "name": "科技路沿线"}, {"parent_id": "D722", "children": [], "type": "A", "id": "A2971", "name": "科技路西口"}], "type": "D", "id": "D722", "name": "高新区"}, {"parent_id": "C234", "children": [ {"parent_id": "D718", "children": [], "type": "A", "id": "A2968", "name": "十里铺"}, {"parent_id": "D718", "children": [], "type": "A", "id": "A1927", "name": "浐灞生态区"}, {"parent_id": "D718", "children": [], "type": "A", "id": "A938", "name": "白鹿原"}, {"parent_id": "D718", "children": [], "type": "A", "id": "A2519", "name": "纺织城"}], "type": "D", "id": "D718", "name": "灞桥区"}, {"parent_id": "C234", "children": [ {"parent_id": "D719", "children": [], "type": "A", "id": "A535", "name": "西北大/西工大"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A3680", "name": "立丰国际"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A2969", "name": "东大街"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A1039", "name": "钟楼/鼓楼"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A337", "name": "西安交大/东郊"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A2520", "name": "含光路"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A3353", "name": "李家村"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A115", "name": "太乙路"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A775", "name": "小雁塔"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A4218", "name": "南大街"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A3968", "name": "南稍门"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A1928", "name": "和平门/建国门"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A4430", "name": "省体育场"}, {"parent_id": "D719", "children": [], "type": "A", "id": "A939", "name": "东关正街"}], "type": "D", "id": "D719", "name": "碑林区"}, {"parent_id": "C234", "children": [ {"parent_id": "D181", "children": [], "type": "A", "id": "A2779", "name": "道街"}, {"parent_id": "D181", "children": [], "type": "A", "id": "A1640", "name": "万达广场"}, {"parent_id": "D181", "children": [], "type": "A", "id": "A419", "name": "南站"}, {"parent_id": "D181", "children": [], "type": "A", "id": "A3187", "name": "步行街"}, {"parent_id": "D181", "children": [], "type": "A", "id": "A2304", "name": "浙商/天朗"}], "type": "D", "id": "D181", "name": "新抚区"}, {"parent_id": "C234", "children": [ {"parent_id": "D180", "children": [], "type": "A", "id": "A418", "name": "望花乐购"}, {"parent_id": "D180", "children": [], "type": "A", "id": "A1639", "name": "丹东路"}, {"parent_id": "D180", "children": [], "type": "A", "id": "A2303", "name": "雷锋路"}], "type": "D", "id": "D180", "name": "望花区"}], "type": "C", "id": "C234", "name": "西安"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C379", "name": "渭南"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C378", "name": "咸阳"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C377", "name": "宝鸡"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C376", "name": "铜川"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C383", "name": "安康"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C384", "name": "商洛"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C382", "name": "榆林"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C380", "name": "延安"}, {"parent_id": "P20", "children": [], "type": "C", "id": "C381", "name": "汉中"}], "type": "P", "id": "P20", "name": "陕西"}, {"parent_id": "N1", "children": [ {"parent_id": "P21", "children": [], "type": "C", "id": "C390", "name": "张掖"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C395", "name": "陇南"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C394", "name": "定西"}, {"parent_id": "P21", "children": [ {"parent_id": "C180", "children": [ {"parent_id": "D518", "children": [], "type": "A", "id": "A833", "name": "兰州新区"}], "type": "D", "id": "D518", "name": "永登县"}, {"parent_id": "C180", "children": [], "type": "D", "id": "D519", "name": "榆中县"}, {"parent_id": "C180", "children": [ {"parent_id": "D512", "children": [], "type": "A", "id": "A1957", "name": "农民巷"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2121", "name": "双城门"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2737", "name": "中山林"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A514", "name": "甘南路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2675", "name": "新港城"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2653", "name": "西关十字"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2184", "name": "秦安路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A829", "name": "北滨河路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2622", "name": "五泉山"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1577", "name": "民主西路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2214", "name": "滩尖子"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2907", "name": "草场街"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2454", "name": "北面滩"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A988", "name": "广武门"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1803", "name": "南关十字"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A4182", "name": "大润发"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2256", "name": "通渭路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2068", "name": "平凉路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1279", "name": "静宁路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2541", "name": "武都路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A3633", "name": "东岗东路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1177", "name": "火车站"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2159", "name": "铁路局"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2700", "name": "雁滩路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2702", "name": "张掖路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A4399", "name": "段家滩"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1353", "name": "酒泉路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A89", "name": "大众巷"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2688", "name": "永昌路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1415", "name": "九州开发区"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1677", "name": "麦积山路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2328", "name": "体育公园"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A742", "name": "皋兰路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2420", "name": "王府井"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A296", "name": "二热"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1508", "name": "兰州一中"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A2206", "name": "天庆嘉园"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1473", "name": "兰州大学"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A3302", "name": "东方红广场"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A1851", "name": "白银路"}, {"parent_id": "D512", "children": [], "type": "A", "id": "A3925", "name": "定西路"}], "type": "D", "id": "D512", "name": "城关区"}, {"parent_id": "C180", "children": [], "type": "D", "id": "D513", "name": "皋兰县"}, {"parent_id": "C180", "children": [ {"parent_id": "D516", "children": [], "type": "A", "id": "A2909", "name": "南滨河路"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A2456", "name": "兰州西站"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A3635", "name": "小西湖"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A4184", "name": "倚能"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A831", "name": "龚家湾"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A3304", "name": "万辉国际广场"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A1853", "name": "金港城"}, {"parent_id": "D516", "children": [], "type": "A", "id": "A3927", "name": "秀川"}], "type": "D", "id": "D516", "name": "七里河区"}, {"parent_id": "C180", "children": [ {"parent_id": "D517", "children": [], "type": "A", "id": "A4401", "name": "玉门街"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A2457", "name": "兰化医院"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A3305", "name": "天鹅湖"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A4185", "name": "西固人家"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A3636", "name": "西固城"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A3928", "name": "西固公园"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A832", "name": "北站"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A2910", "name": "十二街区"}, {"parent_id": "D517", "children": [], "type": "A", "id": "A1854", "name": "兰炼医院"}], "type": "D", "id": "D517", "name": "西固区"}, {"parent_id": "C180", "children": [], "type": "D", "id": "D514", "name": "红古区"}, {"parent_id": "C180", "children": [ {"parent_id": "D515", "children": [], "type": "A", "id": "A4400", "name": "桃海"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A90", "name": "西北师大"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A2908", "name": "交通大学"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A2455", "name": "金牛街"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A4183", "name": "实创现代城"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A3634", "name": "培黎广场"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A3926", "name": "十里店"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A830", "name": "安宁庭院"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A3303", "name": "安宁西路"}, {"parent_id": "D515", "children": [], "type": "A", "id": "A1852", "name": "费家营十字"}], "type": "D", "id": "D515", "name": "安宁区"}], "type": "C", "id": "C180", "name": "兰州"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C385", "name": "嘉峪关"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C388", "name": "天水"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C389", "name": "武威"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C386", "name": "金昌"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C387", "name": "白银"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C391", "name": "平凉"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C393", "name": "庆阳"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C392", "name": "酒泉"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C397", "name": "甘南"}, {"parent_id": "P21", "children": [], "type": "C", "id": "C396", "name": "临夏"}], "type": "P", "id": "P21", "name": "甘肃"}, {"parent_id": "N1", "children": [ {"parent_id": "P22", "children": [], "type": "C", "id": "C401", "name": "黄南"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C400", "name": "海北"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C403", "name": "果洛"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C402", "name": "海南州"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C405", "name": "海西"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C404", "name": "玉树"}, {"parent_id": "P22", "children": [], "type": "C", "id": "C399", "name": "海东"}, {"parent_id": "P22", "children": [ {"parent_id": "C398", "children": [ {"parent_id": "D1020", "children": [], "type": "A", "id": "A1257", "name": "小桥"}, {"parent_id": "D1020", "children": [], "type": "A", "id": "A2112", "name": "朝阳"}, {"parent_id": "D1020", "children": [], "type": "A", "id": "A2649", "name": "西郊"}], "type": "D", "id": "D1020", "name": "城北区"}, {"parent_id": "C398", "children": [ {"parent_id": "D1021", "children": [], "type": "A", "id": "A2650", "name": "国际村"}, {"parent_id": "D1021", "children": [], "type": "A", "id": "A1258", "name": "湟光"}, {"parent_id": "D1021", "children": [], "type": "A", "id": "A2113", "name": "五一路"}], "type": "D", "id": "D1021", "name": "城东区"}, {"parent_id": "C398", "children": [ {"parent_id": "D1022", "children": [], "type": "A", "id": "A3442", "name": "西关大街"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A2651", "name": "胜利路"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A4477", "name": "乐尚都市"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A3754", "name": "麒麟湾"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A1259", "name": "师大"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A4035", "name": "长江路"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A4276", "name": "海湖路"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A2114", "name": "力盟步行街"}, {"parent_id": "D1022", "children": [], "type": "A", "id": "A3077", "name": "虎台"}], "type": "D", "id": "D1022", "name": "城西区"}, {"parent_id": "C398", "children": [ {"parent_id": "D1023", "children": [], "type": "A", "id": "A3443", "name": "南小街"}, {"parent_id": "D1023", "children": [], "type": "A", "id": "A2652", "name": "七一路"}, {"parent_id": "D1023", "children": [], "type": "A", "id": "A2115", "name": "大十字"}, {"parent_id": "D1023", "children": [], "type": "A", "id": "A3755", "name": "夏都大街"}, {"parent_id": "D1023", "children": [], "type": "A", "id": "A3078", "name": "东台"}, {"parent_id": "D1023", "children": [], "type": "A", "id": "A1260", "name": "西门"}], "type": "D", "id": "D1023", "name": "城中区"}, {"parent_id": "C398", "children": [], "type": "D", "id": "D1024", "name": "大通回族土族自治县"}, {"parent_id": "C398", "children": [], "type": "D", "id": "D1025", "name": "湟中县"}], "type": "C", "id": "C398", "name": "西宁"}], "type": "P", "id": "P22", "name": "青海"}, {"parent_id": "N1", "children": [ {"parent_id": "P24", "children": [], "type": "C", "id": "C409", "name": "固原"}, {"parent_id": "P24", "children": [], "type": "C", "id": "C408", "name": "吴忠"}, {"parent_id": "P24", "children": [], "type": "C", "id": "C410", "name": "中卫"}, {"parent_id": "P24", "children": [], "type": "C", "id": "C407", "name": "石嘴山"}, {"parent_id": "P24", "children": [ {"parent_id": "C406", "children": [], "type": "D", "id": "D1031", "name": "永宁县"}, {"parent_id": "C406", "children": [ {"parent_id": "D1030", "children": [], "type": "A", "id": "A2126", "name": "同心路"}, {"parent_id": "D1030", "children": [], "type": "A", "id": "A1291", "name": "宁夏大学"}], "type": "D", "id": "D1030", "name": "西夏区"}, {"parent_id": "C406", "children": [], "type": "D", "id": "D1026", "name": "贺兰县"}, {"parent_id": "C406", "children": [ {"parent_id": "D1027", "children": [], "type": "A", "id": "A2124", "name": "民生花园/蓝山名邸"}, {"parent_id": "D1027", "children": [], "type": "A", "id": "A3444", "name": "悦海新天地"}, {"parent_id": "D1027", "children": [], "type": "A", "id": "A2654", "name": "世纪金花购物中心"}, {"parent_id": "D1027", "children": [], "type": "A", "id": "A1289", "name": "万达"}, {"parent_id": "D1027", "children": [], "type": "A", "id": "A3079", "name": "新城"}, {"parent_id": "D1027", "children": [], "type": "A", "id": "A3756", "name": "良田附近"}], "type": "D", "id": "D1027", "name": "金凤区"}, {"parent_id": "C406", "children": [], "type": "D", "id": "D1028", "name": "灵武市"}, {"parent_id": "C406", "children": [ {"parent_id": "D1029", "children": [], "type": "A", "id": "A2125", "name": "鼓楼"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A3445", "name": "光明广场"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A1106", "name": "东门附近"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A2655", "name": "老大楼"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A4478", "name": "湖滨街"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A1290", "name": "新华"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A3080", "name": "南门广场"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A375", "name": "新一中"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A4036", "name": "唐徕"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A4277", "name": "绿地21城"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A565", "name": "新二中"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A3757", "name": "香渔王子"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A157", "name": "建发现代城"}, {"parent_id": "D1029", "children": [], "type": "A", "id": "A834", "name": "北门金三角"}], "type": "D", "id": "D1029", "name": "兴庆区"}], "type": "C", "id": "C406", "name": "银川"}], "type": "P", "id": "P24", "name": "宁夏"}, {"parent_id": "N1", "children": [ {"parent_id": "P25", "children": [], "type": "C", "id": "C423", "name": "塔城"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C422", "name": "伊犁"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C421", "name": "和田"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C420", "name": "喀什"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C425", "name": "石河子"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C424", "name": "阿勒泰"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C415", "name": "昌吉"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C412", "name": "克拉玛依"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C416", "name": "博尔塔拉"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C417", "name": "巴州"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C414", "name": "哈密"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C413", "name": "吐鲁番"}, {"parent_id": "P25", "children": [ {"parent_id": "C411", "children": [ {"parent_id": "D1036", "children": [], "type": "A", "id": "A1303", "name": "北京南路"}, {"parent_id": "D1036", "children": [], "type": "A", "id": "A3760", "name": "鲤鱼山路"}, {"parent_id": "D1036", "children": [], "type": "A", "id": "A3448", "name": "昆仑路"}, {"parent_id": "D1036", "children": [], "type": "A", "id": "A3083", "name": "喀什西路"}, {"parent_id": "D1036", "children": [], "type": "A", "id": "A2133", "name": "河南西路"}, {"parent_id": "D1036", "children": [], "type": "A", "id": "A2660", "name": "河南东路"}], "type": "D", "id": "D1036", "name": "新市区"}, {"parent_id": "C411", "children": [ {"parent_id": "D1035", "children": [], "type": "A", "id": "A1302", "name": "东风路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A4480", "name": "中山路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A2659", "name": "红旗路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A3447", "name": "民主路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A3082", "name": "建设路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A4038", "name": "文化路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A2132", "name": "光明路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A4279", "name": "新华北路"}, {"parent_id": "D1035", "children": [], "type": "A", "id": "A3759", "name": "五星南路"}], "type": "D", "id": "D1035", "name": "天山区"}, {"parent_id": "C411", "children": [ {"parent_id": "D1034", "children": [], "type": "A", "id": "A1301", "name": "南湖路"}, {"parent_id": "D1034", "children": [], "type": "A", "id": "A2658", "name": "新民路"}, {"parent_id": "D1034", "children": [], "type": "A", "id": "A2131", "name": "苏州路"}], "type": "D", "id": "D1034", "name": "水磨沟区"}, {"parent_id": "C411", "children": [ {"parent_id": "D1033", "children": [], "type": "A", "id": "A3446", "name": "克拉玛依西路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A1300", "name": "阿勒泰路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A2657", "name": "长江路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A4479", "name": "新医路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A3081", "name": "黄河路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A376", "name": "扬子江路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A4037", "name": "奇台路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A2130", "name": "巴州路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A4278", "name": "西北路"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A3758", "name": "揽秀园西街"}, {"parent_id": "D1033", "children": [], "type": "A", "id": "A158", "name": "友好北路"}], "type": "D", "id": "D1033", "name": "沙依巴克区"}, {"parent_id": "C411", "children": [ {"parent_id": "D1032", "children": [], "type": "A", "id": "A2129", "name": "头屯河区"}, {"parent_id": "D1032", "children": [], "type": "A", "id": "A2656", "name": "乌鲁木齐县"}, {"parent_id": "D1032", "children": [], "type": "A", "id": "A1299", "name": "米东区"}], "type": "D", "id": "D1032", "name": "近郊"}], "type": "C", "id": "C411", "name": "乌鲁木齐"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C418", "name": "阿克苏"}, {"parent_id": "P25", "children": [], "type": "C", "id": "C419", "name": "克州"}], "type": "P", "id": "P25", "name": "新疆"}, {"parent_id": "N1", "children": [ {"parent_id": "P28", "children": [], "type": "C", "id": "C432", "name": "澳门"}], "type": "P", "id": "P28", "name": "澳门"}, {"parent_id": "N1", "children": [ {"parent_id": "P26", "children": [], "type": "C", "id": "C428", "name": "台北"}], "type": "P", "id": "P26", "name": "台湾"}, {"parent_id": "N1", "children": [ {"parent_id": "P27", "children": [], "type": "C", "id": "C431", "name": "香港"}], "type": "P", "id": "P27", "name": "香港"}];
PypiClean
/Flask-PluginEngine-0.4.1.tar.gz/Flask-PluginEngine-0.4.1/flask_pluginengine/util.py
import sys from contextlib import contextmanager from functools import wraps from types import FunctionType from flask import current_app from jinja2.utils import internalcode from .globals import _plugin_ctx_stack def get_state(app): """Get the application-specific plugine engine data.""" assert 'pluginengine' in app.extensions, \ 'The pluginengine extension was not registered to the current application. ' \ 'Please make sure to call init_app() first.' return app.extensions['pluginengine'] def resolve_dependencies(plugins): """Resolve dependencies between plugins and sort them accordingly. This function guarantees that a plugin is never loaded before any plugin it depends on. If multiple plugins are ready to be loaded, the order in which they are loaded is undefined and should not be relied upon. If you want a certain order, add a (soft) dependency! :param plugins: dict mapping plugin names to plugin classes """ plugins_deps = {name: (cls.required_plugins, cls.used_plugins) for name, cls in plugins.items()} resolved_deps = set() while plugins_deps: # Get plugins with both hard and soft dependencies being met ready = {cls for cls, deps in plugins_deps.items() if all(d <= resolved_deps for d in deps)} if not ready: # Otherwise check for plugins with all hard dependencies being met ready = {cls for cls, deps in plugins_deps.items() if deps[0] <= resolved_deps} if not ready: # Either a circular dependency or a dependency that's not loaded raise Exception('Could not resolve dependencies between plugins') resolved_deps |= ready for name in ready: yield name, plugins[name] del plugins_deps[name] @contextmanager def plugin_context(plugin): """Enter a plugin context if a plugin is provided, otherwise clear it Useful for code which sometimes needs a plugin context, e.g. because it may be used in both the core and in a plugin. """ if plugin is None: # Explicitly push a None plugin to disable an existing plugin context _plugin_ctx_stack.push(None) try: yield finally: assert _plugin_ctx_stack.pop() is None, 'Popped wrong plugin' else: with plugin.instance.plugin_context(): yield class equality_preserving_decorator: """Decorator which is considered equal with the original function""" def __init__(self, orig_func): self.orig_func = orig_func self.wrapper = None def __call__(self, *args, **kwargs): if self.wrapper is None: assert len(args) == 1 assert not kwargs self.wrapper = args[0] return self else: return self.wrapper(*args, **kwargs) def __eq__(self, other): if isinstance(other, FunctionType): return self.orig_func == other else: return self.orig_func == other.orig_func def __ne__(self, other): return not (self == other) def __hash__(self): return hash(self.orig_func) def __repr__(self): return f'<decorated {self.orig_func!r}>' def plugin_name_from_template_name(name): if not name: return None return name.split(':', 1)[0] if ':' in name else None def wrap_iterator_in_plugin_context(plugin, gen_or_func): """Run an iterator inside a plugin context""" # Heavily based on Flask's stream_with_context try: gen = iter(gen_or_func) except TypeError: @equality_preserving_decorator(gen_or_func) def decorator(*args, **kwargs): return wrap_iterator_in_plugin_context(plugin, gen_or_func(*args, **kwargs)) return decorator if plugin is not None and isinstance(plugin, str): plugin = get_state(current_app).plugin_engine.get_plugin(plugin) @internalcode def generator(): with plugin_context(plugin): # Dummy sentinel. Has to be inside the context block or we're # not actually keeping the context around. yield None yield from gen # The trick is to start the generator. Then the code execution runs until # the first dummy None is yielded at which point the context was already # pushed. This item is discarded. Then when the iteration continues the # real generator is executed. wrapped_g = generator() next(wrapped_g) return wrapped_g def wrap_macro_in_plugin_context(plugin, macro): """Wrap a macro inside a plugin context""" func = macro._func @internalcode @wraps(func) def decorator(*args, **kwargs): with plugin_context(plugin): return func(*args, **kwargs) macro._func = decorator class classproperty(property): def __get__(self, obj, type=None): return self.fget.__get__(None, type)() def make_hashable(obj): """Make an object containing dicts and lists hashable.""" if isinstance(obj, list): return tuple(obj) elif isinstance(obj, dict): return frozenset((k, make_hashable(v)) for k, v in obj.items()) return obj # http://wiki.python.org/moin/PythonDecoratorLibrary#Alternate_memoize_as_nested_functions def memoize(obj): cache = {} @wraps(obj) def memoizer(*args, **kwargs): key = (make_hashable(args), make_hashable(kwargs)) if key not in cache: cache[key] = obj(*args, **kwargs) return cache[key] return memoizer @memoize def wrap_in_plugin_context(plugin, func): assert plugin is not None @wraps(func) def wrapped(*args, **kwargs): with plugin.plugin_context(): return func(*args, **kwargs) return wrapped def with_plugin_context(plugin): """Decorator to ensure a function is always called in the given plugin context. :param plugin: Plugin instance """ def decorator(f): return wrap_in_plugin_context(plugin, f) return decorator def trim_docstring(docstring): """Trim a docstring based on the algorithm in PEP 257 http://legacy.python.org/dev/peps/pep-0257/#handling-docstring-indentation """ if not docstring: return '' # Convert tabs to spaces (following the normal Python rules) # and split into a list of lines: lines = docstring.expandtabs().splitlines() # Determine minimum indentation (first line doesn't count): indent = sys.maxsize for line in lines[1:]: stripped = line.lstrip() if stripped: indent = min(indent, len(line) - len(stripped)) # Remove indentation (first line is special): trimmed = [lines[0].strip()] if indent < sys.maxsize: for line in lines[1:]: trimmed.append(line[indent:].rstrip()) # Strip off trailing and leading blank lines: while trimmed and not trimmed[-1]: trimmed.pop() while trimmed and not trimmed[0]: trimmed.pop(0) # Return a single string: return '\n'.join(trimmed)
PypiClean
/Flask_AdminLTE3-1.0.9-py3-none-any.whl/flask_adminlte3/static/plugins/moment/locale/hr.js
;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, (function (moment) { 'use strict'; //! moment.js locale configuration function translate(number, withoutSuffix, key) { var result = number + ' '; switch (key) { case 'ss': if (number === 1) { result += 'sekunda'; } else if (number === 2 || number === 3 || number === 4) { result += 'sekunde'; } else { result += 'sekundi'; } return result; case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } var hr = moment.defineLocale('hr', { months: { format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split( '_' ), standalone: 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split( '_' ), }, monthsShort: 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split( '_' ), monthsParseExact: true, weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split( '_' ), weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'), weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'H:mm', LTS: 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'Do MMMM YYYY', LLL: 'Do MMMM YYYY H:mm', LLLL: 'dddd, Do MMMM YYYY H:mm', }, calendar: { sameDay: '[danas u] LT', nextDay: '[sutra u] LT', nextWeek: function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay: '[jučer u] LT', lastWeek: function () { switch (this.day()) { case 0: return '[prošlu] [nedjelju] [u] LT'; case 3: return '[prošlu] [srijedu] [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse: 'L', }, relativeTime: { future: 'za %s', past: 'prije %s', s: 'par sekundi', ss: translate, m: translate, mm: translate, h: translate, hh: translate, d: 'dan', dd: translate, M: 'mjesec', MM: translate, y: 'godinu', yy: translate, }, dayOfMonthOrdinalParse: /\d{1,2}\./, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 7, // The week that contains Jan 7th is the first week of the year. }, }); return hr; })));
PypiClean
/NEURON_gpu-8.2.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl/neuron/rxd/geometry.py
import warnings import numpy from neuron import h, nrn from .rxdException import RxDException try: from neuron.rxd import geometry3d has_geometry3d = True except ImportError: has_geometry3d = False class RxDGeometry: def volumes1d(self, sec): raise RxDException("volume1d unimplemented") def surface_areas1d(self, sec): raise RxDException("surface_areas1d unimplemented") def neighbor_areas1d(self, sec): raise RxDException("neighbor_areas1d unimplemented") def is_volume(self): raise RxDException("is_volume unimplemented") def is_area(self): raise RxDException("is_area unimplemented") def __call__(self): """calling returns self to allow for rxd.inside or rxd.inside()""" return self def _volumes1d(sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) for i in range(sec.n3d())] vols = numpy.zeros(sec.nseg) dx = sec.L / sec.nseg for iseg in range(sec.nseg): # get a list of all pts in the segment, including end points lo = iseg * dx hi = (iseg + 1) * dx pts = [lo] + [x for x in arc3d if lo < x < hi] + [hi] diams = numpy.interp(pts, arc3d, diam3d) # sum the volume of the constituent frusta volume = 0 for i in range(len(pts) - 1): diam0, diam1 = diams[i : i + 2] pt0, pt1 = pts[i : i + 2] volume += ( numpy.pi * (pt1 - pt0) / 12.0 * (diam0**2 + diam0 * diam1 + diam1**2) ) vols[iseg] = volume return vols def _make_surfacearea1d_function(scale, diam_scale=1.0): def result(sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) * diam_scale for i in range(sec.n3d())] sas = numpy.zeros(sec.nseg) dx = sec.L / sec.nseg for iseg in range(sec.nseg): # get a list of all pts in the segment, including end points lo = iseg * dx hi = (iseg + 1) * dx pts = [lo] + [x for x in arc3d if lo < x < hi] + [hi] diams = numpy.interp(pts, arc3d, diam3d) # sum the surface areas of the constituent frusta sa = 0 for i in range(len(pts) - 1): diam0, diam1 = diams[i : i + 2] pt0, pt1 = pts[i : i + 2] sa += ( scale * 0.5 * (diam0 + diam1) * numpy.sqrt(0.25 * (diam0 - diam1) ** 2 + (pt1 - pt0) ** 2) ) sas[iseg] = sa return sas return result def _make_perimeter_function(scale, diam_scale=1.0): def result(sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) * diam_scale for i in range(sec.n3d())] area_pos = numpy.linspace(0, sec.L, sec.nseg + 1) diams = numpy.interp(area_pos, arc3d, diam3d) return scale * diams return result _surface_areas1d = _make_surfacearea1d_function(numpy.pi) _perimeter1d = _make_perimeter_function(numpy.pi) def _neighbor_areas1d(sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) for i in range(sec.n3d())] area_pos = numpy.linspace(0, sec.L, sec.nseg + 1) diams = numpy.interp(area_pos, arc3d, diam3d) return numpy.pi * 0.25 * diams**2 def constant_function_per_length(value): return lambda sec: [value * sec.L / sec.nseg for i in range(sec.nseg)] def constant_everywhere_1d(value): return lambda sec: value * numpy.ones(sec.nseg) def constant_everywhere_plus_one_1d(value): return lambda sec: value * numpy.ones(sec.nseg + 1) def constant_function(value): return lambda *args, **kwargs: value def scale_by_constant(scale, f): return lambda *args, **kwargs: scale * f(*args, **kwargs) _always_true = constant_function(True) _always_false = constant_function(False) _always_0 = constant_function(0) inside = RxDGeometry() if has_geometry3d: inside.volumes3d = geometry3d.voxelize2 # neighbor_area_fraction can be a constant or a function inside.neighbor_area_fraction = 1 inside.volumes1d = _volumes1d inside.surface_areas1d = _surface_areas1d inside.neighbor_areas1d = _neighbor_areas1d inside.is_volume = _always_true inside.is_area = _always_false inside.__repr__ = constant_function("inside") # TODO: make a version that allows arbitrary shells? membrane = RxDGeometry() membrane.volumes1d = _surface_areas1d membrane.surface_areas1d = _always_0 membrane.neighbor_areas1d = _perimeter1d membrane.is_volume = _always_false membrane.is_area = _always_true membrane.__repr__ = constant_function("membrane") class Enum: """a silly way of creating unique identifiers without using/allowing/requiring magic constants""" pass _lo_hi_shell = Enum() class DistributedBoundary(RxDGeometry): """Boundary that scales with area. DistributedBoundary(area_per_vol, perim_per_area=0) area_per_vol is the area of the boundary as a function of the volume containing it. e.g. g = DistributedBoundary(2) defines a geometry with 2 um^2 of area per every um^3 of volume. perim_per_area is the perimeter (in um) per 1 um^2 cross section of the volume. For use in reaction-diffusion problems, it may be safely omitted if and only if no species in the corresponding region diffuses. This is often useful for separating FractionalVolume objects. It is assumed that the area is always strictly on the interior. """ def __init__(self, area_per_vol, perim_per_area=0): self._area_per_vol = area_per_vol self._perim_per_area = 0 self.surface_areas1d = _always_0 self.neighbor_areas1d = scale_by_constant(perim_per_area, _neighbor_areas1d) self.volumes1d = scale_by_constant(area_per_vol, _volumes1d) self.is_volume = _always_false self.is_area = _always_true @property def neighbor_area_fraction(self): # TODO: validate that this gives consistent results between 1D and 3D return self._perim_per_area def volumes3d( self, source, dx=0.25, xlo=None, xhi=None, ylo=None, yhi=None, zlo=None, zhi=None, n_soma_step=100, ): # mesh, surface_areas, volumes, triangles = geometry3d.voxelize2(source, dx=dx) # volumes._values *= self._area_per_vol # volume on 2D boundaries is actually the area; the amount of space for holding things # surface_areas._values *= 0 # return mesh, surface_areas, volumes, triangles internal_voxels, surface_voxels, mesh_grid = geometry3d.voxelize2(source, dx=dx) area_per_vol = self._area_per_vol for key in internal_voxels: internal_voxels[key][0] *= area_per_vol for key in surface_voxels: surface_voxels[key][0] *= area_per_vol return internal_voxels, surface_voxels, mesh_grid def __repr__(self): if self._perim_per_area == 0: return "DistributedBoundary(%g)" % (self._area_per_vol) else: return "DistributedBoundary(%g, perim_per_area=%g)" % ( self._area_per_vol, self._perim_per_area, ) class FractionalVolume(RxDGeometry): def __init__( self, volume_fraction=1, surface_fraction=0, neighbor_areas_fraction=None ): if neighbor_areas_fraction is None: neighbor_areas_fraction = volume_fraction if surface_fraction == 0: self.surface_areas1d = _always_0 elif surface_fraction == 1: self.surface_areas1d = _surface_areas1d else: self.surface_areas1d = scale_by_constant(surface_fraction, _surface_areas1d) # TODO: add the if statement so not scaling if 0 or 1 self.neighbor_areas1d = scale_by_constant( neighbor_areas_fraction, _neighbor_areas1d ) self.volumes1d = scale_by_constant(volume_fraction, _volumes1d) self.is_volume = _always_true self.is_area = _always_false self._volume_fraction = volume_fraction self._surface_fraction = surface_fraction self._neighbor_areas_fraction = neighbor_areas_fraction # TODO: does the else case ever make sense? self.neighbor_area_fraction = ( volume_fraction if neighbor_areas_fraction is None else neighbor_areas_fraction ) def volumes3d( self, source, dx=0.25, xlo=None, xhi=None, ylo=None, yhi=None, zlo=None, zhi=None, n_soma_step=100, ): # mesh, surface_areas, volumes, triangles = geometry3d.voxelize2(source, dx=dx) # surface_areas._values *= self._surface_fraction # volumes._values *= self._volume_fraction # return mesh, surface_areas, volumes, triangles internal_voxels, surface_voxels, mesh_grid = geometry3d.voxelize2(source, dx=dx) volume_fraction = self._volume_fraction for key in internal_voxels: internal_voxels[key][0] *= volume_fraction for key in surface_voxels: surface_voxels[key][0] *= volume_fraction return internal_voxels, surface_voxels, mesh_grid def __repr__(self): return ( "FractionalVolume(volume_fraction=%r, surface_fraction=%r, neighbor_areas_fraction=%r)" % ( self._volume_fraction, self._surface_fraction, self._neighbor_areas_fraction, ) ) # TODO: eliminate this class and replace with FixedCrossSection? class ConstantVolume(RxDGeometry): # TODO: do we want different default neighbor_area? def __init__(self, volume=1, surface_area=0, neighbor_area=1): """volume, surface_area per unit length""" self.volumes1d = constant_function_per_length(volume) self.surface_areas1d = constant_function_per_length(surface_area) self.is_volume = _always_true self.is_area = _always_false self.neighbor_areas1d = constant_everywhere_plus_one_1d(neighbor_area) class FixedCrossSection(RxDGeometry): def __init__(self, cross_area, surface_area=0): self.volumes1d = constant_function_per_length(cross_area) self.surface_areas1d = constant_function_per_length(surface_area) self.is_volume = _always_true self.is_area = _always_false self.neighbor_areas1d = constant_everywhere_plus_one_1d(cross_area) self._cross_area = cross_area self._surface_area = surface_area def __repr__(self): return "FixedCrossSection(%r, surface_area=%r)" % ( self._cross_area, self._surface_area, ) class FixedPerimeter(RxDGeometry): def __init__(self, perimeter, on_cell_surface=False): self.volumes1d = constant_function_per_length(perimeter) self.surface_areas1d = _always_0 if not on_cell_surface else self.volumes1d self._perim = perimeter self.is_volume = _always_false self.is_area = _always_true self._on_surface = on_cell_surface def neighbor_areas1d(self, sec): return [self._perim] * (sec.nseg + 1) def __repr__(self): return "FixedPerimeter(%r, on_cell_surface=%r)" % ( self._perim, self._on_surface, ) class ScalableBorder(RxDGeometry): """a membrane that scales proportionally with the diameter. Example use: - the boundary between radial shells e.g. ScalableBorder(diam_scale=0.5) could represent the border of Shell(lo=0, hi=0.5) Args: scale (float, optional) scale the area, default value is π. e.g. for a cylinder of length L and diameter d, ScalableBorder will give an area scale*d*L, by default the surface area. For cylindrical sections only. Use "diam_scale" instead to correctly handle cylindrical and non-cylindrical sections. diam_scale (float, optional), scale the diameter, default value is 1. e.g. for a cylinder of length L and diameter d, ScalableBorder will give an area diam_scale*π*d*L, by default the surface area. Note: Provide either a scale or diam_scale, not both. Sometimes useful for the boundary between FractionalVolume objects, but see also DistributedBoundary which scales with area. """ def __init__(self, scale=None, diam_scale=None, on_cell_surface=False): if scale is not None and diam_scale is not None: raise RxDException( "ScalableBorder either provide scale or diam_scale, not both" ) elif diam_scale is not None: self._scale = numpy.pi self._diam_scale = diam_scale elif scale is not None: self._scale = scale self._diam_scale = 1.0 else: self._scale = numpy.pi self._diam_scale = 1.0 self.volumes1d = _make_surfacearea1d_function(self._scale, self._diam_scale) self.surface_areas1d = _always_0 if not on_cell_surface else self.volumes1d self.is_volume = _always_false self.is_area = _always_true self.neighbor_areas1d = _make_perimeter_function(self._scale, self._diam_scale) self._on_surface = on_cell_surface def __repr__(self): return "ScalableBorder(%r, on_cell_surface=%r)" % ( self._scale, self._on_surface, ) # TODO: remove this, use FixedPerimeter instead? class ConstantArea(RxDGeometry): def __init__(self, area=1, perim=1, on_cell_surface=False): # TODO: fix this warnings.warn("ConstantArea probably not right") self.volumes1d = constant_function(area) self.surface_areas1d = ( _always_0 if not on_cell_surface else constant_function(area) ) self._perim = perim self.is_volume = _always_false self.is_area = _always_true def neighbor_areas1d(self, sec): return [self._perim] * (sec.nseg + 1) # TODO: is there a better name than Shell? class Shell(RxDGeometry): def __init__(self, lo=None, hi=None): if lo is None or hi is None: raise RxDException("only Shells with a lo and hi are supported for now") if lo > hi: lo, hi = hi, lo if lo == hi: raise RxDException("Shell objects must have thickness") self._type = _lo_hi_shell self._lo = lo self._hi = hi if lo == 1 or hi == 1: self.surface_areas1d = _surface_areas1d elif lo < 1 < hi: raise RxDException( "shells may not cross the membrane; i.e. 1 cannot lie strictly between lo and hi" ) else: # TODO: is this what we want; e.g. what if lo < 1 < hi? self.surface_areas1d = _always_0 def __repr__(self): return "Shell(lo=%r, hi=%r)" % (self._lo, self._hi) def neighbor_areas1d(self, sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) for i in range(sec.n3d())] area_pos = numpy.linspace(0, sec.L, sec.nseg + 1) diams = numpy.interp(area_pos, arc3d, diam3d) if self._type == _lo_hi_shell: return numpy.pi * 0.25 * ((diams * self._hi) ** 2 - (diams * self._lo) ** 2) def is_volume(self): return True def is_area(self): return False def volumes1d(self, sec): if not isinstance(sec, nrn.Section): sec = sec._sec arc3d = [sec.arc3d(i) for i in range(sec.n3d())] diam3d = [sec.diam3d(i) for i in range(sec.n3d())] vols = numpy.zeros(sec.nseg) dx = sec.L / sec.nseg for iseg in range(sec.nseg): # get a list of all pts in the segment, including end points lo = iseg * dx hi = (iseg + 1) * dx pts = [lo] + [x for x in arc3d if lo < x < hi] + [hi] diams = numpy.interp(pts, arc3d, diam3d) # sum the volume of the constituent frusta, hollowing out by the inside volume = 0 for i in range(len(pts) - 1): diam0h, diam1h = self._hi * diams[i : i + 2] diam0l, diam1l = self._lo * diams[i : i + 2] pt0, pt1 = pts[i : i + 2] volume += ( numpy.pi * (pt1 - pt0) / 12.0 * ( (diam0h**2 + diam0h * diam1h + diam1h**2) - (diam0l**2 + diam0l * diam1l + diam1l**2) ) ) vols[iseg] = volume return vols class MultipleGeometry(RxDGeometry): """support for different geometries on different sections of a region. Example use: - for radial diffusion in a dendrite (dend) with longitudinal diffusion from a spine (spine). The region for the outer shell of the dendrite (0.8,1] should include the while spine [0,1]; MultipleGeometry(secs=[dend,spine], geos=[Shell(0.8,1), rxd.inside]) Args: sections (list, optional) a list or list-of-lists of sections where the corresponding geometry should be used. If None the same geometry used for all sections, otherwise the list must be the same length as the geos list. If None is in the list, then the corresponding geometry in geos is used as a default value for any section not included in the lists. geometries (list) a list of geometries that are used for the corresponding list of sections in secs. All geometries must be volumes or all all geometries must be areas. """ def __init__(self, secs=None, geos=None): self._secs = {} self._default = None if not secs: if isinstance(geos, list): self._default = geos[0] elif isinstance(geos, RxDGeometry): self._default = geos else: raise RxDException( "MultipleGeometry requires a list-of-lists of sections and their corresponding geometry" ) else: assert len(secs) == len(geos) if all([g.is_area() for g in geos]): self.is_area = _always_true self.is_volume = _always_false elif all([g.is_volume() for g in geos]): self.is_area = _always_false self.is_volume = _always_true else: raise RxDException( "MultipleGeometry requires all geometries are areas or all geometries are volumes" ) for s, g in zip(secs, geos): if not s: self._default = g elif isinstance(s, list): self._secs[h.SectionList(s)] = g else: self._secs[h.SectionList([s])] = g def __repr__(self): secs = [[s for s in sl] for sl in self._secs] geos = [self._secs[sl] for sl in self._secs] return "MultipleGeometry(secs=%r, geos=%r)" % (secs, geos) def _get_geo(self, sec): if not isinstance(sec, nrn.Section): sec = sec._sec for sl in self._secs: if sec in sl: geo = self._secs[sl] break else: if self._default: geo = self._default else: raise RxDException( "MultipleGeometry is not defined on section %r" % sec ) return geo def volumes1d(self, sec): return self._get_geo(sec).volumes1d(sec) def surface_areas1d(self, sec): return self._get_geo(sec).surface_areas1d(sec) def neighbor_areas1d(self, sec): return self._get_geo(sec).neighbor_areas1d(sec)
PypiClean
/Beat_ML1-0.13.1.tar.gz/Beat_ML1-0.13.1/econml/_cate_estimator.py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. """Base classes for all CATE estimators.""" import abc import numpy as np from functools import wraps from copy import deepcopy from warnings import warn from .inference import BootstrapInference from .utilities import (tensordot, ndim, reshape, shape, parse_final_model_params, inverse_onehot, Summary, get_input_columns, check_input_arrays) from .inference import StatsModelsInference, StatsModelsInferenceDiscrete, LinearModelFinalInference,\ LinearModelFinalInferenceDiscrete, NormalInferenceResults, GenericSingleTreatmentModelFinalInference,\ GenericModelFinalInferenceDiscrete from ._shap import _shap_explain_cme, _shap_explain_joint_linear_model_cate from .dowhy import DoWhyWrapper class BaseCateEstimator(metaclass=abc.ABCMeta): """Base class for all CATE estimators in this package.""" def _get_inference_options(self): """ Produce a dictionary mapping string names to :class:`.Inference` types. This is used by the :meth:`fit` method when a string is passed rather than an :class:`.Inference` type. """ return {'bootstrap': BootstrapInference} def _get_inference(self, inference): options = self._get_inference_options() if isinstance(inference, str): if inference in options: inference = options[inference]() else: raise ValueError("Inference option '%s' not recognized; valid values are %s" % (inference, [*options])) # since inference objects can be stateful, we must copy it before fitting; # otherwise this sequence wouldn't work: # est1.fit(..., inference=inf) # est2.fit(..., inference=inf) # est1.effect_interval(...) # because inf now stores state from fitting est2 return deepcopy(inference) def _set_input_names(self, Y, T, X, set_flag=False): """Set input column names if inputs have column metadata.""" self._input_names = { "feature_names": get_input_columns(X, prefix="X"), "output_names": get_input_columns(Y, prefix="Y"), "treatment_names": get_input_columns(T, prefix="T") } if set_flag: # This flag is true when names are set in a child class instead # If names are set in a child class, add an attribute reflecting that self._input_names_set = True def _strata(self, Y, T, *args, **kwargs): """ Get an array of values representing strata that should be preserved by bootstrapping. For example, if treatment is discrete, then each bootstrapped estimator needs to be given at least one instance with each treatment type. For estimators like DRIV, then the same is true of the combination of treatment and instrument. The arguments to this method will match those to fit. Returns ------- strata : array or None A vector with the same number of rows as the inputs, where the unique values represent the strata that need to be preserved by bootstrapping, or None if no preservation is necessary. """ return None def _prefit(self, Y, T, *args, **kwargs): self._d_y = np.shape(Y)[1:] self._d_t = np.shape(T)[1:] # This works only if X is passed as a kwarg # We plan to enforce X as kwarg only in future releases if not hasattr(self, "_input_names_set") or not self._input_names_set: # This checks if names have been set in a child class # If names were set in a child class, don't do it again X = kwargs.get('X') self._set_input_names(Y, T, X) def _postfit(self, Y, T, *args, **kwargs): # Wraps-up fit by setting attributes, cleaning up, etc. pass @abc.abstractmethod def fit(self, *args, inference=None, **kwargs): """ Estimate the counterfactual model from data, i.e. estimates functions :math:`\\tau(X, T0, T1)`, :math:`\\partial \\tau(T, X)`. Note that the signature of this method may vary in subclasses (e.g. classes that don't support instruments will not allow a `Z` argument) Parameters ---------- Y: (n, d_y) matrix or vector of length n Outcomes for each sample T: (n, d_t) matrix or vector of length n Treatments for each sample X: optional (n, d_x) matrix Features for each sample W: optional (n, d_w) matrix Controls for each sample Z: optional (n, d_z) matrix Instruments for each sample inference: optional string, :class:`.Inference` instance, or None Method for performing inference. All estimators support ``'bootstrap'`` (or an instance of :class:`.BootstrapInference`), some support other methods as well. Returns ------- self """ pass def _wrap_fit(m): @wraps(m) def call(self, Y, T, *args, inference=None, **kwargs): inference = self._get_inference(inference) self._prefit(Y, T, *args, **kwargs) if inference is not None: inference.prefit(self, Y, T, *args, **kwargs) # call the wrapped fit method m(self, Y, T, *args, **kwargs) self._postfit(Y, T, *args, **kwargs) if inference is not None: # NOTE: we call inference fit *after* calling the main fit method inference.fit(self, Y, T, *args, **kwargs) self._inference = inference return self return call @abc.abstractmethod def effect(self, X=None, *, T0, T1): """ Calculate the heterogeneous treatment effect :math:`\\tau(X, T0, T1)`. The effect is calculated between the two treatment points conditional on a vector of features on a set of m test samples :math:`\\{T0_i, T1_i, X_i\\}`. Parameters ---------- T0: (m, d_t) matrix or vector of length m Base treatments for each sample T1: (m, d_t) matrix or vector of length m Target treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- τ: (m, d_y) matrix Heterogeneous treatment effects on each outcome for each sample Note that when Y is a vector rather than a 2-dimensional array, the corresponding singleton dimension will be collapsed (so this method will return a vector) """ pass @abc.abstractmethod def marginal_effect(self, T, X=None): """ Calculate the heterogeneous marginal effect :math:`\\partial\\tau(T, X)`. The marginal effect is calculated around a base treatment point conditional on a vector of features on a set of m test samples :math:`\\{T_i, X_i\\}`. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- grad_tau: (m, d_y, d_t) array Heterogeneous marginal effects on each outcome for each sample Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will also be a vector) """ pass def ate(self, X=None, *, T0, T1): """ Calculate the average treatment effect :math:`E_X[\\tau(X, T0, T1)]`. The effect is calculated between the two treatment points and is averaged over the population of X variables. Parameters ---------- T0: (m, d_t) matrix or vector of length m Base treatments for each sample T1: (m, d_t) matrix or vector of length m Target treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- τ: float or (d_y,) array Average treatment effects on each outcome Note that when Y is a vector rather than a 2-dimensional array, the result will be a scalar """ return np.mean(self.effect(X=X, T0=T0, T1=T1), axis=0) def cate_feature_names(self, feature_names=None): """Public interface for getting feature names. To be overriden by estimators that apply transformations the input features. Parameters ---------- feature_names: list of strings of length X.shape[1] or None The names of the input features. If None and X is a dataframe, it defaults to the column names from the dataframe. Returns ------- out_feature_names: list of strings or None Returns feature names. """ if feature_names is not None: return feature_names if hasattr(self, "_input_names"): return self._input_names["feature_names"] return None def cate_output_names(self, output_names=None): """ Public interface for getting output names. To be overriden by estimators that apply transformations the outputs. Parameters ---------- output_names: list of strings of length Y.shape[1] or None The names of the outcomes. If None and the Y passed to fit was a dataframe, it defaults to the column names from the dataframe. Returns ------- output_names: list of strings Returns output names. """ if output_names is not None: return output_names if hasattr(self, "_input_names"): return self._input_names["output_names"] return None def cate_treatment_names(self, treatment_names=None): """ Public interface for getting treatment names. To be overriden by estimators that apply transformations the treatments. Parameters ---------- treatment_names: list of strings of length T.shape[1] or None The names of the treatments. If None and the T passed to fit was a dataframe, it defaults to the column names from the dataframe. Returns ------- treatment_names: list of strings Returns treatment names. """ if treatment_names is not None: return treatment_names if hasattr(self, "_input_names"): return self._input_names["treatment_names"] return None def marginal_ate(self, T, X=None): """ Calculate the average marginal effect :math:`E_{T, X}[\\partial\\tau(T, X)]`. The marginal effect is calculated around a base treatment point and averaged over the population of X. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- grad_tau: (d_y, d_t) array Average marginal effects on each outcome Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will be a scalar) """ return np.mean(self.marginal_effect(T, X=X), axis=0) def _expand_treatments(self, X=None, *Ts): """ Given a set of features and treatments, return possibly modified features and treatments. Parameters ---------- X: optional (m, d_x) matrix Features for each sample, or None Ts: sequence of (m, d_t) matrices Base treatments for each sample Returns ------- output : tuple (X',T0',T1',...) """ return (X,) + Ts def _defer_to_inference(m): @wraps(m) def call(self, *args, **kwargs): name = m.__name__ if self._inference is not None: return getattr(self._inference, name)(*args, **kwargs) else: raise AttributeError("Can't call '%s' because 'inference' is None" % name) return call @_defer_to_inference def effect_interval(self, X=None, *, T0=0, T1=1, alpha=0.05): """ Confidence intervals for the quantities :math:`\\tau(X, T0, T1)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`effect(X, T0, T1)<effect>`, type of :meth:`effect(X, T0, T1))<effect>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @_defer_to_inference def effect_inference(self, X=None, *, T0=0, T1=1): """ Inference results for the quantities :math:`\\tau(X, T0, T1)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample Returns ------- InferenceResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass @_defer_to_inference def marginal_effect_interval(self, T, X=None, *, alpha=0.05): """ Confidence intervals for the quantities :math:`\\partial \\tau(T, X)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix or None (Default=None) Features for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`marginal_effect(T, X)<marginal_effect>`, \ type of :meth:`marginal_effect(T, X)<marginal_effect>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @_defer_to_inference def marginal_effect_inference(self, T, X=None): """ Inference results for the quantities :math:`\\partial \\tau(T, X)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix or None (Default=None) Features for each sample Returns ------- InferenceResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass @_defer_to_inference def ate_interval(self, X=None, *, T0, T1, alpha=0.05): """ Confidence intervals for the quantity :math:`E_X[\\tau(X, T0, T1)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`ate(X, T0, T1)<ate>`, type of :meth:`ate(X, T0, T1))<ate>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @_defer_to_inference def ate_inference(self, X=None, *, T0, T1): """ Inference results for the quantity :math:`E_X[\\tau(X, T0, T1)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix Features for each sample T0: optional (m, d_t) matrix or vector of length m (Default=0) Base treatments for each sample T1: optional (m, d_t) matrix or vector of length m (Default=1) Target treatments for each sample Returns ------- PopulationSummaryResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass @_defer_to_inference def marginal_ate_interval(self, T, X=None, *, alpha=0.05): """ Confidence intervals for the quantities :math:`E_{T,X}[\\partial \\tau(T, X)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix or None (Default=None) Features for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`marginal_ate(T, X)<marginal_ate>`, \ type of :meth:`marginal_ate(T, X)<marginal_ate>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @_defer_to_inference def marginal_ate_inference(self, T, X=None): """ Inference results for the quantities :math:`E_{T,X}[\\partial \\tau(T, X)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix or None (Default=None) Features for each sample Returns ------- PopulationSummaryResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass @property def dowhy(self): """ Get an instance of :class:`.DoWhyWrapper` to allow other functionalities from dowhy package. (e.g. causal graph, refutation test, etc.) Returns ------- DoWhyWrapper: instance An instance of :class:`.DoWhyWrapper` """ return DoWhyWrapper(self) class LinearCateEstimator(BaseCateEstimator): """Base class for all CATE estimators with linear treatment effects in this package.""" @abc.abstractmethod def const_marginal_effect(self, X=None): """ Calculate the constant marginal CATE :math:`\\theta(·)`. The marginal effect is conditional on a vector of features on a set of m test samples X[i]. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample. Returns ------- theta: (m, d_y, d_t) matrix or (d_y, d_t) matrix if X is None Constant marginal CATE of each treatment on each outcome for each sample X[i]. Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will also be a vector) """ pass def effect(self, X=None, *, T0, T1): """ Calculate the heterogeneous treatment effect :math:`\\tau(X, T0, T1)`. The effect is calculated between the two treatment points conditional on a vector of features on a set of m test samples :math:`\\{T0_i, T1_i, X_i\\}`. Since this class assumes a linear effect, only the difference between T0ᵢ and T1ᵢ matters for this computation. Parameters ---------- T0: (m, d_t) matrix Base treatments for each sample T1: (m, d_t) matrix Target treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- effect: (m, d_y) matrix (or length m vector if Y was a vector) Heterogeneous treatment effects on each outcome for each sample. Note that when Y is a vector rather than a 2-dimensional array, the corresponding singleton dimension will be collapsed (so this method will return a vector) """ X, T0, T1 = self._expand_treatments(X, T0, T1) # TODO: what if input is sparse? - there's no equivalent to einsum, # but tensordot can't be applied to this problem because we don't sum over m eff = self.const_marginal_effect(X) # if X is None then the shape of const_marginal_effect will be wrong because the number # of rows of T was not taken into account if X is None: eff = np.repeat(eff, shape(T0)[0], axis=0) m = shape(eff)[0] dT = T1 - T0 einsum_str = 'myt,mt->my' if ndim(dT) == 1: einsum_str = einsum_str.replace('t', '') if ndim(eff) == ndim(dT): # y is a vector, rather than a 2D array einsum_str = einsum_str.replace('y', '') return np.einsum(einsum_str, eff, dT) def marginal_effect(self, T, X=None): """ Calculate the heterogeneous marginal effect :math:`\\partial\\tau(T, X)`. The marginal effect is calculated around a base treatment point conditional on a vector of features on a set of m test samples :math:`\\{T_i, X_i\\}`. Since this class assumes a linear model, the base treatment is ignored in this calculation. Parameters ---------- T: (m, d_t) matrix Base treatments for each sample X: optional (m, d_x) matrix Features for each sample Returns ------- grad_tau: (m, d_y, d_t) array Heterogeneous marginal effects on each outcome for each sample Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will also be a vector) """ X, T = self._expand_treatments(X, T) eff = self.const_marginal_effect(X) return np.repeat(eff, shape(T)[0], axis=0) if X is None else eff def marginal_effect_interval(self, T, X=None, *, alpha=0.05): X, T = self._expand_treatments(X, T) effs = self.const_marginal_effect_interval(X=X, alpha=alpha) if X is None: # need to repeat by the number of rows of T to ensure the right shape effs = tuple(np.repeat(eff, shape(T)[0], axis=0) for eff in effs) return effs marginal_effect_interval.__doc__ = BaseCateEstimator.marginal_effect_interval.__doc__ def marginal_effect_inference(self, T, X=None): X, T = self._expand_treatments(X, T) cme_inf = self.const_marginal_effect_inference(X=X) if X is None: cme_inf = cme_inf._expand_outputs(shape(T)[0]) return cme_inf marginal_effect_inference.__doc__ = BaseCateEstimator.marginal_effect_inference.__doc__ @BaseCateEstimator._defer_to_inference def const_marginal_effect_interval(self, X=None, *, alpha=0.05): """ Confidence intervals for the quantities :math:`\\theta(X)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`const_marginal_effect(X)<const_marginal_effect>` ,\ type of :meth:`const_marginal_effect(X)<const_marginal_effect>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @BaseCateEstimator._defer_to_inference def const_marginal_effect_inference(self, X=None): """ Inference results for the quantities :math:`\\theta(X)` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample Returns ------- InferenceResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass def const_marginal_ate(self, X=None): """ Calculate the average constant marginal CATE :math:`E_X[\\theta(X)]`. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample. Returns ------- theta: (d_y, d_t) matrix Average constant marginal CATE of each treatment on each outcome. Note that when Y or T is a vector rather than a 2-dimensional array, the corresponding singleton dimensions in the output will be collapsed (e.g. if both are vectors, then the output of this method will be a scalar) """ return np.mean(self.const_marginal_effect(X=X), axis=0) @BaseCateEstimator._defer_to_inference def const_marginal_ate_interval(self, X=None, *, alpha=0.05): """ Confidence intervals for the quantities :math:`E_X[\\theta(X)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper : tuple(type of :meth:`const_marginal_ate(X)<const_marginal_ate>` ,\ type of :meth:`const_marginal_ate(X)<const_marginal_ate>` ) The lower and the upper bounds of the confidence interval for each quantity. """ pass @BaseCateEstimator._defer_to_inference def const_marginal_ate_inference(self, X=None): """ Inference results for the quantities :math:`E_X[\\theta(X)]` produced by the model. Available only when ``inference`` is not ``None``, when calling the fit method. Parameters ---------- X: optional (m, d_x) matrix or None (Default=None) Features for each sample Returns ------- PopulationSummaryResults: object The inference results instance contains prediction and prediction standard error and can on demand calculate confidence interval, z statistic and p value. It can also output a dataframe summary of these inference results. """ pass def marginal_ate(self, T, X=None): return self.const_marginal_ate(X=X) marginal_ate.__doc__ = BaseCateEstimator.marginal_ate.__doc__ def marginal_ate_interval(self, T, X=None, *, alpha=0.05): return self.const_marginal_ate_interval(X=X, alpha=alpha) marginal_ate_interval.__doc__ = BaseCateEstimator.marginal_ate_interval.__doc__ def marginal_ate_inference(self, T, X=None): return self.const_marginal_ate_inference(X=X) marginal_ate_inference.__doc__ = BaseCateEstimator.marginal_ate_inference.__doc__ def shap_values(self, X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100): """ Shap value for the final stage models (const_marginal_effect) Parameters ---------- X: (m, d_x) matrix Features for each sample. Should be in the same shape of fitted X in final stage. feature_names: optional None or list of strings of length X.shape[1] (Default=None) The names of input features. treatment_names: optional None or list (Default=None) The name of treatment. In discrete treatment scenario, the name should not include the name of the baseline treatment (i.e. the control treatment, which by default is the alphabetically smaller) output_names: optional None or list (Default=None) The name of the outcome. background_samples: int or None, (Default=100) How many samples to use to compute the baseline effect. If None then all samples are used. Returns ------- shap_outs: nested dictionary of Explanation object A nested dictionary by using each output name (e.g. 'Y0', 'Y1', ... when `output_names=None`) and each treatment name (e.g. 'T0', 'T1', ... when `treatment_names=None`) as key and the shap_values explanation object as value. If the input data at fit time also contain metadata, (e.g. are pandas DataFrames), then the column metatdata for the treatments, outcomes and features are used instead of the above defaults (unless the user overrides with explicitly passing the corresponding names). """ return _shap_explain_cme(self.const_marginal_effect, X, self._d_t, self._d_y, feature_names=feature_names, treatment_names=treatment_names, output_names=output_names, input_names=self._input_names, background_samples=background_samples) class TreatmentExpansionMixin(BaseCateEstimator): """Mixin which automatically handles promotions of scalar treatments to the appropriate shape.""" transformer = None def _prefit(self, Y, T, *args, **kwargs): super()._prefit(Y, T, *args, **kwargs) # need to store the *original* dimensions of T so that we can expand scalar inputs to match; # subclasses should overwrite self._d_t with post-transformed dimensions of T for generating treatments self._d_t_in = self._d_t def _postfit(self, Y, T, *args, **kwargs): super()._postfit(Y, T, *args, **kwargs) if self.transformer: self._set_transformed_treatment_names() def _expand_treatments(self, X=None, *Ts): X, *Ts = check_input_arrays(X, *Ts) n_rows = 1 if X is None else shape(X)[0] outTs = [] for T in Ts: if (ndim(T) == 0) and self._d_t_in and self._d_t_in[0] > 1: warn("A scalar was specified but there are multiple treatments; " "the same value will be used for each treatment. Consider specifying" "all treatments, or using the const_marginal_effect method.") if ndim(T) == 0: T = np.full((n_rows,) + self._d_t_in, T) if self.transformer: T = self.transformer.transform(reshape(T, (-1, 1))) outTs.append(T) return (X,) + tuple(outTs) def _set_transformed_treatment_names(self): """Works with sklearn OHEs""" if hasattr(self, "_input_names"): self._input_names["treatment_names"] = self.transformer.get_feature_names( self._input_names["treatment_names"]).tolist() def cate_treatment_names(self, treatment_names=None): """ Get treatment names. If the treatment is discrete, it will return expanded treatment names. Parameters ---------- treatment_names: list of strings of length T.shape[1] or None The names of the treatments. If None and the T passed to fit was a dataframe, it defaults to the column names from the dataframe. Returns ------- out_treatment_names: list of strings Returns (possibly expanded) treatment names. """ if treatment_names is not None: if self.transformer: return self.transformer.get_feature_names(treatment_names).tolist() return treatment_names # Treatment names is None, default to BaseCateEstimator return super().cate_treatment_names() # override effect to set defaults, which works with the new definition of _expand_treatments def effect(self, X=None, *, T0=0, T1=1): # NOTE: don't explicitly expand treatments here, because it's done in the super call return super().effect(X, T0=T0, T1=T1) effect.__doc__ = BaseCateEstimator.effect.__doc__ def ate(self, X=None, *, T0=0, T1=1): return super().ate(X=X, T0=T0, T1=T1) ate.__doc__ = BaseCateEstimator.ate.__doc__ def ate_interval(self, X=None, *, T0=0, T1=1, alpha=0.05): return super().ate_interval(X=X, T0=T0, T1=T1, alpha=alpha) ate_interval.__doc__ = BaseCateEstimator.ate_interval.__doc__ def ate_inference(self, X=None, *, T0=0, T1=1): return super().ate_inference(X=X, T0=T0, T1=T1) ate_inference.__doc__ = BaseCateEstimator.ate_inference.__doc__ class LinearModelFinalCateEstimatorMixin(BaseCateEstimator): """ Base class for models where the final stage is a linear model. Such an estimator must implement a :attr:`model_final_` attribute that points to the fitted final :class:`.StatsModelsLinearRegression` object that represents the fitted CATE model. Also must implement :attr:`featurizer_` that points to the fitted featurizer and :attr:`bias_part_of_coef` that designates if the intercept is the first element of the :attr:`model_final_` coefficient. Attributes ---------- bias_part_of_coef: bool Whether the CATE model's intercept is contained in the final model's ``coef_`` rather than as a separate ``intercept_`` """ def _get_inference_options(self): options = super()._get_inference_options() options.update(auto=LinearModelFinalInference) return options @property def bias_part_of_coef(self): return False @property def coef_(self): """ The coefficients in the linear model of the constant marginal treatment effect. Returns ------- coef: (n_x,) or (n_t, n_x) or (n_y, n_t, n_x) array like Where n_x is the number of features that enter the final model (either the dimension of X or the dimension of featurizer.fit_transform(X) if the CATE estimator has a featurizer.), n_t is the number of treatments, n_y is the number of outcomes. Dimensions are omitted if the original input was a vector and not a 2D array. For binary treatment the n_t dimension is also omitted. """ return parse_final_model_params(self.model_final_.coef_, self.model_final_.intercept_, self._d_y, self._d_t, self._d_t_in, self.bias_part_of_coef, self.fit_cate_intercept_)[0] @property def intercept_(self): """ The intercept in the linear model of the constant marginal treatment effect. Returns ------- intercept: float or (n_y,) or (n_y, n_t) array like Where n_t is the number of treatments, n_y is the number of outcomes. Dimensions are omitted if the original input was a vector and not a 2D array. For binary treatment the n_t dimension is also omitted. """ if not self.fit_cate_intercept_: raise AttributeError("No intercept was fitted!") return parse_final_model_params(self.model_final_.coef_, self.model_final_.intercept_, self._d_y, self._d_t, self._d_t_in, self.bias_part_of_coef, self.fit_cate_intercept_)[1] @BaseCateEstimator._defer_to_inference def coef__interval(self, *, alpha=0.05): """ The coefficients in the linear model of the constant marginal treatment effect. Parameters ---------- alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lb, ub: tuple(type of :meth:`coef_()<coef_>`, type of :meth:`coef_()<coef_>`) The lower and upper bounds of the confidence interval for each quantity. """ pass @BaseCateEstimator._defer_to_inference def coef__inference(self): """ The inference of coefficients in the linear model of the constant marginal treatment effect. Returns ------- InferenceResults: object The inference of the coefficients in the final linear model """ pass @BaseCateEstimator._defer_to_inference def intercept__interval(self, *, alpha=0.05): """ The intercept in the linear model of the constant marginal treatment effect. Parameters ---------- alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper: tuple(type of :meth:`intercept_()<intercept_>`, type of :meth:`intercept_()<intercept_>`) The lower and upper bounds of the confidence interval. """ pass @BaseCateEstimator._defer_to_inference def intercept__inference(self): """ The inference of intercept in the linear model of the constant marginal treatment effect. Returns ------- InferenceResults: object The inference of the intercept in the final linear model """ pass def summary(self, alpha=0.05, value=0, decimals=3, feature_names=None, treatment_names=None, output_names=None): """ The summary of coefficient and intercept in the linear model of the constant marginal treatment effect. Parameters ---------- alpha: optional float in [0, 1] (default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. value: optinal float (default=0) The mean value of the metric you'd like to test under null hypothesis. decimals: optinal int (default=3) Number of decimal places to round each column to. feature_names: optional list of strings or None (default is None) The input of the feature names treatment_names: optional list of strings or None (default is None) The names of the treatments output_names: optional list of strings or None (default is None) The names of the outputs Returns ------- smry : Summary instance this holds the summary tables and text, which can be printed or converted to various output formats. """ # Get input names treatment_names = self.cate_treatment_names(treatment_names) output_names = self.cate_output_names(output_names) # Summary smry = Summary() smry.add_extra_txt(["<sub>A linear parametric conditional average treatment effect (CATE) model was fitted:", "$Y = \\Theta(X)\\cdot T + g(X, W) + \\epsilon$", "where for every outcome $i$ and treatment $j$ the CATE $\\Theta_{ij}(X)$ has the form:", "$\\Theta_{ij}(X) = \\phi(X)' coef_{ij} + cate\\_intercept_{ij}$", "where $\\phi(X)$ is the output of the `featurizer` or $X$ if `featurizer`=None. " "Coefficient Results table portrays the $coef_{ij}$ parameter vector for " "each outcome $i$ and treatment $j$. " "Intercept Results table portrays the $cate\\_intercept_{ij}$ parameter.</sub>"]) d_t = self._d_t[0] if self._d_t else 1 d_y = self._d_y[0] if self._d_y else 1 try: coef_table = self.coef__inference().summary_frame(alpha=alpha, value=value, decimals=decimals, feature_names=feature_names, treatment_names=treatment_names, output_names=output_names) coef_array = coef_table.values coef_headers = coef_table.columns.tolist() n_level = coef_table.index.nlevels if n_level > 1: coef_stubs = ["|".join(ind_value) for ind_value in coef_table.index.values] else: coef_stubs = coef_table.index.tolist() coef_title = 'Coefficient Results' smry.add_table(coef_array, coef_headers, coef_stubs, coef_title) except Exception as e: print("Coefficient Results: ", str(e)) try: intercept_table = self.intercept__inference().summary_frame(alpha=alpha, value=value, decimals=decimals, feature_names=None, treatment_names=treatment_names, output_names=output_names) intercept_array = intercept_table.values intercept_headers = intercept_table.columns.tolist() n_level = intercept_table.index.nlevels if n_level > 1: intercept_stubs = ["|".join(ind_value) for ind_value in intercept_table.index.values] else: intercept_stubs = intercept_table.index.tolist() intercept_title = 'CATE Intercept Results' smry.add_table(intercept_array, intercept_headers, intercept_stubs, intercept_title) except Exception as e: print("CATE Intercept Results: ", str(e)) if len(smry.tables) > 0: return smry def shap_values(self, X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100): if hasattr(self, "featurizer_") and self.featurizer_ is not None: X = self.featurizer_.transform(X) feature_names = self.cate_feature_names(feature_names) return _shap_explain_joint_linear_model_cate(self.model_final_, X, self._d_t, self._d_y, self.bias_part_of_coef, feature_names=feature_names, treatment_names=treatment_names, output_names=output_names, input_names=self._input_names, background_samples=background_samples) shap_values.__doc__ = LinearCateEstimator.shap_values.__doc__ class StatsModelsCateEstimatorMixin(LinearModelFinalCateEstimatorMixin): """ Mixin class that offers `inference='statsmodels'` options to the CATE estimator that inherits it. Such an estimator must implement a :attr:`model_final_` attribute that points to the fitted final :class:`.StatsModelsLinearRegression` object that represents the fitted CATE model. Also must implement :attr:`featurizer_` that points to the fitted featurizer and :attr:`bias_part_of_coef` that designates if the intercept is the first element of the :attr:`model_final_` coefficient. """ def _get_inference_options(self): # add statsmodels to parent's options options = super()._get_inference_options() options.update(statsmodels=StatsModelsInference) options.update(auto=StatsModelsInference) return options class DebiasedLassoCateEstimatorMixin(LinearModelFinalCateEstimatorMixin): """Mixin for cate models where the final stage is a debiased lasso model.""" def _get_inference_options(self): # add debiasedlasso to parent's options options = super()._get_inference_options() options.update(debiasedlasso=LinearModelFinalInference) options.update(auto=LinearModelFinalInference) return options class ForestModelFinalCateEstimatorMixin(BaseCateEstimator): def _get_inference_options(self): # add blb to parent's options options = super()._get_inference_options() options.update(blb=GenericSingleTreatmentModelFinalInference) options.update(auto=GenericSingleTreatmentModelFinalInference) return options @property def feature_importances_(self): return self.model_final_.feature_importances_ class LinearModelFinalCateEstimatorDiscreteMixin(BaseCateEstimator): # TODO Share some logic with non-discrete version """ Base class for models where the final stage is a linear model. Subclasses must expose a ``fitted_models_final`` attribute returning an array of the fitted models for each non-control treatment """ def _get_inference_options(self): options = super()._get_inference_options() options.update(auto=LinearModelFinalInferenceDiscrete) return options def coef_(self, T): """ The coefficients in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. Returns ------- coef: (n_x,) or (n_y, n_x) array like Where n_x is the number of features that enter the final model (either the dimension of X or the dimension of featurizer.fit_transform(X) if the CATE estimator has a featurizer.) """ _, T = self._expand_treatments(None, T) ind = inverse_onehot(T).item() - 1 assert ind >= 0, "No model was fitted for the control" return self.fitted_models_final[ind].coef_ def intercept_(self, T): """ The intercept in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. Returns ------- intercept: float or (n_y,) array like """ if not self.fit_cate_intercept_: raise AttributeError("No intercept was fitted!") _, T = self._expand_treatments(None, T) ind = inverse_onehot(T).item() - 1 assert ind >= 0, "No model was fitted for the control" return self.fitted_models_final[ind].intercept_.reshape(self._d_y) @BaseCateEstimator._defer_to_inference def coef__interval(self, T, *, alpha=0.05): """ The confidence interval for the coefficients in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper: tuple(type of :meth:`coef_(T)<coef_>`, type of :meth:`coef_(T)<coef_>`) The lower and upper bounds of the confidence interval for each quantity. """ pass @BaseCateEstimator._defer_to_inference def coef__inference(self, T): """ The inference for the coefficients in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. Returns ------- InferenceResults: object The inference of the coefficients in the final linear model """ pass @BaseCateEstimator._defer_to_inference def intercept__interval(self, T, *, alpha=0.05): """ The intercept in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. alpha: optional float in [0, 1] (Default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. Returns ------- lower, upper: tuple(type of :meth:`intercept_(T)<intercept_>`, type of :meth:`intercept_(T)<intercept_>`) The lower and upper bounds of the confidence interval. """ pass @BaseCateEstimator._defer_to_inference def intercept__inference(self, T): """ The inference of the intercept in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- T: alphanumeric The input treatment for which we want the coefficients. Returns ------- InferenceResults: object The inference of the intercept in the final linear model """ pass def summary(self, T, *, alpha=0.05, value=0, decimals=3, feature_names=None, treatment_names=None, output_names=None): """ The summary of coefficient and intercept in the linear model of the constant marginal treatment effect associated with treatment T. Parameters ---------- alpha: optional float in [0, 1] (default=0.05) The overall level of confidence of the reported interval. The alpha/2, 1-alpha/2 confidence interval is reported. value: optinal float (default=0) The mean value of the metric you'd like to test under null hypothesis. decimals: optinal int (default=3) Number of decimal places to round each column to. feature_names: optional list of strings or None (default is None) The input of the feature names treatment_names: optional list of strings or None (default is None) The names of the treatments output_names: optional list of strings or None (default is None) The names of the outputs Returns ------- smry : Summary instance this holds the summary tables and text, which can be printed or converted to various output formats. """ # Get input names treatment_names = self.cate_treatment_names(treatment_names) output_names = self.cate_output_names(output_names) # Note: we do not transform feature names since that is done within summary_frame # Summary smry = Summary() smry.add_extra_txt(["<sub>A linear parametric conditional average treatment effect (CATE) model was fitted:", "$Y = \\Theta(X)\\cdot T + g(X, W) + \\epsilon$", "where $T$ is the one-hot-encoding of the discrete treatment and " "for every outcome $i$ and treatment $j$ the CATE $\\Theta_{ij}(X)$ has the form:", "$\\Theta_{ij}(X) = \\phi(X)' coef_{ij} + cate\\_intercept_{ij}$", "where $\\phi(X)$ is the output of the `featurizer` or $X$ if `featurizer`=None. " "Coefficient Results table portrays the $coef_{ij}$ parameter vector for " "each outcome $i$ and the designated treatment $j$ passed to summary. " "Intercept Results table portrays the $cate\\_intercept_{ij}$ parameter.</sub>"]) try: coef_table = self.coef__inference(T).summary_frame( alpha=alpha, value=value, decimals=decimals, feature_names=feature_names, output_names=output_names) coef_array = coef_table.values coef_headers = coef_table.columns.tolist() coef_stubs = coef_table.index.tolist() coef_title = 'Coefficient Results' smry.add_table(coef_array, coef_headers, coef_stubs, coef_title) except Exception as e: print("Coefficient Results: ", e) try: intercept_table = self.intercept__inference(T).summary_frame( alpha=alpha, value=value, decimals=decimals, feature_names=None, output_names=output_names) intercept_array = intercept_table.values intercept_headers = intercept_table.columns.tolist() intercept_stubs = intercept_table.index.tolist() intercept_title = 'CATE Intercept Results' smry.add_table(intercept_array, intercept_headers, intercept_stubs, intercept_title) except Exception as e: print("CATE Intercept Results: ", e) if len(smry.tables) > 0: return smry class StatsModelsCateEstimatorDiscreteMixin(LinearModelFinalCateEstimatorDiscreteMixin): """ Mixin class that offers `inference='statsmodels'` options to the CATE estimator that inherits it. Such an estimator must implement a :attr:`model_final_` attribute that points to a :class:`.StatsModelsLinearRegression` object that is cloned to fit each discrete treatment target CATE model and a :attr:`fitted_models_final` attribute that returns the list of fitted final models that represent the CATE for each categorical treatment. """ def _get_inference_options(self): # add statsmodels to parent's options options = super()._get_inference_options() options.update(statsmodels=StatsModelsInferenceDiscrete) options.update(auto=StatsModelsInferenceDiscrete) return options class DebiasedLassoCateEstimatorDiscreteMixin(LinearModelFinalCateEstimatorDiscreteMixin): """Mixin for cate models where the final stage is a debiased lasso model.""" def _get_inference_options(self): # add statsmodels to parent's options options = super()._get_inference_options() options.update(debiasedlasso=LinearModelFinalInferenceDiscrete) options.update(auto=LinearModelFinalInferenceDiscrete) return options class ForestModelFinalCateEstimatorDiscreteMixin(BaseCateEstimator): def _get_inference_options(self): # add blb to parent's options options = super()._get_inference_options() options.update(blb=GenericModelFinalInferenceDiscrete) options.update(auto=GenericModelFinalInferenceDiscrete) return options def feature_importances_(self, T): _, T = self._expand_treatments(None, T) ind = inverse_onehot(T).item() - 1 assert ind >= 0, "No model was fitted for the control" return self.fitted_models_final[ind].feature_importances_
PypiClean
/15five-snowplow-tracker-0.8.156.tar.gz/15five-snowplow-tracker-0.8.156/snowplow_tracker/tracker.py
import time import uuid import six from contracts import contract, new_contract from snowplow_tracker import payload, _version, SelfDescribingJson from snowplow_tracker import subject as _subject from snowplow_tracker.timestamp import Timestamp, TrueTimestamp, DeviceTimestamp """ Constants & config """ VERSION = "py-%s" % _version.__version__ DEFAULT_ENCODE_BASE64 = True BASE_SCHEMA_PATH = "iglu:com.snowplowanalytics.snowplow" SCHEMA_TAG = "jsonschema" CONTEXT_SCHEMA = "%s/contexts/%s/1-0-1" % (BASE_SCHEMA_PATH, SCHEMA_TAG) UNSTRUCT_EVENT_SCHEMA = "%s/unstruct_event/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG) FORM_NODE_NAMES = ("INPUT", "TEXTAREA", "SELECT") FORM_TYPES = ( "button", "checkbox", "color", "date", "datetime", "datetime-local", "email", "file", "hidden", "image", "month", "number", "password", "radio", "range", "reset", "search", "submit", "tel", "text", "time", "url", "week" ) """ Tracker class """ class Tracker: new_contract("not_none", lambda s: s is not None) new_contract("non_empty_string", lambda s: isinstance(s, six.string_types) and len(s) > 0) new_contract("string_or_none", lambda s: (isinstance(s, six.string_types) and len(s) > 0) or s is None) new_contract("payload", lambda s: isinstance(s, payload.Payload)) new_contract("tracker", lambda s: isinstance(s, Tracker)) new_contract("emitter", lambda s: hasattr(s, "input")) new_contract("self_describing_json", lambda s: isinstance(s, SelfDescribingJson)) new_contract("context_array", "list(self_describing_json)") new_contract("form_node_name", lambda s: s in FORM_NODE_NAMES) new_contract("form_type", lambda s: s.lower() in FORM_TYPES) new_contract("timestamp", lambda x: (isinstance(x, Timestamp))) new_contract("form_element", lambda x: Tracker.check_form_element(x)) @contract def __init__(self, emitters, subject=None, namespace=None, app_id=None, encode_base64=DEFAULT_ENCODE_BASE64): """ :param emitters: Emitters to which events will be sent :type emitters: list[>0](emitter) | emitter :param subject: Subject to be tracked :type subject: subject | None :param namespace: Identifier for the Tracker instance :type namespace: string_or_none :param app_id: Application ID :type app_id: string_or_none :param encode_base64: Whether JSONs in the payload should be base-64 encoded :type encode_base64: bool """ if subject is None: subject = _subject.Subject() if type(emitters) is list: self.emitters = emitters else: self.emitters = [emitters] self.subject = subject self.encode_base64 = encode_base64 self.standard_nv_pairs = { "tv": VERSION, "tna": namespace, "aid": app_id } self.timer = None @staticmethod @contract def get_uuid(): """ Set transaction ID for the payload once during the lifetime of the event. :rtype: string """ return str(uuid.uuid4()) @staticmethod @contract def get_timestamp(tstamp=None): """ :param tstamp: User-input timestamp or None :type tstamp: int | float | None :rtype: int """ if tstamp is None: return int(time.time() * 1000) elif isinstance(tstamp, (int, float, )): return int(tstamp) """ Tracking methods """ @contract def track(self, pb): """ Send the payload to a emitter :param pb: Payload builder :type pb: payload :rtype: tracker """ for emitter in self.emitters: emitter.input(pb.nv_pairs) return self @contract def complete_payload(self, pb, context, tstamp): """ Called by all tracking events to add the standard name-value pairs to the Payload object irrespective of the tracked event. :param pb: Payload builder :type pb: payload :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ pb.add("eid", Tracker.get_uuid()) if isinstance(tstamp, TrueTimestamp): pb.add("ttm", tstamp.value) if isinstance(tstamp, DeviceTimestamp): pb.add("dtm", Tracker.get_timestamp(tstamp.value)) elif isinstance(tstamp, (int, float, type(None))): pb.add("dtm", Tracker.get_timestamp(tstamp)) if context is not None: context_jsons = list(map(lambda c: c.to_json(), context)) context_envelope = SelfDescribingJson(CONTEXT_SCHEMA, context_jsons).to_json() pb.add_json(context_envelope, self.encode_base64, "cx", "co") pb.add_dict(self.standard_nv_pairs) pb.add_dict(self.subject.standard_nv_pairs) return self.track(pb) @contract def track_page_view(self, page_url, page_title=None, referrer=None, context=None, tstamp=None): """ :param page_url: URL of the viewed page :type page_url: non_empty_string :param page_title: Title of the viewed page :type page_title: string_or_none :param referrer: Referrer of the page :type referrer: string_or_none :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ pb = payload.Payload() pb.add("e", "pv") # pv: page view pb.add("url", page_url) pb.add("page", page_title) pb.add("refr", referrer) return self.complete_payload(pb, context, tstamp) @contract def track_page_ping(self, page_url, page_title=None, referrer=None, min_x=None, max_x=None, min_y=None, max_y=None, context=None, tstamp=None): """ :param page_url: URL of the viewed page :type page_url: non_empty_string :param page_title: Title of the viewed page :type page_title: string_or_none :param referrer: Referrer of the page :type referrer: string_or_none :param min_x: Minimum page x offset seen in the last ping period :type min_x: int | None :param max_x: Maximum page x offset seen in the last ping period :type max_x: int | None :param min_y: Minimum page y offset seen in the last ping period :type min_y: int | None :param max_y: Maximum page y offset seen in the last ping period :type max_y: int | None :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ pb = payload.Payload() pb.add("e", "pp") # pp: page ping pb.add("url", page_url) pb.add("page", page_title) pb.add("refr", referrer) pb.add("pp_mix", min_x) pb.add("pp_max", max_x) pb.add("pp_miy", min_y) pb.add("pp_may", max_y) return self.complete_payload(pb, context, tstamp) @contract def track_link_click(self, target_url, element_id=None, element_classes=None, element_target=None, element_content=None, context=None, tstamp=None): """ :param target_url: Target URL of the link :type target_url: non_empty_string :param element_id: ID attribute of the HTML element :type element_id: string_or_none :param element_classes: Classes of the HTML element :type element_classes: list(str) | tuple(str,*) | None :param element_content: The content of the HTML element :type element_content: string_or_none :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = {} properties["targetUrl"] = target_url if element_id is not None: properties["elementId"] = element_id if element_classes is not None: properties["elementClasses"] = element_classes if element_target is not None: properties["elementTarget"] = element_target if element_content is not None: properties["elementContent"] = element_content event_json = SelfDescribingJson("%s/link_click/%s/1-0-1" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_add_to_cart(self, sku, quantity, name=None, category=None, unit_price=None, currency=None, context=None, tstamp=None): """ :param sku: Item SKU or ID :type sku: non_empty_string :param quantity: Number added to cart :type quantity: int :param name: Item's name :type name: string_or_none :param category: Item's category :type category: string_or_none :param unit_price: Item's price :type unit_price: int | float | None :param currency: Type of currency the price is in :type currency: string_or_none :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = {} properties["sku"] = sku properties["quantity"] = quantity if name is not None: properties["name"] = name if category is not None: properties["category"] = category if unit_price is not None: properties["unitPrice"] = unit_price if currency is not None: properties["currency"] = currency event_json = SelfDescribingJson("%s/add_to_cart/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_remove_from_cart(self, sku, quantity, name=None, category=None, unit_price=None, currency=None, context=None, tstamp=None): """ :param sku: Item SKU or ID :type sku: non_empty_string :param quantity: Number added to cart :type quantity: int :param name: Item's name :type name: string_or_none :param category: Item's category :type category: string_or_none :param unit_price: Item's price :type unit_price: int | float | None :param currency: Type of currency the price is in :type currency: string_or_none :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = {} properties["sku"] = sku properties["quantity"] = quantity if name is not None: properties["name"] = name if category is not None: properties["category"] = category if unit_price is not None: properties["unitPrice"] = unit_price if currency is not None: properties["currency"] = currency event_json = SelfDescribingJson("%s/remove_from_cart/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_form_change(self, form_id, element_id, node_name, value, type_=None, element_classes=None, context=None, tstamp=None): """ :param form_id: ID attribute of the HTML form :type form_id: non_empty_string :param element_id: ID attribute of the HTML element :type element_id: string_or_none :param node_name: Type of input element :type node_name: form_node_name :param value: Value of the input element :type value: string_or_none :param type_: Type of data the element represents :type type_: non_empty_string, form_type :param element_classes: Classes of the HTML element :type element_classes: list(str) | tuple(str,*) | None :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = dict() properties["formId"] = form_id properties["elementId"] = element_id properties["nodeName"] = node_name properties["value"] = value if type_ is not None: properties["type"] = type_ if element_classes is not None: properties["elementClasses"] = element_classes event_json = SelfDescribingJson("%s/change_form/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_form_submit(self, form_id, form_classes=None, elements=None, context=None, tstamp=None): """ :param form_id: ID attribute of the HTML form :type form_id: non_empty_string :param form_classes: Classes of the HTML form :type form_classes: list(str) | tuple(str,*) | None :param elements: Classes of the HTML form :type elements: list(form_element) | None :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = dict() properties['formId'] = form_id if form_classes is not None: properties['formClasses'] = form_classes if elements is not None and len(elements) > 0: properties['elements'] = elements event_json = SelfDescribingJson("%s/submit_form/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_site_search(self, terms, filters=None, total_results=None, page_results=None, context=None, tstamp=None): """ :param terms: Search terms :type terms: seq[>=1](str) :param filters: Filters applied to the search :type filters: dict(str:str|bool) | None :param total_results: Total number of results returned :type total_results: int | None :param page_results: Total number of pages of results :type page_results: int | None :param context: Custom context for the event :type context: context_array | None :param tstamp: Optional user-provided timestamp for the event :type tstamp: timestamp | int | float | None :rtype: tracker """ properties = {} properties["terms"] = terms if filters is not None: properties["filters"] = filters if total_results is not None: properties["totalResults"] = total_results if page_results is not None: properties["pageResults"] = page_results event_json = SelfDescribingJson("%s/site_search/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_ecommerce_transaction_item(self, order_id, sku, price, quantity, name=None, category=None, currency=None, context=None, tstamp=None): """ This is an internal method called by track_ecommerce_transaction. It is not for public use. :param order_id: Order ID :type order_id: non_empty_string :param sku: Item SKU :type sku: non_empty_string :param price: Item price :type price: int | float :param quantity: Item quantity :type quantity: int :param name: Item name :type name: string_or_none :param category: Item category :type category: string_or_none :param currency: The currency the price is expressed in :type currency: string_or_none :param context: Custom context for the event :type context: context_array | None :rtype: tracker """ pb = payload.Payload() pb.add("e", "ti") pb.add("ti_id", order_id) pb.add("ti_sk", sku) pb.add("ti_nm", name) pb.add("ti_ca", category) pb.add("ti_pr", price) pb.add("ti_qu", quantity) pb.add("ti_cu", currency) return self.complete_payload(pb, context, tstamp) @contract def track_ecommerce_transaction(self, order_id, total_value, affiliation=None, tax_value=None, shipping=None, city=None, state=None, country=None, currency=None, items=None, context=None, tstamp=None): """ :param order_id: ID of the eCommerce transaction :type order_id: non_empty_string :param total_value: Total transaction value :type total_value: int | float :param affiliation: Transaction affiliation :type affiliation: string_or_none :param tax_value: Transaction tax value :type tax_value: int | float | None :param shipping: Delivery cost charged :type shipping: int | float | None :param city: Delivery address city :type city: string_or_none :param state: Delivery address state :type state: string_or_none :param country: Delivery address country :type country: string_or_none :param currency: The currency the price is expressed in :type currency: string_or_none :param items: The items in the transaction :type items: list(dict(str:*)) :param context: Custom context for the event :type context: context_array | None :rtype: tracker """ pb = payload.Payload() pb.add("e", "tr") pb.add("tr_id", order_id) pb.add("tr_tt", total_value) pb.add("tr_af", affiliation) pb.add("tr_tx", tax_value) pb.add("tr_sh", shipping) pb.add("tr_ci", city) pb.add("tr_st", state) pb.add("tr_co", country) pb.add("tr_cu", currency) tstamp = Tracker.get_timestamp(tstamp) self.complete_payload(pb, context, tstamp) for item in items: item["tstamp"] = tstamp item["order_id"] = order_id item["currency"] = currency self.track_ecommerce_transaction_item(**item) return self @contract def track_screen_view(self, name=None, id_=None, context=None, tstamp=None): """ :param name: The name of the screen view event :type name: string_or_none :param id_: Screen view ID :type id_: string_or_none :param context: Custom context for the event :type context: context_array | None :rtype: tracker """ screen_view_properties = {} if name is not None: screen_view_properties["name"] = name if id_ is not None: screen_view_properties["id"] = id_ event_json = SelfDescribingJson("%s/screen_view/%s/1-0-0" % (BASE_SCHEMA_PATH, SCHEMA_TAG), screen_view_properties) return self.track_unstruct_event(event_json, context, tstamp) @contract def track_struct_event(self, category, action, label=None, property_=None, value=None, context=None, tstamp=None): """ :param category: Category of the event :type category: non_empty_string :param action: The event itself :type action: non_empty_string :param label: Refer to the object the action is performed on :type label: string_or_none :param property_: Property associated with either the action or the object :type property_: string_or_none :param value: A value associated with the user action :type value: int | float | None :param context: Custom context for the event :type context: context_array | None :rtype: tracker """ pb = payload.Payload() pb.add("e", "se") pb.add("se_ca", category) pb.add("se_ac", action) pb.add("se_la", label) pb.add("se_pr", property_) pb.add("se_va", value) return self.complete_payload(pb, context, tstamp) @contract def track_unstruct_event(self, event_json, context=None, tstamp=None): """ :param event_json: The properties of the event. Has two field: A "data" field containing the event properties and A "schema" field identifying the schema against which the data is validated :type event_json: self_describing_json :param context: Custom context for the event :type context: context_array | None :param tstamp: User-set timestamp :type tstamp: timestamp | int | None :rtype: tracker """ envelope = SelfDescribingJson(UNSTRUCT_EVENT_SCHEMA, event_json.to_json()).to_json() pb = payload.Payload() pb.add("e", "ue") pb.add_json(envelope, self.encode_base64, "ue_px", "ue_pr") return self.complete_payload(pb, context, tstamp) # Alias track_self_describing_event = track_unstruct_event @contract def flush(self, is_async=False): """ Flush the emitter :param is_async: Whether the flush is done asynchronously. Default is False :type is_async: bool :rtype: tracker """ for emitter in self.emitters: if is_async: emitter.flush() else: emitter.sync_flush() return self @contract def set_subject(self, subject): """ Set the subject of the events fired by the tracker :param subject: Subject to be tracked :type subject: subject | None :rtype: tracker """ self.subject = subject return self @contract def add_emitter(self, emitter): """ Add a new emitter to which events should be passed :param emitter: New emitter :type emitter: emitter :rtype: tracker """ self.emitters.append(emitter) return self @staticmethod def check_form_element(element): """ PyContracts helper method to check that dictionary conforms element in sumbit_form and change_form schemas """ all_present = isinstance(element, dict) and 'name' in element and 'value' in element and 'nodeName' in element try: if element['type'] in FORM_TYPES: type_valid = True else: type_valid = False except KeyError: type_valid = True return all_present and element['nodeName'] in FORM_NODE_NAMES and type_valid
PypiClean
/FP-SMC-ALS-test1-0.0.1.tar.gz/FP-SMC-ALS-test1-0.0.1/smc/api/session.py
import copy import json import logging import ssl import requests import collections import smc # import smc.api.web from smc.api.web import send_request, counters from smc.api.entry_point import Resource from smc.api.configloader import load_from_file, load_from_environ from smc.api.common import SMCRequest from smc.base.decorators import cached_property from smc.api.exceptions import ( ConfigLoadError, SMCConnectionError, UnsupportedEntryPoint, SessionManagerNotFound, SessionNotFound, SMCOperationFailure, ) from smc.base.model import ElementFactory from requests.adapters import HTTPAdapter, PoolManager from urllib3 import Retry # requests.packages.urllib3.disable_warnings() MAX_RETRY = 5 ERROR_CODES_SUPPORTING_AUTO_RETRY = [ 503, # to support db concurrent access from SMC 409, # to support ETag conflict 429, # to support too many requests 413, # to support entity too large ] HTTP_METHODS_SUPPORTING_AUTO_RETRY = [ "HEAD", "TRACE", "GET", "POST", # to support creation and api services with possible db concurrency "PUT", "OPTIONS", "DELETE", ] logger = logging.getLogger(__name__) class SessionManager(object): """ The SessionManager keeps track of sessions created within smc-python. In most cases, this is transparent functionality as most scripts will use only a single session for it's lifetime. By default a single Session Manager is created that will be used when processing all requests to the SMC. Session Manager also has a hook that can be called that will change the way the session manager retrieves the session from the manager. An example might be that you are using smc-python in a web application and authenticating the user to the SMC. Each web session stores the name of the authenticated user. You want to use that to map to the SMC session by retrieving the user from the web session ID and then from the SessionManager. A function hook can be registered that will retrieve use some external criteria to determine which session to retrieve from the SessionManager. .. seealso:: :meth:`~register_hook`. Creating your own session manager might be useful if you needed custom functionality or needed to extend the default. Create a new manager and call mount to set it on the global request object:: manager = SessionManager() manager.mount() ..note:: By default, a single session is maintained and considered the `default` session. :param list(Session) sessions: list of sessions """ _session_hook = None def __init__(self, sessions=None): self._sessions = collections.OrderedDict() sessions = sessions or [] for session in sessions: self._register(session) # self._connections = local() #TODO: Make self._sessions an attribute # of threading local @classmethod def create(cls, sessions=None): """ A session manager will be mounted to the SMCRequest class through this classmethod. If there is already an existing SessionManager, that is returned instead. :param list sessions: a list of Session objects :rtype: SessionManager """ manager = getattr(SMCRequest, "_session_manager") if manager is not None: return manager manager = SessionManager(sessions) manager.mount() return manager def mount(self): """ Mount this session manager on the request class, making this the global manager for processing requests :return: None """ setattr(SMCRequest, "_session_manager", self) def register_hook(self, hook): """ Add a hook that specifies how to retrieve the session from the session manager. A hook must be a callable that takes one argument (the SessionManager) and extracts the session based on some criteria. An example of using a hook:: from smc import manager def retrieve_session(session_manager): ... admin = session_manager.get_session('admin') return admin if admin.is_active else session_manager.get_default_session() manager.register_hook(retrieve_session) Hooks can be used when your application requires multiple sessions within the same python interpreter. For example, in a web app, you might use the SMC administrator account to log in and store the session within the web application which allows you to also store and retrieve that SMC based session for further operations. """ if callable(hook): self._session_hook = hook def __contains__(self, session): """ A session is considered to exist if the current user attached to the session matches. In SMC, an administrative account must be unique even if it only exists in a specific domain. :rtype: bool """ return session in self.sessions @property def sessions(self): """ All available sessions in this session manager :rtype: list(Session) """ return list(self._sessions.values()) def get_default_session(self): """ The default session is nothing more than the first session added into the session handler pool. This will likely change in the future but for now each session identifies the domain and also manages domain switching within a single session. :rtype: Session """ if self._sessions: return self.get_session(next(iter(self._sessions))) return self.get_session() def get_session(self, user=None): """ Retrieve the session based on user, or return and empty session. Note that an empty session is not inserted into the Session Manager until `login` has been successfully called on the session. :param str user: optional user to find in the session manager :raises SessionNotFound: session was not found in manager :rtype: Session """ session = self._sessions.get(user) return session if session else Session() # raise SessionNotFound('Session specified by name: %s does not currently ' # 'exist.' % user) def close_all(self): for admin_session in list(self._sessions.keys()): self._sessions[admin_session].logout() self._sessions.clear() def _get_session_key(self, session): for name, _session in self._sessions.items(): if _session == session: return name def _register(self, session): """ Register a session """ user_name = session.name smc.session_name.name = "{}-{}".format(user_name, session.api_version) if user_name: self._sessions[smc.session_name.name] = session return smc.session_name.name def _deregister(self, session): """ Deregister a session. """ if session in self: self._sessions.pop(self._get_session_key(session), None) class SSLAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, ssl_version=ssl.PROTOCOL_TLSv1_2) class Session(object): """ Session represents the clients session to the SMC. A session is obtained by calling login(). If sessions need to be long lived as might be the case when running under a web platform, a session is automatically refreshed when it expires. Best practice is to call logout() after to clear the session from the SMC. A session will be automatically closed once the python interpreter closes. Each session will also have a single connection pool associated with it. This results in a single persistent connection to the SMC that will be re-used as needed. """ def __init__(self, manager=None): self._params = {} # Retrieved from login self._session = None # requests.Session self._resource = None # smc.api.entry_point.Resource self._manager = manager # Session Manager that tracks this session # Transactions are supported in version 0.6.2 and beyond. When # run with atomic, this session parameter indicates whether the # operation in process is within an atomic block or not self.in_atomic_block = False # Transactions that are within the given atomic block self.transactions = [] smc.session_name.name = None @property def manager(self): """ Return the session manager for this session :rtype: SessionManager """ manager = SMCRequest._session_manager if not self._manager else self._manager if not manager: raise SessionManagerNotFound( "A session manager was not found. " "This is an initialization error binding the SessionManager. " ) return manager @property def is_active(self): """ Is this session active. Active means there is a stored session ID for the SMC using the current account. This does not specify whether the session ID has been timed out on the server but does indicate the account has not called logout. :rtype: bool """ return self._session is not None and "JSESSIONID" in self._session.cookies @property def _extra_args(self): """ Extra args are collected from login and used if provided. These are generally not needed but may be used to enable visibility of beta features or set special settings """ return self._params.get("kwargs", {}) @property def entry_points(self): """ Entry points that are bound to this session. Entry points are exposed by the SMC API and provide links to top level resources :rtype: Resource """ if not self._resource: raise SMCConnectionError( "No entry points found, it is likely " "there is no valid login session." ) return self._resource @property def api_version(self): """ Current API Version :rtype: str """ return self._params.get("api_version") @property def session(self): return self._session @property def sock(self): """ get new secure socket from the pool :rtype: SSLSocket """ return self._connpool._get_conn().sock @property def session_id(self): """ The session ID in header type format. Can be inserted into a connection if necessary using:: {'Cookie': session.session_id} :rtype: str """ return ( None if not self.session or "JSESSIONID" not in self.session.cookies else "JSESSIONID={}".format(self.session.cookies["JSESSIONID"]) ) @property def credential(self): # Login credentials return Credential(**{k: self._params.get(k) for k in ("api_key", "login", "pwd")}) @property def url(self): """ The fully qualified SMC URL in use, includes the port number :rtype: str """ return self._params.get("url", "") @property def web_socket_url(self): socket_proto = "wss" if self.is_ssl else "ws" return "{}://{}/{}".format(socket_proto, self.url.split("://")[-1], self.api_version) @property def is_ssl(self): """ Is this an SSL connection :rtype: bool """ return self.url.startswith("https") if self.session else False @property def timeout(self): """ Session timeout in seconds :rtype: int """ return self._params.get("timeout", 30) @property def domain(self): """ Logged in SMC domain :rtype: str """ return "Shared Domain" if not self._params.get("domain") else self._params.get("domain") @property def name(self): """ Return the administrator name for this session. Can be None if the session has not yet been established. .. note:: The administrator name was introduced in SMC version 6.4. Previous versions will show the unique session identifier for this session. :rtype: str """ if self.session: # protect cached property from being set before session try: return self.current_user.name except AttributeError: # TODO: Catch ConnectionError? No session pass except SMCOperationFailure: # Related to recent SMC update. It can failed in case user # does not have Manage Administrator defined in his role. logging.error( "Failed to get username, please make sure you " "can have 'Manage Administrator' in your role" ) return hash(self) @cached_property def current_user(self): """ .. versionadded:: 0.6.0 Requires SMC version >= 6.4 Return the currently logged on API Client user element. :raises UnsupportedEntryPoint: Current user is only supported with SMC version >= 6.4 :rtype: Element """ if self.session: try: response = self.session.get(self.entry_points.get("current_user")) if response.status_code in (200, 201): admin_href = response.json().get("value") request = SMCRequest(href=admin_href) smcresult = send_request(self, "get", request) return ElementFactory(admin_href, smcresult) except UnsupportedEntryPoint: pass def login( self, url=None, api_key=None, login=None, pwd=None, api_version=None, timeout=None, verify=True, alt_filepath=None, domain=None, **kwargs ): """ Login to SMC API and retrieve a valid session. Sessions use a pool connection manager to provide dynamic scalability during times of increased load. Each session is managed by a global session manager making it possible to have more than one session per interpreter. An example login and logout session:: from smc import session session.login(url='http://1.1.1.1:8082', api_key='SomeSMCG3ener@t3dPwd') .....do stuff..... session.logout() :param str url: ip of SMC management server :param str api_key: API key created for api client in SMC :param str login: Administrator user in SMC that has privilege to SMC API. :param str pwd: Password for user login. :param api_version (optional): specify api version :param int timeout: (optional): specify a timeout for initial connect; (default 10) :param str|boolean verify: verify SSL connections using cert (default: verify=True) You can pass verify the path to a CA_BUNDLE file or directory with certificates of trusted CAs :param str alt_filepath: If using .smcrc, alternate path+filename :param str domain: domain to log in to. If domains are not configured, this field will be ignored and api client logged in to 'Shared Domain'. :param bool retry_on_busy: pass as kwarg with boolean if you want to add retries if the SMC returns HTTP 503 error during operation. You can also optionally customize this behavior and call :meth:`.set_retry_on_busy` :return: user session name in SessionManager :rtype: str :raises ConfigLoadError: loading cfg from ~.smcrc fails For SSL connections, you can disable validation of the SMC SSL certificate by setting verify=False, however this is not a recommended practice. If you want to use the SSL certificate generated and used by the SMC API server for validation, set verify='path_to_my_dot_pem'. It is also recommended that your certificate has subjectAltName defined per RFC 2818 If SSL warnings are thrown in debug output, see: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings Logout should be called to remove the session immediately from the SMC server. .. note:: As of SMC 6.4 it is possible to give a standard Administrative user access to the SMC API. It is still possible to use an API Client by providing the api_key in the login call. """ params = {} if not url or (not api_key and not (login and pwd)): try: # First try load from file params = ( load_from_file(alt_filepath) if alt_filepath is not None else load_from_file() ) logger.debug("Read config data from file: %s", params) except ConfigLoadError: # Last ditch effort, try to load from environment params = load_from_environ() logger.debug("Read config data from environ: %s", params) params = params or dict( url=url, api_key=api_key, login=login, pwd=pwd, api_version=api_version, verify=verify, timeout=timeout, domain=domain, kwargs=kwargs or {}, ) # Check to see this session is already logged in. If so, return. # The session object represents a single connection. Log out to # re-use the same session object or get_session() from the # SessionManager to track multiple sessions. if self.manager and (self.session and self in self.manager): logger.info( "An attempt to log in occurred when a session already " "exists, bypassing login for session: %s" % self ) return self._params = {k: v for k, v in params.items() if v is not None} verify_ssl = self._params.get("verify", True) # Determine and set the API version we will use. self._params.update( api_version=get_api_version(self.url, self.api_version, self.timeout, verify_ssl) ) extra_args = self._params.get("kwargs", {}) # Retries configured retry_on_busy = extra_args.pop("retry_on_busy", False) request = self._build_auth_request(verify_ssl, **extra_args) # This will raise if session login fails... self._session = self._get_session(request) self.session.verify = verify_ssl if retry_on_busy: self.set_retry_on_busy() # Load entry points load_entry_points(self) logger.debug( "Login succeeded for admin: %s in domain: %s, session: %s", self.name, self.domain, self.session_id, ) return self.manager._register(self) def __repr__(self): return "Session(name=%s,domain=%s)" % (self.name, self.domain) def _build_auth_request(self, verify=False, **kwargs): """ Build the authentication request to SMC """ json = {"domain": self.domain} credential = self.credential params = {} if credential.provider_name.startswith("lms"): if self.domain: params = dict(login=credential._login, pwd=credential._pwd, domain=self.domain) else: params = dict(login=credential._login, pwd=credential._pwd) else: json.update(authenticationkey=credential._api_key) if kwargs: json.update(**kwargs) # Store in case we need to rebuild later self._extra_args.update(**kwargs) request = dict( url=self.credential.get_provider_entry_point(self.url, self.api_version), json=json, params=params, headers={"content-type": "application/json"}, verify=verify, ) return request def _get_session(self, request): """ Authenticate the request dict :param dict request: request dict built from user input :raises SMCConnectionError: failure to connect :return: python requests session :rtype: requests.Session """ _session = requests.sessions.Session() # empty session retry = Retry( total=MAX_RETRY, read=MAX_RETRY, connect=MAX_RETRY, backoff_factor=0.3, method_whitelist=HTTP_METHODS_SUPPORTING_AUTO_RETRY, status_forcelist=ERROR_CODES_SUPPORTING_AUTO_RETRY, ) adapter = HTTPAdapter(max_retries=retry) ssladapter = SSLAdapter(max_retries=retry) _session.mount("http://", adapter) _session.mount("https://", ssladapter) response = _session.post(**request) logger.info("Using SMC API version: %s", self.api_version) self._connpool = ssladapter.get_connection(request.get("url")) if response.status_code != 200: raise SMCConnectionError( "Login failed, HTTP status code: %s and reason: %s" % (response.status_code, response.reason) ) return _session def logout(self): """ Logout session from SMC :return: None """ if not self.session: self.manager._deregister(self) return try: r = self.session.put(self.entry_points.get("logout")) if r.status_code == 204: logger.info( "Logged out admin: %s of domain: %s successfully", self.name, self.domain ) else: logger.error( "Logout status was unexpected. Received response " "with status code: %s", (r.status_code), ) except requests.exceptions.SSLError as e: logger.error("SSL exception thrown during logout: %s", e) except requests.exceptions.ConnectionError as e: logger.error("Connection error on logout: %s", e) finally: self.entry_points.clear() self.manager._deregister(self) requests.sessions.session().close() try: delattr(self, "current_user") except AttributeError: pass logger.debug("Call counters: %s" % counters) def refresh(self): """ Refresh session on 401. This is called automatically if your existing session times out and resends the operation/s which returned the error. :raises SMCConnectionError: Problem re-authenticating using existing api credentials """ if self.session and self.name: # Did session timeout? logger.info( "Session timed out, will try obtaining a new session using " "previously saved credential information." ) self.logout() # Force log out session just in case self.login(**self.copy()) if self.session: return raise SMCConnectionError("Session expired and attempted refresh failed.") def switch_domain(self, domain): """ Switch from one domain to another. You can call session.login() with a domain key value to log directly into the domain of choice or alternatively switch from domain to domain. The user must have permissions to the domain or unauthorized will be returned. In addition, when switching domains, you will be logged out of the current domain to close the connection pool associated with the previous session. This prevents potentially excessive open connections to SMC :: session.login() # Log in to 'Shared Domain' ... session.switch_domain('MyDomain') :raises SMCConnectionError: Error logging in to specified domain. This typically means the domain either doesn't exist or the user does not have privileges to that domain. """ if self.domain != domain: if self in self.manager: # Exit current domain self.logout() logger.info("Switching to domain: %r and creating new session", domain) params = self.copy() params.update(domain=domain) self.login(**params) def set_retry_on_busy(self, total=5, backoff_factor=0.1, status_forcelist=None, **kwargs): """ Mount a custom retry object on the current session that allows service level retries when the SMC might reply with a Service Unavailable (503) message. This can be possible in larger environments with higher database activity. You can all this on the existing session, or provide as a dict to the login constructor. :param int total: total retries :param float backoff_factor: when to retry :param list status_forcelist: list of HTTP error codes to retry on :param list method_whitelist: list of methods to apply retries for, GET, POST and PUT by default :return: None """ if self.session: from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry method_whitelist = kwargs.pop("method_whitelist", []) or ["GET", "POST", "PUT"] status_forcelist = frozenset(status_forcelist) if status_forcelist else frozenset([503]) retry = Retry( total=total, backoff_factor=backoff_factor, status_forcelist=status_forcelist, method_whitelist=method_whitelist, ) for proto_str in ("http://", "https://"): self.session.mount(proto_str, HTTPAdapter(max_retries=retry)) logger.debug("Mounting retry object to HTTP session: %s" % retry) def copy(self): # Copy the relevant parameters to make another session login # using the existing information params = copy.copy(self._params) kwargs = params.pop("kwargs", {}) params.update(**kwargs) return params def _get_log_schema(self): """ Get the log schema for this SMC version. :return: dict """ if self.session and self.session_id: schema = "{}/{}/monitoring/log/schemas".format(self.url, self.api_version) response = self.session.get( url=schema, headers={"cookie": self.session_id, "content-type": "application/json"} ) if response.status_code in (200, 201): return response.json() class Credential(object): """ Provider for authenticating the user. LMS Login is a user created within the SMC as a normal administrative account. Login is the standard way of using an API client and key as password. The key of the CredentialMap also indicates the entry point for which to POST the authentication. """ CredentialMap = {"lms_login": ("login", "pwd"), "login": ("api_key",)} def __init__(self, api_key=None, login=None, pwd=None): self._api_key = api_key self._login = login self._pwd = pwd @property def provider_name(self): return "login" if self._api_key else "lms_login" def get_provider_entry_point(self, url, api_version): return "{url}/{api_version}/{provider_name}".format( url=url, api_version=api_version, provider_name=self.provider_name ) @property def has_credentials(self): """ Does this session have valid credentials :rtype: bool """ return all( [ getattr(self, "_%s" % field, None) is not None for field in self.CredentialMap.get(self.provider_name) ] ) def load_entry_points(self): try: r = self.session.get( "{url}/{api_version}/api".format(url=self.url, api_version=self.api_version) ) if r.status_code == 200: result_list = json.loads(r.text) self._resource = Resource(result_list["entry_point"]) logger.debug("Loaded entry points with obtained session.") else: raise SMCConnectionError( "Invalid status received while getting entry points from SMC. " "Status code received %s. Reason: %s" % (r.status_code, r.reason) ) except requests.exceptions.RequestException as e: raise SMCConnectionError(e) def available_api_versions(base_url, timeout=10, verify=True): """ Get all available API versions for this SMC :return version numbers :rtype: list """ try: r = requests.get("%s/api" % base_url, timeout=timeout, verify=verify) # no session required if r.status_code == 200: j = json.loads(r.text) versions = [] for version in j["version"]: versions.append(version["rel"]) return versions raise SMCConnectionError( "Invalid status received while getting entry points from SMC. " "Status code received %s. Reason: %s" % (r.status_code, r.reason) ) except requests.exceptions.RequestException as e: raise SMCConnectionError(e) def get_api_version(base_url, api_version=None, timeout=10, verify=True): """ Get the API version specified or resolve the latest version :return api version :rtype: float """ versions = available_api_versions(base_url, timeout, verify) # search min and max versions min_version = "99.99" max_version = "0.0" for i in versions: major, minor = str(i).split(".") major_max, minor_max = str(max_version).split(".") major_min, minor_min = str(min_version).split(".") if (int(major) == int(major_max) and int(minor) > int(minor_max))\ or (int(major) > int(major_max)): max_version = major + "." + minor if int(major) <= int(major_min) and int(minor) < int(minor_min): min_version = major + "." + minor newest_version = max_version major_newest, minor_newest = str(newest_version).split(".") if int(major_newest) <= 6 and int(minor_newest) <= 5: best_version = newest_version else: best_version = min_version if api_version is None: api_version = best_version else: if api_version not in versions: api_version = best_version return api_version
PypiClean
/JumpScale-core-6.0.0.tar.gz/JumpScale-core-6.0.0/lib/JumpScale/baselib/lrucache/LRUCache.py
# Copyright 2004 Evan Prodromou <evan@bad.dynu.ca> # Licensed under the Academic Free License 2.1 # arch-tag: LRU cache main module """a simple LRU (Least-Recently-Used) cache module This module provides very simple LRU (Least-Recently-Used) cache functionality. An *in-memory cache* is useful for storing the results of an 'expensive' process (one that takes a lot of time or resources) for later re-use. Typical examples are accessing data from the filesystem, a database, or a network location. If you know you'll need to re-read the data again, it can help to keep it in a cache. You *can* use a Python dictionary as a cache for some purposes. However, if the results you're caching are large, or you have a lot of possible results, this can be impractical memory-wise. An *LRU cache*, on the other hand, only keeps _some_ of the results in memory, which keeps you from overusing resources. The cache is bounded by a maximum size; if you try to add more values to the cache, it will automatically discard the values that you haven't read or written to in the longest time. In other words, the least-recently-used items are discarded. [1]_ .. [1]: 'Discarded' here means 'removed from the cache'. """ from __future__ import generators import time from heapq import heappush, heappop, heapify __version__ = "0.2" __all__ = ['CacheKeyError', 'LRUCache', 'DEFAULT_SIZE'] __docformat__ = 'reStructuredText en' DEFAULT_SIZE = 16 """Default size of a new LRUCache object, if no 'size' argument is given.""" class CacheKeyError(KeyError): """Error raised when cache requests fail When a cache record is accessed which no longer exists (or never did), this error is raised. To avoid it, you may want to check for the existence of a cache record before reading or deleting it.""" pass class LRUCache(object): class __Node(object): """Record of a cached value. Not for public consumption.""" def __init__(self, key, obj, timestamp): object.__init__(self) self.key = key self.obj = obj self.atime = timestamp self.mtime = self.atime def __cmp__(self, other): return cmp(self.atime, other.atime) def __repr__(self): return "<%s %s => %s (%s)>" % \ (self.__class__, self.key, self.obj, \ time.asctime(time.localtime(self.atime))) def __init__(self, size=DEFAULT_SIZE): # Check arguments if size <= 0: raise ValueError, size elif type(size) is not type(0): raise TypeError, size object.__init__(self) self.__heap = [] self.__dict = {} self.size = size """Maximum size of the cache. If more than 'size' elements are added to the cache, the least-recently-used ones will be discarded.""" def __len__(self): return len(self.__heap) def __contains__(self, key): return self.__dict.has_key(key) def __setitem__(self, key, obj): if self.__dict.has_key(key): node = self.__dict[key] node.obj = obj node.atime = time.time() node.mtime = node.atime heapify(self.__heap) else: # size may have been reset, so we loop while len(self.__heap) >= self.size: lru = heappop(self.__heap) del self.__dict[lru.key] node = self.__Node(key, obj, time.time()) self.__dict[key] = node heappush(self.__heap, node) def __getitem__(self, key): if not self.__dict.has_key(key): raise CacheKeyError(key) else: node = self.__dict[key] node.atime = time.time() heapify(self.__heap) return node.obj def __delitem__(self, key): if not self.__dict.has_key(key): raise CacheKeyError(key) else: node = self.__dict[key] del self.__dict[key] self.__heap.remove(node) heapify(self.__heap) return node.obj def __iter__(self): copy = self.__heap[:] while len(copy) > 0: node = heappop(copy) yield node.key raise StopIteration def __setattr__(self, name, value): object.__setattr__(self, name, value) # automagically shrink heap on resize if name == 'size': while len(self.__heap) > value: lru = heappop(self.__heap) del self.__dict[lru.key] def __repr__(self): return "<%s (%d elements)>" % (str(self.__class__), len(self.__heap)) def mtime(self, key): """Return the last modification time for the cache record with key. May be useful for cache instances where the stored values can get 'stale', such as caching file or network resource contents.""" if not self.__dict.has_key(key): raise CacheKeyError(key) else: node = self.__dict[key] return node.mtime if __name__ == "__main__": cache = LRUCache(25) print cache for i in range(50): cache[i] = str(i) print cache if 46 in cache: del cache[46] print cache cache.size = 10 print cache cache[46] = '46' print cache print len(cache) for c in cache: print c print cache print cache.mtime(46) for c in cache: print c
PypiClean
/Guerilla-1.0.2.tar.gz/Guerilla-1.0.2/guerilla/players.py
import chess import random import chess.uci from abc import ABCMeta, abstractmethod import guerilla.data_handler as dh from guerilla.play.neural_net import NeuralNet from guerilla.play.search import Minimax, IterativeDeepening class Player: __metaclass__ = ABCMeta def __init__(self, name): """ Initializes the Player abstract class. Input: name [String] Name of the player. """ self.name = name @property def colour(self): return self._colour @colour.setter def colour(self, colour): if colour.lower() in ['white', 'w']: self._colour = 'white' elif colour.lower() in ['black', 'b']: self._colour = 'black' else: raise ValueError("Error: Invalid colour! Must be 'white','w','black', or 'b'.") @abstractmethod def __enter__(self): raise NotImplementedError("You should never see this") @abstractmethod def __exit__(self, e_type, value, traceback): raise NotImplementedError("You should never see this") @abstractmethod def get_move(self, board): """ Gets the next move from a player given the current board. Input: Board [chess.Board] Output: Move [chess.Move] """ raise NotImplementedError("You should never see this") def new_game(self): """ Let's the player know that a new game is being played. Output: None. """ pass class Guerilla(Player): search_types = { "minimax": Minimax, "iterativedeepening": IterativeDeepening } def __init__(self, name, colour=None, search_type='minimax', load_file=None, hp_load_file=None, seed=None, verbose=True, nn_params=None, search_params=None): super(Guerilla, self).__init__(name) self.nn = NeuralNet(load_file=load_file, hp_load_file=hp_load_file, seed=seed, verbose=verbose, hp=nn_params) search_params = {} if search_params is None else search_params self.search = Guerilla.search_types[search_type](self.nn.evaluate, **search_params) def __enter__(self): self.nn.start_session() self.nn.init_graph() return self def __exit__(self, e_type, value, traceback): if e_type is not None: print e_type, value, traceback self.nn.close_session() self.nn.reset_graph() def get_move(self, board): # print "Guerilla is thinking..." score, move, leaf = self.search.run(board) if move is None: raise ValueError("There are no valid moves from this position! FEN: %s " "\n\t Debug Info: Score: %f Move: %s Leaf Board: %s" % ( board.fen(), score, str(move), leaf)) return move def get_cp_adv_white(self, fen): """ Returns the centipawn advantage of white given the current fen. Input: fen [String] FEN. Output: centipawn advantage [Float] Centipawn advantage of white. """ if dh.white_is_next(fen): return self.nn.evaluate(fen) else: # Black plays next return -self.nn.evaluate(dh.flip_board(fen)) def get_cp_adv_black(self, fen): """ Returns the centipawn advantage of black given the current fen. Input: fen [String] FEN. Output: centipawn advantage [Float] Centipawn advantage of black. """ return -self.get_cp_adv_white(fen) class Human(Player): def __init__(self, name, colour=None): super(Human, self).__init__(name) def __enter__(self): return self def __exit__(self, e_type, value, traceback): if e_type is not None: print e_type, value, traceback def get_move_from_tml(self, board): move = None while True: print "Please enter your move %s (? for help):" % self.name usr_input = raw_input().lower() if usr_input == '?': print "Input move must be in algebraic notation (i.e. a2a3). \nOther commands" print "\t?\tDisplay help (this text).\n\tl\tPrint legal moves.\n\tr\tPlay a random (legal) move." elif usr_input == 'l': print "Legal Moves: " + ', '.join([str(x) for x in board.legal_moves]) elif usr_input == 'r': move = random.sample(board.legal_moves, 1)[0] break elif usr_input in [str(x) for x in board.legal_moves]: move = chess.Move.from_uci(usr_input) break else: print "Invalid or illegal input, legal moves are: " + ', '.join([str(x) for x in board.legal_moves]) return move def get_move(self, board): """ Fetches a move from the command line. Input: Board [Chess.board] """ return self.get_move_from_tml(board) class Stockfish(Player): def __init__(self, name, colour=None, time_limit=2): """ Initializes the Stockfish class. Input: time_limit [Integer] The time limit for each move search in SECONDS. """ super(Stockfish, self).__init__(name) self.time_limit = time_limit * 1000 # convert to milliseconds # Setup chess engine self.engine = chess.uci.popen_engine('stockfish') self.engine.uci() self.new_game() def __enter__(self): return self def __exit__(self, e_type, value, traceback): if e_type is not None: print e_type, value, traceback def get_move(self, board): self.engine.position(board) move, _ = self.engine.go(movetime=self.time_limit) return move def new_game(self): self.engine.ucinewgame() pass def main(): # test with Guerilla('Harambe', search_type='iterativedeepening', search_params={'time_limit': 5}, load_file='6811.p') as g: board = chess.Board() print g.get_move(board) print "HIT: {} MISS: {} DEPTH REACHED: {}".format(g.search.tt.cache_hit, g.search.tt.cache_miss, g.search.depth_reached) if __name__ == '__main__': main()
PypiClean
/GsuiteToMd-1.3.0.tar.gz/GsuiteToMd-1.3.0/docs/build/html/_static/doctools.js
* select a different prefix for underscore */ $u = _.noConflict(); /** * make the code below compatible with browsers without * an installed firebug like debugger if (!window.console || !console.firebug) { var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; window.console = {}; for (var i = 0; i < names.length; ++i) window.console[names[i]] = function() {}; } */ /** * small helper function to urldecode strings */ jQuery.urldecode = function(x) { return decodeURIComponent(x).replace(/\+/g, ' '); }; /** * small helper function to urlencode strings */ jQuery.urlencode = encodeURIComponent; /** * This function returns the parsed url parameters of the * current request. Multiple values per key are supported, * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; for (var i = 0; i < parts.length; i++) { var tmp = parts[i].split('=', 2); var key = jQuery.urldecode(tmp[0]); var value = jQuery.urldecode(tmp[1]); if (key in result) result[key].push(value); else result[key] = [value]; } return result; }; /** * highlight a given string on a jquery object by wrapping it in * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { function highlight(node, addItems) { if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className) && !jQuery(node.parentNode).hasClass("nohighlight")) { var span; var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); if (isInSVG) { span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); } else { span = document.createElement("span"); span.className = className; } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); if (isInSVG) { var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); var bbox = node.parentElement.getBBox(); rect.x.baseVal.value = bbox.x; rect.y.baseVal.value = bbox.y; rect.width.baseVal.value = bbox.width; rect.height.baseVal.value = bbox.height; rect.setAttribute('class', className); addItems.push({ "parent": node.parentNode, "target": rect}); } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { highlight(this, addItems); }); } } var addItems = []; var result = this.each(function() { highlight(this, addItems); }); for (var i = 0; i < addItems.length; ++i) { jQuery(addItems[i].parent).before(addItems[i].target); } return result; }; /* * backward compatibility for jQuery.browser * This will be supported until firefox bug is fixed. */ if (!jQuery.browser) { jQuery.uaMatch = function(ua) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; jQuery.browser = {}; jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true; } /** * Small JavaScript module for the documentation. */ var Documentation = { init : function() { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { this.initOnKeyListeners(); } }, /** * i18n support */ TRANSLATIONS : {}, PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; if (typeof translated === 'undefined') return string; return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, addTranslations : function(catalog) { for (var key in catalog.messages) this.TRANSLATIONS[key] = catalog.messages[key]; this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); this.LOCALE = catalog.locale; }, /** * add context elements like header anchor links */ addContextElements : function() { $('div[id] > :header:first').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this headline')). appendTo(this); }); $('dt[id]').each(function() { $('<a class="headerlink">\u00B6</a>'). attr('href', '#' + this.id). attr('title', _('Permalink to this definition')). appendTo(this); }); }, /** * workaround a firefox stupidity * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); }, /** * highlight the search words provided in the url in the text */ highlightSearchWords : function() { var params = $.getQueryParameters(); var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; if (terms.length) { var body = $('div.body'); if (!body.length) { body = $('body'); } window.setTimeout(function() { $.each(terms, function() { body.highlightText(this.toLowerCase(), 'highlighted'); }); }, 10); $('<p class="highlight-link"><a href="javascript:Documentation.' + 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>') .appendTo($('#searchbox')); } }, /** * init the domain index toggle buttons */ initIndexTable : function() { var togglers = $('img.toggler').click(function() { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); }).css('display', ''); if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { togglers.click(); } }, /** * helper function to hide the search marks again */ hideSearchWords : function() { $('#searchbox .highlight-link').fadeOut(300); $('span.highlighted').removeClass('highlighted'); }, /** * make the url absolute */ makeURL : function(relativeURL) { return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; }, /** * get the current relative url */ getCurrentURL : function() { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); }, initOnKeyListeners: function() { $(document).keydown(function(event) { var activeElementType = document.activeElement.tagName; // don't navigate when in search box, textarea, dropdown or button if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey && !event.shiftKey) { switch (event.keyCode) { case 37: // left var prevHref = $('link[rel="prev"]').prop('href'); if (prevHref) { window.location.href = prevHref; return false; } case 39: // right var nextHref = $('link[rel="next"]').prop('href'); if (nextHref) { window.location.href = nextHref; return false; } } } }); } }; // quick alias for translations _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); });
PypiClean
/ClickSQL-0.1.9.4.tar.gz/ClickSQL-0.1.9.4/README.md
# ClickSQL: ClickHouse client for Humans [![CodeQL](https://github.com/sn0wfree/ClickSQL/actions/workflows/codeql-analysis.yml/badge.svg?branch=master)](https://github.com/sn0wfree/ClickSQL/actions/workflows/codeql-analysis.yml) [![Python package](https://github.com/sn0wfree/ClickSQL/actions/workflows/python-package.yml/badge.svg?branch=master)](https://github.com/sn0wfree/ClickSQL/actions/workflows/python-package.yml) -------------- Package information: ClickSQL is a python client for ClickHouse database, which may help users to use ClickHouse more easier and pythonic. More information for ClickHouse can be found at [here](http://clickhouse.tech) ## Installation `pip install ClickSQL` ## Usage ### Initial connection to setup a database connection and send a heartbeat-check signal ```python from ClickSQL import BaseSingleFactorTableNode conn_str = "clickhouse://default:test121231@99.99.9.9:8123/system" Node = BaseSingleFactorTableNode(conn_str) >>> connection test: Ok. ``` ### Query #### execute a SQL Query ```python from ClickSQL import BaseSingleFactorTableNode conn_str = "clickhouse://default:test121231@99.99.9.9:8123/system" Node = BaseSingleFactorTableNode(conn_str) Node('show tables from system limit 1') >>> connection test: Ok. >>> name >>> 0 aggregate_function_combinators ``` #### execute a Query without SQL ```python from ClickSQL import BaseSingleFactorTableNode factor = BaseSingleFactorTableNode( 'clickhouse://default:default@127.0.0.1:8123/sample.sample', cols=['cust_no', 'product_id', 'money'], order_by_cols=['money asc'], money='money >= 100000' ) factor['money'].head(10) >>> connection test: Ok. >>> money >>> 0 1000000.0 >>> 1 1000000.0 >>> 2 1000000.0 >>> 3 1000000.0 >>> 4 1000000.0 >>> 5 1000000.0 >>> 6 1000000.0 >>> 7 1000000.0 >>> 8 1000000.0 >>> 9 1000000.0 ``` ## Insert data insert data into database by various ways ### Insert data via DataFrame ```python from ClickSQL import BaseSingleFactorTableNode as factortable import numpy as np import pandas as pd factor = factortable( 'clickhouse://default:default@127.0.0.1:8123/sample.sample' ) db = 'sample' table = 'sample' df = pd.DataFrame(np.random.random(size=(10000,3)),columns=['cust_no', 'product_id', 'money']) factor.insert_df(df, db, table, chunksize=100000) ``` ### Insert data via SQL(Inner) ```python from ClickSQL import BaseSingleFactorTableNode as factortable factor = factortable( 'clickhouse://default:default@127.0.0.1:8123/sample.sample' ) factor("insert into sample.sample select * from other_db.other_table") ``` ### Create table #### Create table by SQL ```python from ClickSQL import BaseSingleFactorTableNode conn_str = "clickhouse://default:test121231@99.99.9.9:8123/system" Node = BaseSingleFactorTableNode(conn_str) Node('create table test.test2 (v1 String, v2 Int64, v3 Float64,v4 DataTime) Engine=MergeTree() order by v4') ``` #### Create table by DataFrame ```python from ClickSQL import BaseSingleFactorTableNode import numpy as np import pandas as pd conn_str = "clickhouse://default:test121231@99.99.9.9:8123/system" Node = BaseSingleFactorTableNode(conn_str) db = 'test' table = 'test2' df_or_sql_or_dict = pd.DataFrame(np.random.random(size=(10000,2)),columns=['v1', 'v3']) df_or_sql_or_dict['v2'] =1 df_or_sql_or_dict['v4'] =pd.to_datetime('2020-01-01 00:00:00') Node.create( db, table, df_or_sql_or_dict, key_cols=['v4'],) ``` ### Contribution Welcome to improve this package or submit an issue or any others ## Author sn0wfree # Plan ## Available functions or properties 1. get data from clickhouse 2. insert data into clickhouse 3. create 4. alter 5. execute standard SQL and transform into DataFrame(Auto) 3. able to execute select query 4. able to execute insert query 5. no require clickhouse-client 6. auto create table sql 7. can execute explain query 8. Insert Data via DataFrame 3. alter function & drop function ## In Process 2. create a pandas_liked executable function, which can compatible with pandas 9. distributed query(query+insert) ## schedule 1. ORM 4. can execute user role query 5. create analysis component 6. auto report system 7. table register system 8. data manager system 8. meta data manager
PypiClean
/Nano-Assault-1.0.tar.gz/Nano-Assault-1.0/nanoassault/levels.py
# (C) 2017, Eike Jesinghaus # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from .collectibles import Energy from .enemies import CoccusDesertus, CoccusIactans, CoccusImmanis, BacillusCeler from .level import Level class LevelStart(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), (), keylevel) class LevelCDCorner(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((CoccusDesertus, (2, 2)), (CoccusDesertus, (13, 2)), (CoccusDesertus, (2, 9)), (CoccusDesertus, (13, 9))), keylevel) class LevelCIMid(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((CoccusIactans, (7.5, 5.5)),), keylevel) class LevelCITwo(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((CoccusIactans, (6, 5)), (CoccusIactans, (9, 5))), keylevel) class LevelCICD(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((CoccusDesertus, (4, 4)), (CoccusDesertus, (11, 4)), (CoccusDesertus, (4, 7)), (CoccusDesertus, (11, 7)), (CoccusIactans, (7.5, 5.5))), keylevel, Energy((7.5, 5.5))) class LevelBossCI(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((CoccusImmanis, (7, 5)),), keylevel) class LevelBC(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((BacillusCeler, (7, 5)),), keylevel) class LevelBCCD(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((BacillusCeler, (7, 5)), (CoccusDesertus, (8, 5))), keylevel) class LevelBCThree(Level): def __init__(self, theme, keylevel): Level.__init__(self, theme, (), ((BacillusCeler, (5, 5)), (BacillusCeler, (7, 5)), (BacillusCeler, (9, 5))), keylevel) ALL_LEVELS = [] BOSS_LEVELS = [] for i in Level.__subclasses__(): if i.__name__.startswith("LevelBoss"): BOSS_LEVELS.append(i) else: ALL_LEVELS.append(i)
PypiClean
/Django_CryptographicFields-2.1.0-py3-none-any.whl/CryptographicFields/fields.py
from typing import Any from django.db import models from django.core import exceptions, validators from django.db.models.fields import PositiveIntegerRelDbTypeMixin from .cryptography import encrypt, decrypt from ast import literal_eval import datetime from django import forms from django.utils import timezone from uuid import UUID from django.utils.translation import gettext_lazy as _ from django.db.models.lookups import StartsWith as StartWith, FieldGetDbPrepValueMixin """ to_python() make validations & checks type of the data get_db_prep_value() encrypts the data from_db_value() decrypts the data returned from the db pre_save() generates date ,datetime,time for the respestive fields get_db_prep_save() saves the value into db """ class StartsWith(FieldGetDbPrepValueMixin, StartWith): pass class CharField(models.CharField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return decrypt(value) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class BooleanField(models.BooleanField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return literal_eval(decrypt(value)) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class DateField(models.DateField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return encrypt(connection.ops.adapt_datefield_value(value)) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: try: return datetime.date.fromisoformat(decrypt(value)) except AttributeError: from timestring import Date return Date(decrypt(value)).date.date() def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class DateTimeField(models.DateTimeField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return super().get_prep_value(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return encrypt(connection.ops.adapt_datetimefield_value(value)) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: try: return datetime.datetime.fromisoformat(decrypt(value)) except AttributeError: from timestring import Date return Date(decrypt(value)).date def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class TimeField(models.TimeField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return encrypt(connection.ops.adapt_timefield_value(value)) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: try: return datetime.time.fromisoformat(decrypt(value)) except AttributeError: from timestring import Date return Date(decrypt(value)).date.time() def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class DecimalField(models.DecimalField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return super().to_python(value) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def get_db_prep_save(self, value, connection,): return encrypt(connection.ops.adapt_decimalfield_value(self.get_prep_value(value), self.max_digits, self.decimal_places)) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return float(decrypt(value)) # return value def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault('max_length', 254) super().__init__(*args, **kwargs) def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield(**{ 'form_class': forms.EmailField, **kwargs, }) class FloatField(models.FloatField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return float(decrypt(value)) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class IntegerField(models.IntegerField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return int(decrypt(value)) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class BigIntegerField(IntegerField): error_messages = { 'invalid': _('“%(value)s” value must be less than %(max) & greater than %(min).'), } description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def to_python(self, value: Any) -> Any: value = self.clean(super().to_python(value), None) if value < (-self.MAX_BIGINT-1) or value > self.MAX_BIGINT: raise exceptions.ValidationError(self.error_messages['invalid'], code='invalid', params={'value': value, 'max': self.MAX_BIGINT, 'min': (-self.MAX_BIGINT-1)}) return value def formfield(self, **kwargs): return super().formfield(**{ 'min_value': -self.MAX_BIGINT - 1, 'max_value': self.MAX_BIGINT, **kwargs, }) class GenericIPAddressField(models.GenericIPAddressField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(connection.ops.adapt_ipaddressfield_value(value)) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return decrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _('Positive big integer') error_messages = { 'invalid': _('“%(value)s” value must be less than greater than %(min).'), } def to_python(self, value: Any) -> Any: value = self.clean(super().to_python(value), None) if value < 0: raise exceptions.ValidationError(self.error_messages['invalid'], code='invalid', params={'value': value, 'min': 0}) return value def formfield(self, **kwargs): return super().formfield(**{ 'min_value': 0, **kwargs, }) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") error_messages = { 'invalid': _('“%(value)s” value must be less than greater than %(min).'), } def to_python(self, value: Any) -> Any: value = self.clean(super().to_python(value), None) if value < 0: raise exceptions.ValidationError(self.error_messages['invalid'], code='invalid', params={'value': value, 'min': 0}) return value def formfield(self, **kwargs): return super().formfield(**{ 'min_value': 0, **kwargs, }) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive small integer") error_messages = { 'invalid': _('“%(value)s” value must be less than greater than %(min).'), } def to_python(self, value: Any) -> Any: value = self.clean(super().to_python(value), None) if value < 0: raise exceptions.ValidationError(self.error_messages['invalid'], code='invalid', params={'value': value, 'min': 0}) return value def formfield(self, **kwargs): return super().formfield(**{ 'min_value': 0, **kwargs, }) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__(self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs['max_length'] if self.db_index is False: kwargs['db_index'] = False else: del kwargs['db_index'] if self.allow_unicode is not False: kwargs['allow_unicode'] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield(**{ 'form_class': forms.SlugField, 'allow_unicode': self.allow_unicode, **kwargs, }) class SmallIntegerField(IntegerField): description = _("Small integer") class TextField(models.TextField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return decrypt(value) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault('max_length', 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs['max_length'] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield(**{ 'form_class': forms.URLField, **kwargs, }) class BinaryField(models.BinaryField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: if isinstance(value, str): value = bytes(value, "UTF-8") elif isinstance(value, memoryview): value = bytes(value) value = self.clean(value, None) return value def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return bytes.fromhex(decrypt(value)) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(bytes(connection.Database.Binary(value)).hex()) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class UUIDField(models.UUIDField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return UUID(hex=decrypt(value)) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value.hex) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value class FilePathField(models.FilePathField): def get_internal_type(self) -> str: return "TextField" def to_python(self, value: Any) -> Any: return self.clean(super().to_python(value), None) def get_prep_value(self, value: Any) -> Any: return self.to_python(value) def from_db_value(self, value: Any, expression: Any, connection: Any) -> Any: return decrypt(value) def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return encrypt(value) def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ self.validate(value, model_instance) self.run_validators(value) return value CharField.register_lookup(StartsWith) BooleanField.register_lookup(StartsWith) DateField.register_lookup(StartsWith) DateTimeField.register_lookup(StartsWith) EmailField.register_lookup(StartsWith) GenericIPAddressField.register_lookup(StartsWith) SlugField.register_lookup(StartsWith) TextField.register_lookup(StartsWith) URLField.register_lookup(StartsWith) BinaryField.register_lookup(StartsWith) UUIDField.register_lookup(StartsWith) FilePathField.register_lookup(StartsWith) DateField.register_lookup(StartsWith, lookup_name="date") DateTimeField.register_lookup(StartsWith, lookup_name="date") TimeField.register_lookup(StartsWith, lookup_name="time")
PypiClean
/Cubane-1.0.11.tar.gz/Cubane-1.0.11/cubane/lib/ucsv.py
from __future__ import unicode_literals from cubane.lib.utf8 import get_file_encoding, write_file_encoding import csv ; from csv import * import codecs import cStringIO __version__ = '1.0 Unicode' __dropins__ = ['reader', 'writer'] class UTF8Recoder: """ Iterator that reads a stream encoded in the given encoding. The output is re-encoded to UTF-8 for internal consistency. """ def __init__(self, f, encoding): self.reader = codecs.getreader(encoding)(f) def __iter__(self): return self def next(self): chunk = self.reader.next() chunk = chunk.encode('utf-8') return chunk class reader: """ A CSV reader which will iterate over lines in the CSV file 'f', from content in the optional encoding. """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds): # try to read BOM if available bom, encoding = get_file_encoding(f, encoding) # open csv reader f = UTF8Recoder(f, encoding) self.reader = csv.reader(f, dialect=dialect, **kwds) def value(self, s): try: return int(s) except: pass try: return float(s) except: pass return unicode(s, 'utf-8') def next(self): row = self.reader.next() return [self.value(s) for s in row] def __iter__(self): return self class writer: """ A CSV writer which will write rows to CSV file 'f', employing the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding='utf-8', **kwds): self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.lookup(encoding)[-1](f, 'ignore') # write byte order mark for UTF encodings write_file_encoding(self.stream, encoding) def writerow(self, row): self.writer.writerow([(u'%s'%s).encode('utf-8') for s in row]) # fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode('utf-8') # ... and reencode it into the target encoding self.encoder.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row)
PypiClean
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/lib/scons-2.3.2/SCons/Platform/win32.py
__revision__ = "src/engine/SCons/Platform/win32.py 2014/07/05 09:42:21 garyo" import os import os.path import sys import tempfile from SCons.Platform.posix import exitvalmap from SCons.Platform import TempFileMunge import SCons.Util try: import msvcrt import win32api import win32con msvcrt.get_osfhandle win32api.SetHandleInformation win32con.HANDLE_FLAG_INHERIT except ImportError: parallel_msg = \ "you do not seem to have the pywin32 extensions installed;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." except AttributeError: parallel_msg = \ "your pywin32 extensions do not support file handle operations;\n" + \ "\tparallel (-j) builds may not work reliably with open Python files." else: parallel_msg = None import builtins _builtin_file = builtins.file _builtin_open = builtins.open class _scons_file(_builtin_file): def __init__(self, *args, **kw): _builtin_file.__init__(self, *args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(self.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) def _scons_open(*args, **kw): fp = _builtin_open(*args, **kw) win32api.SetHandleInformation(msvcrt.get_osfhandle(fp.fileno()), win32con.HANDLE_FLAG_INHERIT, 0) return fp builtins.file = _scons_file builtins.open = _scons_open try: import threading spawn_lock = threading.Lock() # This locked version of spawnve works around a Windows # MSVCRT bug, because its spawnve is not thread-safe. # Without this, python can randomly crash while using -jN. # See the python bug at http://bugs.python.org/issue6476 # and SCons issue at # http://scons.tigris.org/issues/show_bug.cgi?id=2449 def spawnve(mode, file, args, env): spawn_lock.acquire() try: if mode == os.P_WAIT: ret = os.spawnve(os.P_NOWAIT, file, args, env) else: ret = os.spawnve(mode, file, args, env) finally: spawn_lock.release() if mode == os.P_WAIT: pid, status = os.waitpid(ret, 0) ret = status >> 8 return ret except ImportError: # Use the unsafe method of spawnve. # Please, don't try to optimize this try-except block # away by assuming that the threading module is always present. # In the test test/option-j.py we intentionally call SCons with # a fake threading.py that raises an import exception right away, # simulating a non-existent package. def spawnve(mode, file, args, env): return os.spawnve(mode, file, args, env) # The upshot of all this is that, if you are using Python 1.5.2, # you had better have cmd or command.com in your PATH when you run # scons. def piped_spawn(sh, escape, cmd, args, env, stdout, stderr): # There is no direct way to do that in python. What we do # here should work for most cases: # In case stdout (stderr) is not redirected to a file, # we redirect it into a temporary file tmpFileStdout # (tmpFileStderr) and copy the contents of this file # to stdout (stderr) given in the argument if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 else: # one temporary file for stdout and stderr tmpFileStdout = os.path.normpath(tempfile.mktemp()) tmpFileStderr = os.path.normpath(tempfile.mktemp()) # check if output is redirected stdoutRedirected = 0 stderrRedirected = 0 for arg in args: # are there more possibilities to redirect stdout ? if (arg.find( ">", 0, 1 ) != -1 or arg.find( "1>", 0, 2 ) != -1): stdoutRedirected = 1 # are there more possibilities to redirect stderr ? if arg.find( "2>", 0, 2 ) != -1: stderrRedirected = 1 # redirect output of non-redirected streams to our tempfiles if stdoutRedirected == 0: args.append(">" + str(tmpFileStdout)) if stderrRedirected == 0: args.append("2>" + str(tmpFileStderr)) # actually do the spawn try: args = [sh, '/C', escape(' '.join(args)) ] ret = spawnve(os.P_WAIT, sh, args, env) except OSError, e: # catch any error try: ret = exitvalmap[e[0]] except KeyError: sys.stderr.write("scons: unknown OSError exception code %d - %s: %s\n" % (e[0], cmd, e[1])) if stderr is not None: stderr.write("scons: %s: %s\n" % (cmd, e[1])) # copy child output from tempfiles to our streams # and do clean up stuff if stdout is not None and stdoutRedirected == 0: try: stdout.write(open( tmpFileStdout, "r" ).read()) os.remove( tmpFileStdout ) except (IOError, OSError): pass if stderr is not None and stderrRedirected == 0: try: stderr.write(open( tmpFileStderr, "r" ).read()) os.remove( tmpFileStderr ) except (IOError, OSError): pass return ret def exec_spawn(l, env): try: result = spawnve(os.P_WAIT, l[0], l, env) except OSError, e: try: result = exitvalmap[e[0]] sys.stderr.write("scons: %s: %s\n" % (l[0], e[1])) except KeyError: result = 127 if len(l) > 2: if len(l[2]) < 1000: command = ' '.join(l[0:3]) else: command = l[0] else: command = l[0] sys.stderr.write("scons: unknown OSError exception code %d - '%s': %s\n" % (e[0], command, e[1])) return result def spawn(sh, escape, cmd, args, env): if not sh: sys.stderr.write("scons: Could not find command interpreter, is it in your PATH?\n") return 127 return exec_spawn([sh, '/C', escape(' '.join(args))], env) # Windows does not allow special characters in file names anyway, so no # need for a complex escape function, we will just quote the arg, except # that "cmd /c" requires that if an argument ends with a backslash it # needs to be escaped so as not to interfere with closing double quote # that we add. def escape(x): if x[-1] == '\\': x = x + '\\' return '"' + x + '"' # Get the windows system directory name _system_root = None def get_system_root(): global _system_root if _system_root is not None: return _system_root # A resonable default if we can't read the registry val = os.environ.get('SystemRoot', "C:\\WINDOWS") if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') except KeyboardInterrupt: raise except: pass _system_root = val return val # Get the location of the program files directory def get_program_files_dir(): # Now see if we can look in the registry... val = '' if SCons.Util.can_read_reg: try: # Look for Windows Program Files directory k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'ProgramFilesDir') except SCons.Util.RegError: val = '' pass if val == '': # A reasonable default if we can't read the registry # (Actually, it's pretty reasonable even if we can :-) val = os.path.join(os.path.dirname(get_system_root()),"Program Files") return val # Determine which windows CPU were running on. class ArchDefinition(object): """ A class for defining architecture-specific settings and logic. """ def __init__(self, arch, synonyms=[]): self.arch = arch self.synonyms = synonyms SupportedArchitectureList = [ ArchDefinition( 'x86', ['i386', 'i486', 'i586', 'i686'], ), ArchDefinition( 'x86_64', ['AMD64', 'amd64', 'em64t', 'EM64T', 'x86_64'], ), ArchDefinition( 'ia64', ['IA64'], ), ] SupportedArchitectureMap = {} for a in SupportedArchitectureList: SupportedArchitectureMap[a.arch] = a for s in a.synonyms: SupportedArchitectureMap[s] = a def get_architecture(arch=None): """Returns the definition for the specified architecture string. If no string is specified, the system default is returned (as defined by the PROCESSOR_ARCHITEW6432 or PROCESSOR_ARCHITECTURE environment variables). """ if arch is None: arch = os.environ.get('PROCESSOR_ARCHITEW6432') if not arch: arch = os.environ.get('PROCESSOR_ARCHITECTURE') return SupportedArchitectureMap.get(arch, ArchDefinition('', [''])) def generate(env): # Attempt to find cmd.exe (for WinNT/2k/XP) or # command.com for Win9x cmd_interp = '' # First see if we can look in the registry... if SCons.Util.can_read_reg: try: # Look for Windows NT system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows NT\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'System32\\cmd.exe') except SCons.Util.RegError: try: # Okay, try the Windows 9x system root k=SCons.Util.RegOpenKeyEx(SCons.Util.hkey_mod.HKEY_LOCAL_MACHINE, 'Software\\Microsoft\\Windows\\CurrentVersion') val, tok = SCons.Util.RegQueryValueEx(k, 'SystemRoot') cmd_interp = os.path.join(val, 'command.com') except KeyboardInterrupt: raise except: pass # For the special case of not having access to the registry, we # use a temporary path and pathext to attempt to find the command # interpreter. If we fail, we try to find the interpreter through # the env's PATH. The problem with that is that it might not # contain an ENV and a PATH. if not cmd_interp: systemroot = get_system_root() tmp_path = systemroot + os.pathsep + \ os.path.join(systemroot,'System32') tmp_pathext = '.com;.exe;.bat;.cmd' if 'PATHEXT' in os.environ: tmp_pathext = os.environ['PATHEXT'] cmd_interp = SCons.Util.WhereIs('cmd', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = SCons.Util.WhereIs('command', tmp_path, tmp_pathext) if not cmd_interp: cmd_interp = env.Detect('cmd') if not cmd_interp: cmd_interp = env.Detect('command') if 'ENV' not in env: env['ENV'] = {} # Import things from the external environment to the construction # environment's ENV. This is a potential slippery slope, because we # *don't* want to make builds dependent on the user's environment by # default. We're doing this for SystemRoot, though, because it's # needed for anything that uses sockets, and seldom changes, and # for SystemDrive because it's related. # # Weigh the impact carefully before adding other variables to this list. import_env = [ 'SystemDrive', 'SystemRoot', 'TEMP', 'TMP' ] for var in import_env: v = os.environ.get(var) if v: env['ENV'][var] = v if 'COMSPEC' not in env['ENV']: v = os.environ.get("COMSPEC") if v: env['ENV']['COMSPEC'] = v env.AppendENVPath('PATH', get_system_root() + '\System32') env['ENV']['PATHEXT'] = '.COM;.EXE;.BAT;.CMD' env['OBJPREFIX'] = '' env['OBJSUFFIX'] = '.obj' env['SHOBJPREFIX'] = '$OBJPREFIX' env['SHOBJSUFFIX'] = '$OBJSUFFIX' env['PROGPREFIX'] = '' env['PROGSUFFIX'] = '.exe' env['LIBPREFIX'] = '' env['LIBSUFFIX'] = '.lib' env['SHLIBPREFIX'] = '' env['SHLIBSUFFIX'] = '.dll' env['LIBPREFIXES'] = [ '$LIBPREFIX' ] env['LIBSUFFIXES'] = [ '$LIBSUFFIX' ] env['PSPAWN'] = piped_spawn env['SPAWN'] = spawn env['SHELL'] = cmd_interp env['TEMPFILE'] = TempFileMunge env['TEMPFILEPREFIX'] = '@' env['MAXLINELENGTH'] = 2048 env['ESCAPE'] = escape env['HOST_OS'] = 'win32' env['HOST_ARCH'] = get_architecture().arch # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
PypiClean
/EVE_Gnosis-2017.6.27.tar.gz/EVE_Gnosis-2017.6.27/EVE_Gnosis/formulas/formulas.py
from math import sqrt, exp class Formulas(object): def __init__(self): pass @staticmethod def capacitor_shield_tick(maximum_amount, current_amount, recharge_rate, end_time=1000, start_time=0): """ :param maximum_amount: The size of the capacitor/shield in gigajoules (GJ) :param current_amount: The current level of the capacitor/shield in gigajoules (GJ) :param recharge_rate: Recharge time listed for the capacitor/shield, in milliseconds :param end_time: The length of time that we are running, in milliseconds :param start_time: The length of time that we are starting, in milliseconds (unlikely to be used) :return: Returns the new capacitor amount in gigajoules (GJ) This function assumes nothing else is at play to change the values while it's being calculated. Formula validated and confirmed by CCP Larrikin. <3 """ tau = recharge_rate / 5.0 time_diff = start_time - end_time new_amount = ( (1.0 + (sqrt(current_amount / maximum_amount) - 1.0) * exp(time_diff / tau)) ** 2 ) * maximum_amount if new_amount > maximum_amount: # Sanity check and make sure we don't return more than our maximum somehow. return maximum_amount else: return new_amount @staticmethod def capacitor_shield_regen_matrix(capacitor_amount, capacitor_time): """ :param capacitor_amount: The size of the capacitor/shield in gigajoules (GJ) :param capacitor_time: Recharge time listed for the capacitor/shield, in milliseconds :return: A matrix with the percent, capacitor amount after the tick, and the delta This function assumes nothing else is at play to change the values while it's being calculated. Most useful to determine the percentage point that gives the most cap, or for graphing it. """ regen_matrix = [] percent = 0 while percent < 1: current_amount = capacitor_amount * percent tick_amount = Formulas.capacitor_shield_tick(capacitor_amount, current_amount, capacitor_time) regen_matrix.append( { 'Percent': round(percent, 2), 'AmountPostTick': tick_amount, 'DeltaAmount': tick_amount - current_amount } ) percent += .01 regen_matrix.append( { 'Percent': 1, 'AmountPostTick': capacitor_amount, 'DeltaAmount': 0 } ) return regen_matrix @staticmethod def stacking_penalty(value, depth): """ :param value: The value to apply the stacking penalty to :param depth: How many stacking penalties to apply :return: Value after stacking penalties have been applied. """ current_effectiveness = 1 / exp(((depth - 1) / 2.67) ** 2.0) new_value = 1 + ((value * current_effectiveness) / 100) return new_value
PypiClean
/Crowd-3.1.0-py3-none-any.whl/crowd.py
import json import requests from lxml import etree class CrowdServer(object): """Crowd server authentication object. This is a Crowd authentication class to be configured for a particular application (app_name) to authenticate users against a Crowd server (crowd_url). This module uses the Crowd JSON API for talking to Crowd. An application account must be configured in the Crowd server and permitted to authenticate users against one or more user directories prior to using this module. Please see the Crowd documentation for information about configuring additional applications to talk to Crowd. The ``ssl_verify`` parameter controls how and if certificates are verified. If ``True``, the SSL certificate will be verified. A CA_BUNDLE path can also be provided. The ``client_cert`` tuple (cert,key) specifies a SSL client certificate and key files. """ def __init__(self, crowd_url, app_name, app_pass, ssl_verify=True, timeout=None, client_cert=None): self.crowd_url = crowd_url self.app_name = app_name self.app_pass = app_pass self.rest_url = crowd_url.rstrip("/") + "/rest/usermanagement/1" self.ssl_verify = ssl_verify self.client_cert = client_cert self.timeout = timeout self.session = self._build_session(content_type='json') self.session_xml = self._build_session(content_type='xml') def __str__(self): return "Crowd Server at %s" % self.crowd_url def __repr__(self): return "<CrowdServer('%s', '%s', '%s')>" % \ (self.crowd_url, self.app_name, self.app_pass) def _build_session(self, content_type='json'): headers = { 'Content-Type': 'application/{}'.format(content_type), 'Accept': 'application/{}'.format(content_type), } session = requests.Session() session.verify = self.ssl_verify session.cert = self.client_cert session.auth = requests.auth.HTTPBasicAuth(self.app_name, self.app_pass) session.headers.update(headers) return session def _get(self, *args, **kwargs): """Wrapper around Requests for GET requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.get(*args, **kwargs) return req def _get_xml(self, *args, **kwargs): """Wrapper around Requests for GET XML requests Returns: Response: A Requests Response object """ req = self.session_xml.get(*args, **kwargs) return req def _post(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.post(*args, **kwargs) return req def _post_xml(self, *args, **kwargs): """Wrapper around Requests for POST requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session_xml.post(*args, **kwargs) return req def _put(self, *args, **kwargs): """Wrapper around Requests for PUT requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.put(*args, **kwargs) return req def _delete(self, *args, **kwargs): """Wrapper around Requests for DELETE requests Returns: Response: A Requests Response object """ if 'timeout' not in kwargs: kwargs['timeout'] = self.timeout req = self.session.delete(*args, **kwargs) return req def auth_ping(self): """Test that application can authenticate to Crowd. Attempts to authenticate the application user against the Crowd server. In order for user authentication to work, an application must be able to authenticate. Returns: bool: True if the application authentication succeeded. """ url = self.rest_url + "/non-existent/location" response = self._get(url) if response.status_code == 401: return False elif response.status_code == 404: return True else: # An error encountered - problem with the Crowd server? return False def auth_user(self, username, password): """Authenticate a user account against the Crowd server. Attempts to authenticate the user against the Crowd server. Args: username: The account username. password: The account password. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ response = self._post(self.rest_url + "/authentication", data=json.dumps({"value": password}), params={"username": username}) # If authentication failed for any reason return None if not response.ok: return None # ...otherwise return a dictionary of user attributes return response.json() def get_session(self, username, password, remote="127.0.0.1", proxy=None): """Create a session for a user. Attempts to create a user session on the Crowd server. Args: username: The account username. password: The account password. remote: The remote address of the user. This can be used to create multiple concurrent sessions for a user. The host you run this program on may need to be configured in Crowd as a trusted proxy for this to work. proxy: Value of X-Forwarded-For server header. Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ params = { "username": username, "password": password, "validation-factors": { "validationFactors": [ {"name": "remote_address", "value": remote, }, ] } } if proxy: params["validation-factors"]["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, }) response = self._post(self.rest_url + "/session", data=json.dumps(params), params={"expand": "user"}) # If authentication failed for any reason return None if not response.ok: return None # Otherwise return the user object return response.json() def validate_session(self, token, remote="127.0.0.1", proxy=None): """Validate a session token. Validate a previously acquired session token against the Crowd server. This may be a token provided by a user from a http cookie or by some other means. Args: token: The session token. remote: The remote address of the user. proxy: Value of X-Forwarded-For server header Returns: dict: A dict mapping of user attributes if the application authentication was successful. See the Crowd documentation for the authoritative list of attributes. None: If authentication failed. """ params = { "validationFactors": [ {"name": "remote_address", "value": remote, }, ] } if proxy: params["validationFactors"].append({"name": "X-Forwarded-For", "value": proxy, }) url = self.rest_url + "/session/%s" % token response = self._post(url, data=json.dumps(params), params={"expand": "user"}) # For consistency between methods use None rather than False # If token validation failed for any reason return None if not response.ok: return None # Otherwise return the user object return response.json() def terminate_session(self, token): """Terminates the session token, effectively logging out the user from all crowd-enabled services. Args: token: The session token. Returns: True: If session terminated None: If session termination failed """ url = self.rest_url + "/session/%s" % token response = self._delete(url) # For consistency between methods use None rather than False # If token validation failed for any reason return None if not response.ok: return None # Otherwise return True return True def get_cookie_conf(self): """Retrieve cookie configuration Returns: dict: conf information None: if failure occurred """ response = self._get(self.rest_url + "/config/cookie") if not response.ok: return None return response.json() def add_user(self, username, raise_on_error=False, **kwargs): """Add a user to the directory Args: username: The account username raise_on_error: optional (default: False) **kwargs: key-value pairs: password: mandatory email: mandatory first_name: optional last_name: optional display_name: optional active: optional (default True) Returns: True: Succeeded False: If unsuccessful """ # Check that mandatory elements have been provided if 'password' not in kwargs: raise ValueError("missing password") if 'email' not in kwargs: raise ValueError("missing email") # Populate data with default and mandatory values. # A KeyError means a mandatory value was not provided, # so raise a ValueError indicating bad args. try: data = { "name": username, "first-name": username, "last-name": username, "display-name": username, "email": kwargs["email"], "password": {"value": kwargs["password"]}, "active": True } except KeyError: return ValueError # Remove special case 'password' del(kwargs["password"]) # Put values from kwargs into data for k, v in kwargs.items(): new_k = k.replace("_", "-") if new_k not in data: raise ValueError("invalid argument %s" % k) data[new_k] = v response = self._post(self.rest_url + "/user", data=json.dumps(data)) if response.status_code == 201: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False def get_user(self, username): """Retrieve information about a user Returns: dict: User information None: If no user or failure occurred """ response = self._get(self.rest_url + "/user", params={"username": username, "expand": "attributes"}) if not response.ok: return None return response.json() def set_active(self, username, active_state): """Set the active state of a user Args: username: The account username active_state: True or False Returns: True: If successful None: If no user or failure occurred """ if active_state not in (True, False): raise ValueError("active_state must be True or False") user = self.get_user(username) if user is None: return None if user['active'] is active_state: # Already in desired state return True user['active'] = active_state response = self._put(self.rest_url + "/user", params={"username": username}, data=json.dumps(user)) if response.status_code == 204: return True return None def set_user_attribute(self, username, attribute, value, raise_on_error=False): """Set an attribute on a user :param username: The username on which to set the attribute :param attribute: The name of the attribute to set :param value: The value of the attribute to set :return: True on success, False on failure. """ data = { 'attributes': [ { 'name': attribute, 'values': [ value ] }, ] } response = self._post(self.rest_url + "/user/attribute", params={"username": username,}, data=json.dumps(data)) if response.status_code == 204: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False def create_group(self, name, description='', raise_on_error=False): """Create a new group with the <name>. Args: name (str): the group name of a new group Returns: None: if succeeded error msg (str): If unsuccessful """ data = { "name": name, "description": description, "type": "GROUP", "active": True } response = self._post(self.rest_url + "/group", data=json.dumps(data)) if response.status_code == 201: return if raise_on_error: raise RuntimeError(response.json()['message']) return response.json()['message'] def remove_group(self, name, raise_on_error=False): """Remove a group with the <name>. Args: name (str): the group name of a removed group Returns: None: If succeeded error msg (str): If unsuccessful """ data = { "groupname": name } response = self._delete(self.rest_url + "/group", params=data) if response.status_code == 204: return if raise_on_error: raise RuntimeError(response.json()['message']) return response.json()['message'] def update_group(self, name, data, raise_on_error=False): """Update a group with the <name>. Args: name (str): the group name of a removed group data (dict): new group attrs Returns: None: if succeeded error msg (str): If unsuccessful """ params = { 'groupname': name } data["name"] = name data["type"] = "GROUP" response = self._put( self.rest_url + "/group", params=params, data=json.dumps(data) ) if response.status_code == 200: return if raise_on_error: raise RuntimeError(response.json()['message']) return response.json()['message'] def add_child_group(self, name, parent, raise_on_error=False): """Add a child group with the <name> to <parent> group. Args: name (str): the name of a child group parent (str): the name of a parent group Returns: None: if succeeded error msg (str): If unsuccessful """ params = { 'groupname': parent } data = { "name": name } response = self._post( self.rest_url + "/group/child-group/direct", data=json.dumps(data), params=params ) if response.status_code == 201: return if raise_on_error: raise RuntimeError(response.json()['message']) return response.json()['message'] def remove_child_group(self, name, parent, raise_on_error=False): """Add a child group with the <name> to <parent> group. Args: name (str): the name of a child group parent (str): the name of a parent group Returns: None: if succeeded error msg (str): If unsuccessful """ params = { 'groupname': parent, 'child-groupname': name } response = self._delete( self.rest_url + "/group/child-group/direct", params=params ) if response.status_code == 204: return if raise_on_error: raise RuntimeError(response.json()['message']) return response.json()['message'] def add_user_to_group(self, username, groupname, raise_on_error=False): """Add a user to a group :param username: The username to assign to the group :param groupname: The group name into which to assign the user :return: True on success, False on failure. """ data = { 'name': groupname, } response = self._post(self.rest_url + "/user/group/direct", params={"username": username,}, data=json.dumps(data)) if response.status_code == 201: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False def remove_user_from_group(self, username, groupname, raise_on_error=False): """Remove a user from a group Attempts to remove a user from a group Args: username: The username to remove from the group. groupname: The group name to be removed from the user. Returns: True: Succeeded False: If unsuccessful """ response = self._delete( self.rest_url + "/group/user/direct", params={ "username": username, "groupname": groupname } ) if response.status_code == 204: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False def change_password(self, username, newpassword, raise_on_error=False): """Change new password for a user Args: username: The account username. newpassword: The account new password. raise_on_error: optional (default: False) Returns: True: Succeeded False: If unsuccessful """ response = self._put(self.rest_url + "/user/password", data=json.dumps({"value": newpassword}), params={"username": username}) if response.ok: return True if raise_on_error: raise RuntimeError(response.json()['message']) return False def send_password_reset_link(self, username): """Sends the user a password reset link (by email) Args: username: The account username. Returns: True: Succeeded False: If unsuccessful """ response = self._post(self.rest_url + "/user/mail/password", params={"username": username}) if response.ok: return True return False def get_groups(self, username): """Retrieves a list of group names that have <username> as a direct member. Returns: list: A list of strings of group names. """ response = self._get(self.rest_url + "/user/group/direct", params={"username": username}) if not response.ok: return None return [g['name'] for g in response.json()['groups']] def get_nested_groups(self, username): """Retrieve a list of all group names that have <username> as a direct or indirect member. Args: username: The account username. Returns: list: A list of strings of group names. """ response = self._get(self.rest_url + "/user/group/nested", params={"username": username}) if not response.ok: return None return [g['name'] for g in response.json()['groups']] def get_nested_group_users(self, groupname): """Retrieves a list of all users that directly or indirectly belong to the given groupname. Args: groupname: The group name. Returns: list: A list of strings of user names. """ response = self._get(self.rest_url + "/group/user/nested", params={"groupname": groupname, "start-index": 0, "max-results": 99999}) if not response.ok: return None return [u['name'] for u in response.json()['users']] def user_exists(self, username): """Determines if the user exists. Args: username: The user name. Returns: bool: True if the user exists in the Crowd application. """ response = self._get(self.rest_url + "/user", params={"username": username}) if not response.ok: return None return True def get_memberships(self): """Fetches all group memberships. Returns: dict: key: group name value: (array of users, array of groups) """ response = self._get_xml(self.rest_url + "/group/membership") if not response.ok: return None xmltree = etree.fromstring(response.content) memberships = {} for mg in xmltree.findall('membership'): # coerce values to unicode in a python 2 and 3 compatible way group = u'{}'.format(mg.get('group')) users = [u'{}'.format(u.get('name')) for u in mg.find('users').findall('user')] groups = [u'{}'.format(g.get('name')) for g in mg.find('groups').findall('group')] memberships[group] = {u'users': users, u'groups': groups} return memberships def search(self, entity_type, property_name, search_string, start_index=0, max_results=99999): """Performs a user search using the Crowd search API. https://developer.atlassian.com/display/CROWDDEV/Crowd+REST+Resources#CrowdRESTResources-SearchResource Args: entity_type: 'user' or 'group' property_name: eg. 'email', 'name' search_string: the string to search for. start_index: starting index of the results (default: 0) max_results: maximum number of results returned (default: 99999) Returns: json results: Returns search results. """ params = { "entity-type": entity_type, "expand": entity_type, "property-search-restriction": { "property": {"name": property_name, "type": "STRING"}, "match-mode": "CONTAINS", "value": search_string, } } params = { 'entity-type': entity_type, 'expand': entity_type, 'start-index': start_index, 'max-results': max_results } # Construct XML payload of the form: # <property-search-restriction> # <property> # <name>email</name> # <type>STRING</type> # </property> # <match-mode>EXACTLY_MATCHES</match-mode> # <value>bob@example.net</value> # </property-search-restriction> root = etree.Element('property-search-restriction') property_ = etree.Element('property') prop_name = etree.Element('name') prop_name.text = property_name property_.append(prop_name) prop_type = etree.Element('type') prop_type.text = 'STRING' property_.append(prop_type) root.append(property_) match_mode = etree.Element('match-mode') match_mode.text = 'CONTAINS' root.append(match_mode) value = etree.Element('value') value.text = search_string root.append(value) # Construct the XML payload expected by search API payload = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(root).decode('utf-8') # We're sending XML but would like a JSON response session = self._build_session(content_type='xml') session.headers.update({'Accept': 'application/json'}) response = session.post(self.rest_url + "/search", params=params, data=payload, timeout=self.timeout) if not response.ok: return None return response.json()
PypiClean
/HelioSat-0.6.2-py3-none-any.whl/heliosat/spacecraft.py
import concurrent.futures import datetime import heliosat import logging import multiprocessing import numpy as np import spiceypy from .caching import cache_add_entry, cache_entry_exists, cache_generate_key, cache_get_entry from .datafile import DataFile from .smoothing import smooth_data from .util import dt_utc, dt_utc_from_ts, sanitize_dt from typing import Any, List, Optional, Sequence, Tuple, Union class Body(object): """Body class. """ name: str name_naif: str def __init__(self, name: str, name_naif: str, kernel_group: Optional[str] = None, **kwargs: Any) -> None: self.name = name self.name_naif = name_naif if "default" not in heliosat._skm.group_list: heliosat._skm.load_group("default") if kernel_group: heliosat._skm.load_group(kernel_group, **kwargs) def trajectory(self, dt: Union[datetime.datetime, Sequence[datetime.datetime]], reference_frame: str = "J2000", observer: str = "SUN", units: str = "AU") -> np.ndarray: logger = logging.getLogger(__name__) dt = sanitize_dt(dt) traj = np.array( spiceypy.spkpos( self.name_naif, spiceypy.datetime2et(dt), reference_frame, "NONE", observer )[0] ) if units == "AU": traj *= 6.68459e-9 elif units == "m": traj *= 1e3 elif units == "km": pass else: logger.exception("unit \"%s\" is not supported", units) raise ValueError("unit \"{0!s}\" is not supported".format(units)) return traj class Spacecraft(Body): """Spacecraft class. """ name: str name_naif: str kernel_group: str _json: dict data_file_class = DataFile def __init__(self, **kwargs: Any) -> None: logger = logging.getLogger(__name__) super(Spacecraft, self).__init__(self.name, self.name_naif, self.kernel_group, **kwargs) # legacy support self.get_data = self.get def get(self, dt: Union[str, datetime.datetime, Sequence[str], Sequence[datetime.datetime]], data_key: str, **kwargs: Any) -> Tuple[np.ndarray, np.ndarray]: logger = logging.getLogger(__name__) data_key = self.data_key_resolve(data_key) if isinstance(dt, datetime.datetime): dt = [dt] dt = sanitize_dt(dt) # type: ignore # caching identifier identifiers = { "data_key": data_key, "spacecraft": self.name, "times": [_t.timestamp() for _t in dt], # type: ignore "version": heliosat.__version__, **kwargs } # extract relevant kwargs remove_nans = kwargs.pop("remove_nans", False) return_datetimes = kwargs.pop("return_datetimes", False) sampling_freq = kwargs.pop("sampling_freq", 60) smoothing_kwargs = {"smoothing": kwargs.pop("smoothing", "closest")} # get additional smoothing args for key in dict(kwargs): if "smoothing" in key: smoothing_kwargs[key] = kwargs.pop(key) use_cache = kwargs.pop("use_cache", False) if use_cache: cache_key = cache_generate_key(identifiers) if cache_entry_exists(cache_key): dt_r, dk_r = cache_get_entry(cache_key) return dt_r, dk_r else: logger.info("cache entry \"%s\" not found", cache_key) # use dt list as endpoints if kwargs.pop("as_endpoints", False): if len(dt) < 2: # type: ignore logger.exception("datetime list must be of length larger of 2 to use endpoints") raise ValueError("datetime list must be of length larger of 2 to use endpoints") _ = np.linspace(dt[0].timestamp(), dt[-1].timestamp(), int((dt[-1].timestamp() - dt[0].timestamp()) // sampling_freq)) # type: ignore dt = [datetime.datetime.fromtimestamp(_, datetime.timezone.utc) for _ in _] dt_r, dk_r = self._get_data(dt[0], dt[-1], data_key, **kwargs) # type: ignore if smoothing_kwargs["smoothing"]: dt_r, dk_r = smooth_data(dt, dt_r, dk_r, **smoothing_kwargs) # type: ignore if return_datetimes: _dt = list(dt_r) for i in range(len(_dt)): if _dt[i] != np.nan: _dt[i] = dt_utc_from_ts(dt_r[i]) dt_r = np.array(_dt) if remove_nans: nanfilter = np.invert(np.any(np.isnan(dk_r[:, :]), axis=1)) dt_r = dt_r[nanfilter] dk_r = dk_r[nanfilter] if use_cache: logger.info("generating cache entry \"%s\"", cache_key) cache_add_entry(cache_key, (dt_r, dk_r)) return dt_r, dk_r def _get_data(self, dt_start: datetime.datetime, dt_end: datetime.datetime, data_key: str, **kwargs: Any) -> Tuple[np.ndarray, np.ndarray]: logger = logging.getLogger(__name__) data_key = self.data_key_resolve(data_key) dt_start = sanitize_dt(dt_start) # type: ignore dt_end = sanitize_dt(dt_end) # type: ignore if dt_start > dt_end: logger.exception("starting date must be before final date") raise ValueError("starting date must be before final date") force_download = kwargs.get("force_download", False) # get necessary files files = self._get_files(dt_start, dt_end, data_key, force_download=force_download) logger.info("using %s files to generate " "data in between %s - %s", len(files), dt_start, dt_end) columns = kwargs.get("columns", ["~"]) columns.extend(kwargs.get("extra_columns", [])) frame = kwargs.get("frame", kwargs.get("reference_frame", None)) max_workers = min([multiprocessing.cpu_count(), len(files)]) with concurrent.futures.ProcessPoolExecutor(max_workers=max_workers) as executor: futures = [executor.submit(file.read, dt_start, dt_end, data_key, columns, frame) for file in files] result = [_ for _ in [future.result() for future in futures] if _] dt_r = np.concatenate([_[0] for _ in result]) dk_r = np.concatenate([_[1] for _ in result]) return dt_r, dk_r def _get_files(self, dt_start: datetime.datetime, dt_end: datetime.datetime, data_key: str, force_download: bool = False) -> List[DataFile]: logger = logging.getLogger(__name__) # adjust ranges slightly if (dt_end - dt_start).days > 1: dt_start -= datetime.timedelta(hours=dt_start.hour, minutes=dt_start.minute, seconds=dt_start.second) if dt_end.hour == 0 and dt_end.minute == 0 and dt_end.second == 0: dt_end -= datetime.timedelta(seconds=1) files = [] # prepare urls for day in [dt_start + datetime.timedelta(days=i) for i in range((dt_end - dt_start).days + 1)]: base_urls = [] for url in self._json["keys"][data_key]["base_urls"]: url = url.replace("{YYYY}", str(day.year)) url = url.replace("{YY}", "{0:02d}".format(day.year % 100)) url = url.replace("{MM}", "{:02d}".format(day.month)) url = url.replace("{MONTH}", day.strftime("%B")[:3].upper()) url = url.replace("{DD}", "{:02d}".format(day.day)) url = url.replace("{DOY}", "{:03d}".format(day.timetuple().tm_yday)) doym1 = dt_utc(day.year, day.month, 1) if day.month == 12: doym2 = dt_utc(day.year + 1, 1, 1) - datetime.timedelta(days=1) else: doym2 = dt_utc(day.year, day.month + 1, 1) - datetime.timedelta(days=1) url = url.replace("{DOYM1}", "{:03d}".format(doym1.timetuple().tm_yday)) url = url.replace("{DOYM2}", "{:03d}".format(doym2.timetuple().tm_yday)) base_urls.append(url) filename = self._json["keys"][data_key].get("filename", None) if filename: filename = filename.replace("{YYYY}", str(day.year)) filename = filename.replace("{YY}", "{0:02d}".format(day.year % 100)) filename = filename.replace("{MM}", "{:02d}".format(day.month)) filename = filename.replace("{MONTH}", day.strftime("%B")[:3].upper()) filename = filename.replace("{DD}", "{:02d}".format(day.day)) filename = filename.replace("{DOY}", "{:03d}".format(day.timetuple().tm_yday)) doym1 = dt_utc(day.year, day.month, 1) if day.month == 12: doym2 = dt_utc(day.year + 1, 1, 1) - datetime.timedelta(days=1) else: doym2 = dt_utc(day.year, day.month + 1, 1) - datetime.timedelta(days=1) filename = filename.replace("{DOYM1}", "{:03d}".format(doym1.timetuple().tm_yday)) filename = filename.replace("{DOYM2}", "{:03d}".format(doym2.timetuple().tm_yday)) files.append(self.data_file_class(base_urls, filename, data_key, self._json)) with concurrent.futures.ThreadPoolExecutor(max_workers=25) as executor: futures = [executor.submit(file.prepare, force_download) for file in files] for future in concurrent.futures.as_completed(futures): _ = future.result() for file in list(files): if not file.ready: files.remove(file) return files @property def data_keys(self) -> List[str]: return list(self._json["keys"].keys()) def data_key_resolve(self, data_key: str) -> str: logger = logging.getLogger(__name__) if data_key not in self._json["keys"]: resolved = False for key in self._json["keys"]: if data_key in self._json["keys"][key].get("alt_keys", []): data_key = key resolved = True break if not resolved: logger.exception("data_key \"%s\" not found", data_key) raise KeyError("data_key \"{0!s}\" not found".format(data_key)) return data_key
PypiClean
/Kloudio-1.0.0.tar.gz/Kloudio-1.0.0/kloudio/models/report_del_response.py
import pprint import re # noqa: F401 import six from kloudio.configuration import Configuration class ReportDelResponse(object): """ """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'object': 'str', 'id': 'str', 'deleted': 'bool' } attribute_map = { 'object': 'object', 'id': 'id', 'deleted': 'deleted' } def __init__(self, object=None, id=None, deleted=None, local_vars_configuration=None): # noqa: E501 """ReportDelResponse - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._object = None self._id = None self._deleted = None self.discriminator = None self.object = object self.id = id self.deleted = deleted @property def object(self): """Gets the object of this ReportDelResponse. # noqa: E501 :return: The object of this ReportDelResponse. # noqa: E501 :rtype: str """ return self._object @object.setter def object(self, object): """Sets the object of this ReportDelResponse. :param object: The object of this ReportDelResponse. # noqa: E501 :type object: str """ if self.local_vars_configuration.client_side_validation and object is None: # noqa: E501 raise ValueError("Invalid value for `object`, must not be `None`") # noqa: E501 self._object = object @property def id(self): """Gets the id of this ReportDelResponse. # noqa: E501 :return: The id of this ReportDelResponse. # noqa: E501 :rtype: str """ return self._id @id.setter def id(self, id): """Sets the id of this ReportDelResponse. :param id: The id of this ReportDelResponse. # noqa: E501 :type id: str """ if self.local_vars_configuration.client_side_validation and id is None: # noqa: E501 raise ValueError("Invalid value for `id`, must not be `None`") # noqa: E501 self._id = id @property def deleted(self): """Gets the deleted of this ReportDelResponse. # noqa: E501 :return: The deleted of this ReportDelResponse. # noqa: E501 :rtype: bool """ return self._deleted @deleted.setter def deleted(self, deleted): """Sets the deleted of this ReportDelResponse. :param deleted: The deleted of this ReportDelResponse. # noqa: E501 :type deleted: bool """ if self.local_vars_configuration.client_side_validation and deleted is None: # noqa: E501 raise ValueError("Invalid value for `deleted`, must not be `None`") # noqa: E501 self._deleted = deleted def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ReportDelResponse): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, ReportDelResponse): return True return self.to_dict() != other.to_dict()
PypiClean
/Nuitka-1.8.tar.gz/Nuitka-1.8/nuitka/build/inline_copy/lib/scons-4.3.0/SCons/Environment.py
import copy import os import sys import re import shlex from collections import UserDict import SCons.Action import SCons.Builder import SCons.Debug from SCons.Debug import logInstanceCreation import SCons.Defaults from SCons.Errors import UserError, BuildError import SCons.Memoize import SCons.Node import SCons.Node.Alias import SCons.Node.FS import SCons.Node.Python import SCons.Platform import SCons.SConf import SCons.SConsign import SCons.Subst import SCons.Tool import SCons.Warnings from SCons.Util import ( AppendPath, CLVar, LogicalLines, MethodWrapper, PrependPath, Split, WhereIs, flatten, is_Dict, is_List, is_Sequence, is_String, is_Tuple, semi_deepcopy, semi_deepcopy_dict, to_String_for_subst, uniquer_hashables, ) class _Null: pass _null = _Null _warn_copy_deprecated = True _warn_source_signatures_deprecated = True _warn_target_signatures_deprecated = True CleanTargets = {} CalculatorArgs = {} def alias_builder(env, target, source): pass AliasBuilder = SCons.Builder.Builder( action=alias_builder, target_factory=SCons.Node.Alias.default_ans.Alias, source_factory=SCons.Node.FS.Entry, multi=True, is_explicit=None, name='AliasBuilder', ) def apply_tools(env, tools, toolpath): # Store the toolpath in the Environment. # This is expected to work even if no tools are given, so do this first. if toolpath is not None: env['toolpath'] = toolpath if not tools: return # Filter out null tools from the list. for tool in [_f for _f in tools if _f]: if is_List(tool) or is_Tuple(tool): # toolargs should be a dict of kw args toolname, toolargs, *rest = tool _ = env.Tool(toolname, **toolargs) else: _ = env.Tool(tool) # These names are (or will be) controlled by SCons; users should never # set or override them. The warning can optionally be turned off, # but scons will still ignore the illegal variable names even if it's off. reserved_construction_var_names = [ 'CHANGED_SOURCES', 'CHANGED_TARGETS', 'SOURCE', 'SOURCES', 'TARGET', 'TARGETS', 'UNCHANGED_SOURCES', 'UNCHANGED_TARGETS', ] future_reserved_construction_var_names = [ #'HOST_OS', #'HOST_ARCH', #'HOST_CPU', ] def copy_non_reserved_keywords(dict): result = semi_deepcopy(dict) for k in result.copy().keys(): if k in reserved_construction_var_names: msg = "Ignoring attempt to set reserved variable `$%s'" SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % k) del result[k] return result def _set_reserved(env, key, value): msg = "Ignoring attempt to set reserved variable `$%s'" SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % key) def _set_future_reserved(env, key, value): env._dict[key] = value msg = "`$%s' will be reserved in a future release and setting it will become ignored" SCons.Warnings.warn(SCons.Warnings.FutureReservedVariableWarning, msg % key) def _set_BUILDERS(env, key, value): try: bd = env._dict[key] for k in bd.copy().keys(): del bd[k] except KeyError: bd = BuilderDict(bd, env) env._dict[key] = bd for k, v in value.items(): if not SCons.Builder.is_a_Builder(v): raise UserError('%s is not a Builder.' % repr(v)) bd.update(value) def _del_SCANNERS(env, key): del env._dict[key] env.scanner_map_delete() def _set_SCANNERS(env, key, value): env._dict[key] = value env.scanner_map_delete() def _delete_duplicates(l, keep_last): """Delete duplicates from a sequence, keeping the first or last.""" seen=set() result=[] if keep_last: # reverse in & out, then keep first l.reverse() for i in l: try: if i not in seen: result.append(i) seen.add(i) except TypeError: # probably unhashable. Just keep it. result.append(i) if keep_last: result.reverse() return result # The following is partly based on code in a comment added by Peter # Shannon at the following page (there called the "transplant" class): # # ASPN : Python Cookbook : Dynamically added methods to a class # https://code.activestate.com/recipes/81732/ # # We had independently been using the idiom as BuilderWrapper, but # factoring out the common parts into this base class, and making # BuilderWrapper a subclass that overrides __call__() to enforce specific # Builder calling conventions, simplified some of our higher-layer code. # # Note: MethodWrapper moved to SCons.Util as it was needed there # and otherwise we had a circular import problem. class BuilderWrapper(MethodWrapper): """ A MethodWrapper subclass that that associates an environment with a Builder. This mainly exists to wrap the __call__() function so that all calls to Builders can have their argument lists massaged in the same way (treat a lone argument as the source, treat two arguments as target then source, make sure both target and source are lists) without having to have cut-and-paste code to do it. As a bit of obsessive backwards compatibility, we also intercept attempts to get or set the "env" or "builder" attributes, which were the names we used before we put the common functionality into the MethodWrapper base class. We'll keep this around for a while in case people shipped Tool modules that reached into the wrapper (like the Tool/qt.py module does, or did). There shouldn't be a lot attribute fetching or setting on these, so a little extra work shouldn't hurt. """ def __call__(self, target=None, source=_null, *args, **kw): if source is _null: source = target target = None if target is not None and not is_List(target): target = [target] if source is not None and not is_List(source): source = [source] return super().__call__(target, source, *args, **kw) def __repr__(self): return '<BuilderWrapper %s>' % repr(self.name) def __str__(self): return self.__repr__() def __getattr__(self, name): if name == 'env': return self.object elif name == 'builder': return self.method else: raise AttributeError(name) def __setattr__(self, name, value): if name == 'env': self.object = value elif name == 'builder': self.method = value else: self.__dict__[name] = value # This allows a Builder to be executed directly # through the Environment to which it's attached. # In practice, we shouldn't need this, because # builders actually get executed through a Node. # But we do have a unit test for this, and can't # yet rule out that it would be useful in the # future, so leave it for now. #def execute(self, **kw): # kw['env'] = self.env # self.builder.execute(**kw) class BuilderDict(UserDict): """This is a dictionary-like class used by an Environment to hold the Builders. We need to do this because every time someone changes the Builders in the Environment's BUILDERS dictionary, we must update the Environment's attributes.""" def __init__(self, dict, env): # Set self.env before calling the superclass initialization, # because it will end up calling our other methods, which will # need to point the values in this dictionary to self.env. self.env = env UserDict.__init__(self, dict) def __semi_deepcopy__(self): # These cannot be copied since they would both modify the same builder object, and indeed # just copying would modify the original builder raise TypeError( 'cannot semi_deepcopy a BuilderDict' ) def __setitem__(self, item, val): try: method = getattr(self.env, item).method except AttributeError: pass else: self.env.RemoveMethod(method) UserDict.__setitem__(self, item, val) BuilderWrapper(self.env, val, item) def __delitem__(self, item): UserDict.__delitem__(self, item) delattr(self.env, item) def update(self, dict): for i, v in dict.items(): self.__setitem__(i, v) _is_valid_var = re.compile(r'[_a-zA-Z]\w*$') def is_valid_construction_var(varstr): """Return if the specified string is a legitimate construction variable. """ return _is_valid_var.match(varstr) class SubstitutionEnvironment: """Base class for different flavors of construction environments. This class contains a minimal set of methods that handle construction variable expansion and conversion of strings to Nodes, which may or may not be actually useful as a stand-alone class. Which methods ended up in this class is pretty arbitrary right now. They're basically the ones which we've empirically determined are common to the different construction environment subclasses, and most of the others that use or touch the underlying dictionary of construction variables. Eventually, this class should contain all the methods that we determine are necessary for a "minimal" interface to the build engine. A full "native Python" SCons environment has gotten pretty heavyweight with all of the methods and Tools and construction variables we've jammed in there, so it would be nice to have a lighter weight alternative for interfaces that don't need all of the bells and whistles. (At some point, we'll also probably rename this class "Base," since that more reflects what we want this class to become, but because we've released comments that tell people to subclass Environment.Base to create their own flavors of construction environment, we'll save that for a future refactoring when this class actually becomes useful.) """ def __init__(self, **kw): """Initialization of an underlying SubstitutionEnvironment class. """ if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.SubstitutionEnvironment') self.fs = SCons.Node.FS.get_default_fs() self.ans = SCons.Node.Alias.default_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._dict = kw.copy() self._init_special() self.added_methods = [] #self._memo = {} def _init_special(self): """Initial the dispatch tables for special handling of special construction variables.""" self._special_del = {} self._special_del['SCANNERS'] = _del_SCANNERS self._special_set = {} for key in reserved_construction_var_names: self._special_set[key] = _set_reserved for key in future_reserved_construction_var_names: self._special_set[key] = _set_future_reserved self._special_set['BUILDERS'] = _set_BUILDERS self._special_set['SCANNERS'] = _set_SCANNERS # Freeze the keys of self._special_set in a list for use by # methods that need to check. self._special_set_keys = list(self._special_set.keys()) def __eq__(self, other): return self._dict == other._dict def __delitem__(self, key): special = self._special_del.get(key) if special: special(self, key) else: del self._dict[key] def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): # This is heavily used. This implementation is the best we have # according to the timings in bench/env.__setitem__.py. # # The "key in self._special_set_keys" test here seems to perform # pretty well for the number of keys we have. A hard-coded # list worked a little better in Python 2.5, but that has the # disadvantage of maybe getting out of sync if we ever add more # variable names. # So right now it seems like a good trade-off, but feel free to # revisit this with bench/env.__setitem__.py as needed (and # as newer versions of Python come out). if key in self._special_set_keys: self._special_set[key](self, key, value) else: # If we already have the entry, then it's obviously a valid # key and we don't need to check. If we do check, using a # global, pre-compiled regular expression directly is more # efficient than calling another function or a method. if key not in self._dict and not _is_valid_var.match(key): raise UserError("Illegal construction variable `%s'" % key) self._dict[key] = value def get(self, key, default=None): """Emulates the get() method of dictionaries.""" return self._dict.get(key, default) def __contains__(self, key): return key in self._dict def keys(self): """Emulates the keys() method of dictionaries.""" return self._dict.keys() def values(self): """Emulates the values() method of dictionaries.""" return self._dict.values() def items(self): """Emulates the items() method of dictionaries.""" return self._dict.items() def setdefault(self, key, default=None): """Emulates the setdefault() method of dictionaries.""" return self._dict.setdefault(key, default) def arg2nodes(self, args, node_factory=_null, lookup_list=_null, **kw): if node_factory is _null: node_factory = self.fs.File if lookup_list is _null: lookup_list = self.lookup_list if not args: return [] args = flatten(args) nodes = [] for v in args: if is_String(v): n = None for l in lookup_list: n = l(v) if n is not None: break if n is not None: if is_String(n): # n = self.subst(n, raw=1, **kw) kw['raw'] = 1 n = self.subst(n, **kw) if node_factory: n = node_factory(n) if is_List(n): nodes.extend(n) else: nodes.append(n) elif node_factory: # v = node_factory(self.subst(v, raw=1, **kw)) kw['raw'] = 1 v = node_factory(self.subst(v, **kw)) if is_List(v): nodes.extend(v) else: nodes.append(v) else: nodes.append(v) return nodes def gvars(self): return self._dict def lvars(self): return {} def subst(self, string, raw=0, target=None, source=None, conv=None, executor=None): """Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters. """ gvars = self.gvars() lvars = self.lvars() lvars['__env__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst(string, self, raw, target, source, gvars, lvars, conv) def subst_kw(self, kw, raw=0, target=None, source=None): nkw = {} for k, v in kw.items(): k = self.subst(k, raw, target, source) if is_String(v): v = self.subst(v, raw, target, source) nkw[k] = v return nkw def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None): """Calls through to SCons.Subst.scons_subst_list(). See the documentation for that function.""" gvars = self.gvars() lvars = self.lvars() lvars['__env__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst_list(string, self, raw, target, source, gvars, lvars, conv) def subst_path(self, path, target=None, source=None): """Substitute a path list, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.""" if not is_List(path): path = [path] def s(obj): """This is the "string conversion" routine that we have our substitutions use to return Nodes, not strings. This relies on the fact that an EntryProxy object has a get() method that returns the underlying Node that it wraps, which is a bit of architectural dependence that we might need to break or modify in the future in response to additional requirements.""" try: get = obj.get except AttributeError: obj = to_String_for_subst(obj) else: obj = get() return obj r = [] for p in path: if is_String(p): p = self.subst(p, target=target, source=source, conv=s) if is_List(p): if len(p) == 1: p = p[0] else: # We have an object plus a string, or multiple # objects that we need to smush together. No choice # but to make them into a string. p = ''.join(map(to_String_for_subst, p)) else: p = s(p) r.append(p) return r subst_target_source = subst def backtick(self, command): import subprocess # common arguments kw = { 'stdin' : 'devnull', 'stdout' : subprocess.PIPE, 'stderr' : subprocess.PIPE, 'universal_newlines' : True, } # if the command is a list, assume it's been quoted # othewise force a shell if not is_List(command): kw['shell'] = True # run constructed command p = SCons.Action._subproc(self, command, **kw) out,err = p.communicate() status = p.wait() if err: sys.stderr.write("" + err) if status: raise OSError("'%s' exited %d" % (command, status)) return out def AddMethod(self, function, name=None): """ Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself. """ method = MethodWrapper(self, function, name) self.added_methods.append(method) def RemoveMethod(self, function): """ Removes the specified function's MethodWrapper from the added_methods list, so we don't re-bind it when making a clone. """ self.added_methods = [dm for dm in self.added_methods if dm.method is not function] def Override(self, overrides): """ Produce a modified environment whose variables are overridden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment. This function is much more efficient than Clone() or creating a new Environment because it doesn't copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn't even create a wrapper object if there are no overrides. """ if not overrides: return self o = copy_non_reserved_keywords(overrides) if not o: return self overrides = {} merges = None for key, value in o.items(): if key == 'parse_flags': merges = value else: overrides[key] = SCons.Subst.scons_subst_once(value, self, key) env = OverrideEnvironment(self, overrides) if merges: env.MergeFlags(merges) return env def ParseFlags(self, *flags): """Return a dict of parsed flags. Parse ``flags`` and return a dict with the flags distributed into the appropriate construction variable names. The flags are treated as a typical set of command-line flags for a GNU-like toolchain, such as might have been generated by one of the {foo}-config scripts, and used to populate the entries based on knowledge embedded in this method - the choices are not expected to be portable to other toolchains. If one of the ``flags`` strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict. """ dict = { 'ASFLAGS' : CLVar(''), 'CFLAGS' : CLVar(''), 'CCFLAGS' : CLVar(''), 'CXXFLAGS' : CLVar(''), 'CPPDEFINES' : [], 'CPPFLAGS' : CLVar(''), 'CPPPATH' : [], 'FRAMEWORKPATH' : CLVar(''), 'FRAMEWORKS' : CLVar(''), 'LIBPATH' : [], 'LIBS' : [], 'LINKFLAGS' : CLVar(''), 'RPATH' : [], } def do_parse(arg): # if arg is a sequence, recurse with each element if not arg: return if not is_String(arg): for t in arg: do_parse(t) return # if arg is a command, execute it if arg[0] == '!': arg = self.backtick(arg[1:]) # utility function to deal with -D option def append_define(name, dict = dict): t = name.split('=') if len(t) == 1: dict['CPPDEFINES'].append(name) else: dict['CPPDEFINES'].append([t[0], '='.join(t[1:])]) # Loop through the flags and add them to the appropriate option. # This tries to strike a balance between checking for all possible # flags and keeping the logic to a finite size, so it doesn't # check for some that don't occur often. It particular, if the # flag is not known to occur in a config script and there's a way # of passing the flag to the right place (by wrapping it in a -W # flag, for example) we don't check for it. Note that most # preprocessor options are not handled, since unhandled options # are placed in CCFLAGS, so unless the preprocessor is invoked # separately, these flags will still get to the preprocessor. # Other options not currently handled: # -iqoutedir (preprocessor search path) # -u symbol (linker undefined symbol) # -s (linker strip files) # -static* (linker static binding) # -shared* (linker dynamic binding) # -symbolic (linker global binding) # -R dir (deprecated linker rpath) # IBM compilers may also accept -qframeworkdir=foo params = shlex.split(arg) append_next_arg_to = None # for multi-word args for arg in params: if append_next_arg_to: if append_next_arg_to == 'CPPDEFINES': append_define(arg) elif append_next_arg_to == '-include': t = ('-include', self.fs.File(arg)) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-imacros': t = ('-imacros', self.fs.File(arg)) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-isysroot': t = ('-isysroot', arg) dict['CCFLAGS'].append(t) dict['LINKFLAGS'].append(t) elif append_next_arg_to == '-isystem': t = ('-isystem', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-iquote': t = ('-iquote', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-idirafter': t = ('-idirafter', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-arch': t = ('-arch', arg) dict['CCFLAGS'].append(t) dict['LINKFLAGS'].append(t) elif append_next_arg_to == '--param': t = ('--param', arg) dict['CCFLAGS'].append(t) else: dict[append_next_arg_to].append(arg) append_next_arg_to = None elif not arg[0] in ['-', '+']: dict['LIBS'].append(self.fs.File(arg)) elif arg == '-dylib_file': dict['LINKFLAGS'].append(arg) append_next_arg_to = 'LINKFLAGS' elif arg[:2] == '-L': if arg[2:]: dict['LIBPATH'].append(arg[2:]) else: append_next_arg_to = 'LIBPATH' elif arg[:2] == '-l': if arg[2:]: dict['LIBS'].append(arg[2:]) else: append_next_arg_to = 'LIBS' elif arg[:2] == '-I': if arg[2:]: dict['CPPPATH'].append(arg[2:]) else: append_next_arg_to = 'CPPPATH' elif arg[:4] == '-Wa,': dict['ASFLAGS'].append(arg[4:]) dict['CCFLAGS'].append(arg) elif arg[:4] == '-Wl,': if arg[:11] == '-Wl,-rpath=': dict['RPATH'].append(arg[11:]) elif arg[:7] == '-Wl,-R,': dict['RPATH'].append(arg[7:]) elif arg[:6] == '-Wl,-R': dict['RPATH'].append(arg[6:]) else: dict['LINKFLAGS'].append(arg) elif arg[:4] == '-Wp,': dict['CPPFLAGS'].append(arg) elif arg[:2] == '-D': if arg[2:]: append_define(arg[2:]) else: append_next_arg_to = 'CPPDEFINES' elif arg == '-framework': append_next_arg_to = 'FRAMEWORKS' elif arg[:14] == '-frameworkdir=': dict['FRAMEWORKPATH'].append(arg[14:]) elif arg[:2] == '-F': if arg[2:]: dict['FRAMEWORKPATH'].append(arg[2:]) else: append_next_arg_to = 'FRAMEWORKPATH' elif arg in [ '-mno-cygwin', '-pthread', '-openmp', '-fmerge-all-constants', '-fopenmp', ]: dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg == '-mwindows': dict['LINKFLAGS'].append(arg) elif arg[:5] == '-std=': if '++' in arg[5:]: key='CXXFLAGS' else: key='CFLAGS' dict[key].append(arg) elif arg[0] == '+': dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg in [ '-include', '-imacros', '-isysroot', '-isystem', '-iquote', '-idirafter', '-arch', '--param', ]: append_next_arg_to = arg else: dict['CCFLAGS'].append(arg) for arg in flags: do_parse(arg) return dict def MergeFlags(self, args, unique=True): """Merge flags into construction variables. Merges the flags from ``args`` into this construction environent. If ``args`` is not a dict, it is first converted to a dictionary with flags distributed into appropriate construction variables. See :meth:`ParseFlags`. Args: args: flags to merge unique: merge flags rather than appending (default: True) """ if not is_Dict(args): args = self.ParseFlags(args) if not unique: self.Append(**args) return for key, value in args.items(): if not value: continue value = Split(value) try: orig = self[key] except KeyError: orig = value else: if not orig: orig = value elif value: # Add orig and value. The logic here was lifted from # part of env.Append() (see there for a lot of comments # about the order in which things are tried) and is # used mainly to handle coercion of strings to CLVar to # "do the right thing" given (e.g.) an original CCFLAGS # string variable like '-pipe -Wall'. try: orig = orig + value except (KeyError, TypeError): try: add_to_orig = orig.append except AttributeError: value.insert(0, orig) orig = value else: add_to_orig(value) t = [] if key[-4:] == 'PATH': ### keep left-most occurence for v in orig: if v not in t: t.append(v) else: ### keep right-most occurence for v in orig[::-1]: if v not in t: t.insert(0, v) self[key] = t def default_decide_source(dependency, target, prev_ni, repo_node=None): f = SCons.Defaults.DefaultEnvironment().decide_source return f(dependency, target, prev_ni, repo_node) def default_decide_target(dependency, target, prev_ni, repo_node=None): f = SCons.Defaults.DefaultEnvironment().decide_target return f(dependency, target, prev_ni, repo_node) def default_copy_from_cache(env, src, dst): return SCons.CacheDir.CacheDir.copy_from_cache(env, src, dst) def default_copy_to_cache(env, src, dst): return SCons.CacheDir.CacheDir.copy_to_cache(env, src, dst) class Base(SubstitutionEnvironment): """Base class for "real" construction Environments. These are the primary objects used to communicate dependency and construction information to the build engine. Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment. """ ####################################################################### # This is THE class for interacting with the SCons build engine, # and it contains a lot of stuff, so we're going to try to keep this # a little organized by grouping the methods. ####################################################################### ####################################################################### # Methods that make an Environment act like a dictionary. These have # the expected standard names for Python mapping objects. Note that # we don't actually make an Environment a subclass of UserDict for # performance reasons. Note also that we only supply methods for # dictionary functionality that we actually need and use. ####################################################################### def __init__( self, platform=None, tools=None, toolpath=None, variables=None, parse_flags=None, **kw ): """Initialization of a basic SCons construction environment. Sets up special construction variables like BUILDER, PLATFORM, etc., and searches for and applies available Tools. Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we need to initialize things in a very specific order that doesn't work with the much simpler base class initialization. """ if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.Base') self._memo = {} self.fs = SCons.Node.FS.get_default_fs() self.ans = SCons.Node.Alias.default_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._dict = semi_deepcopy(SCons.Defaults.ConstructionEnvironment) self._init_special() self.added_methods = [] # We don't use AddMethod, or define these as methods in this # class, because we *don't* want these functions to be bound # methods. They need to operate independently so that the # settings will work properly regardless of whether a given # target ends up being built with a Base environment or an # OverrideEnvironment or what have you. self.decide_target = default_decide_target self.decide_source = default_decide_source self.cache_timestamp_newer = False self._dict['BUILDERS'] = BuilderDict(self._dict['BUILDERS'], self) if platform is None: platform = self._dict.get('PLATFORM', None) if platform is None: platform = SCons.Platform.Platform() if is_String(platform): platform = SCons.Platform.Platform(platform) self._dict['PLATFORM'] = str(platform) platform(self) # these should be set by the platform, backstop just in case self._dict['HOST_OS'] = self._dict.get('HOST_OS', None) self._dict['HOST_ARCH'] = self._dict.get('HOST_ARCH', None) # these are not currently set by the platform, give them a default self._dict['TARGET_OS'] = self._dict.get('TARGET_OS', None) self._dict['TARGET_ARCH'] = self._dict.get('TARGET_ARCH', None) # Apply the passed-in and customizable variables to the # environment before calling the tools, because they may use # some of them during initialization. if 'options' in kw: # Backwards compatibility: they may stll be using the # old "options" keyword. variables = kw['options'] del kw['options'] self.Replace(**kw) keys = list(kw.keys()) if variables: keys = keys + list(variables.keys()) variables.Update(self) save = {} for k in keys: try: save[k] = self._dict[k] except KeyError: # No value may have been set if they tried to pass in a # reserved variable name like TARGETS. pass SCons.Tool.Initializers(self) if tools is None: tools = self._dict.get('TOOLS', None) if tools is None: tools = ['default'] apply_tools(self, tools, toolpath) # Now restore the passed-in and customized variables # to the environment, since the values the user set explicitly # should override any values set by the tools. for key, val in save.items(): self._dict[key] = val # Finally, apply any flags to be merged in if parse_flags: self.MergeFlags(parse_flags) ####################################################################### # Utility methods that are primarily for internal use by SCons. # These begin with lower-case letters. ####################################################################### def get_builder(self, name): """Fetch the builder with the specified name from the environment. """ try: return self._dict['BUILDERS'][name] except KeyError: return None def validate_CacheDir_class(self, custom_class=None): """Validate the passed custom CacheDir class, or if no args are passed, validate the custom CacheDir class from the environment. """ if custom_class is None: custom_class = self.get("CACHEDIR_CLASS", SCons.CacheDir.CacheDir) if not issubclass(custom_class, SCons.CacheDir.CacheDir): raise UserError("Custom CACHEDIR_CLASS %s not derived from CacheDir" % str(custom_class)) return custom_class def get_CacheDir(self): try: path = self._CacheDir_path except AttributeError: path = SCons.Defaults.DefaultEnvironment()._CacheDir_path cachedir_class = self.validate_CacheDir_class() try: if (path == self._last_CacheDir_path # this checks if the cachedir class type has changed from what the # instantiated cache dir type is. If the are exactly the same we # can just keep using the existing one, otherwise the user is requesting # something new, so we will re-instantiate below. and type(self._last_CacheDir) is cachedir_class): return self._last_CacheDir except AttributeError: pass cd = cachedir_class(path) self._last_CacheDir_path = path self._last_CacheDir = cd return cd def get_factory(self, factory, default='File'): """Return a factory function for creating Nodes for this construction environment. """ name = default try: is_node = issubclass(factory, SCons.Node.FS.Base) except TypeError: # The specified factory isn't a Node itself--it's # most likely None, or possibly a callable. pass else: if is_node: # The specified factory is a Node (sub)class. Try to # return the FS method that corresponds to the Node's # name--that is, we return self.fs.Dir if they want a Dir, # self.fs.File for a File, etc. try: name = factory.__name__ except AttributeError: pass else: factory = None if not factory: # They passed us None, or we picked up a name from a specified # class, so return the FS method. (Note that we *don't* # use our own self.{Dir,File} methods because that would # cause env.subst() to be called twice on the file name, # interfering with files that have $$ in them.) factory = getattr(self.fs, name) return factory @SCons.Memoize.CountMethodCall def _gsm(self): try: return self._memo['_gsm'] except KeyError: pass result = {} try: scanners = self._dict['SCANNERS'] except KeyError: pass else: # Reverse the scanner list so that, if multiple scanners # claim they can scan the same suffix, earlier scanners # in the list will overwrite later scanners, so that # the result looks like a "first match" to the user. if not is_List(scanners): scanners = [scanners] else: scanners = scanners[:] # copy so reverse() doesn't mod original scanners.reverse() for scanner in scanners: for k in scanner.get_skeys(self): if k and self['PLATFORM'] == 'win32': k = k.lower() result[k] = scanner self._memo['_gsm'] = result return result def get_scanner(self, skey): """Find the appropriate scanner given a key (usually a file suffix). """ if skey and self['PLATFORM'] == 'win32': skey = skey.lower() return self._gsm().get(skey) def scanner_map_delete(self, kw=None): """Delete the cached scanner map (if we need to). """ try: del self._memo['_gsm'] except KeyError: pass def _update(self, other): """Private method to update an environment's consvar dict directly. Bypasses the normal checks that occur when users try to set items. """ self._dict.update(other) def _update_onlynew(self, other): """Private method to add new items to an environment's consvar dict. Only adds items from `other` whose keys do not already appear in the existing dict; values from `other` are not used for replacement. Bypasses the normal checks that occur when users try to set items. """ for k, v in other.items(): if k not in self._dict: self._dict[k] = v def get_src_sig_type(self): try: return self.src_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().src_sig_type self.src_sig_type = t return t def get_tgt_sig_type(self): try: return self.tgt_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().tgt_sig_type self.tgt_sig_type = t return t ####################################################################### # Public methods for manipulating an Environment. These begin with # upper-case letters. The essential characteristic of methods in # this section is that they do *not* have corresponding same-named # global functions. For example, a stand-alone Append() function # makes no sense, because Append() is all about appending values to # an Environment's construction variables. ####################################################################### def Append(self, **kw): """Append values to construction variables in an Environment. The variable is created if it is not already present. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): try: if key == 'CPPDEFINES' and is_String(self._dict[key]): self._dict[key] = [self._dict[key]] orig = self._dict[key] except KeyError: # No existing var in the environment, so set to the new value. if key == 'CPPDEFINES' and is_String(val): self._dict[key] = [val] else: self._dict[key] = val continue try: # Check if the original looks like a dict: has .update? update_dict = orig.update except AttributeError: try: # Just try to add them together. This will work # in most cases, when the original and new values # are compatible types. self._dict[key] = orig + val except (KeyError, TypeError): try: # Check if the original is a list: has .append? add_to_orig = orig.append except AttributeError: # The original isn't a list, but the new # value is (by process of elimination), # so insert the original in the new value # (if there's one to insert) and replace # the variable with it. if orig: val.insert(0, orig) self._dict[key] = val else: # The original is a list, so append the new # value to it (if there's a value to append). if val: add_to_orig(val) continue # The original looks like a dictionary, so update it # based on what we think the value looks like. # We can't just try adding the value because # dictionaries don't have __add__() methods, and # things like UserList will incorrectly coerce the # original dict to a list (which we don't want). if is_List(val): if key == 'CPPDEFINES': tmp = [] for (k, v) in orig.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) orig = tmp orig += val self._dict[key] = orig else: for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.scanner_map_delete(kw) def _canonicalize(self, path): """Allow Dirs and strings beginning with # for top-relative. Note this uses the current env's fs (in self). """ if not is_String(path): # typically a Dir path = str(path) if path and path[0] == '#': path = str(self.fs.Dir(path)) return path def AppendENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=0): """Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the end (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = AppendPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def AppendUnique(self, delete_existing=0, **kw): """Append values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to end. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): if is_List(val): val = _delete_duplicates(val, delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif is_Dict(self._dict[key]) and is_Dict(val): self._dict[key].update(val) elif is_List(val): dk = self._dict[key] if key == 'CPPDEFINES': tmp = [] for i in val: if is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif is_Tuple(i): tmp.append(i) else: tmp.append((i,)) val = tmp # Construct a list of (key, value) tuples. if is_Dict(dk): tmp = [] for (k, v) in dk.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) dk = tmp elif is_String(dk): dk = [(dk,)] else: tmp = [] for i in dk: if is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp else: if not is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = dk + val else: dk = self._dict[key] if is_List(dk): if key == 'CPPDEFINES': tmp = [] for i in dk: if is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp # Construct a list of (key, value) tuples. if is_Dict(val): tmp = [] for (k, v) in val.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) val = tmp elif is_String(val): val = [(val,)] if delete_existing: dk = list(filter(lambda x, val=val: x not in val, dk)) self._dict[key] = dk + val else: dk = [x for x in dk if x not in val] self._dict[key] = dk + val else: # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = list(filter(lambda x, val=val: x not in val, dk)) self._dict[key] = dk + [val] else: if val not in dk: self._dict[key] = dk + [val] else: if key == 'CPPDEFINES': if is_String(dk): dk = [dk] elif is_Dict(dk): tmp = [] for (k, v) in dk.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) dk = tmp if is_String(val): if val in dk: val = [] else: val = [val] elif is_Dict(val): tmp = [] for i,j in val.items(): if j is not None: tmp.append((i,j)) else: tmp.append(i) val = tmp if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = dk + val self.scanner_map_delete(kw) def Clone(self, tools=[], toolpath=None, parse_flags = None, **kw): """Return a copy of a construction Environment. The copy is like a Python "deep copy"--that is, independent copies are made recursively of each objects--except that a reference is copied when an object is not deep-copyable (like a function). There are no references to any mutable objects in the original Environment. """ builders = self._dict.get('BUILDERS', {}) clone = copy.copy(self) # BUILDERS is not safe to do a simple copy clone._dict = semi_deepcopy_dict(self._dict, ['BUILDERS']) clone._dict['BUILDERS'] = BuilderDict(builders, clone) # Check the methods added via AddMethod() and re-bind them to # the cloned environment. Only do this if the attribute hasn't # been overwritten by the user explicitly and still points to # the added method. clone.added_methods = [] for mw in self.added_methods: if mw == getattr(self, mw.name): clone.added_methods.append(mw.clone(clone)) clone._memo = {} # Apply passed-in variables before the tools # so the tools can use the new variables kw = copy_non_reserved_keywords(kw) new = {} for key, value in kw.items(): new[key] = SCons.Subst.scons_subst_once(value, self, key) clone.Replace(**new) apply_tools(clone, tools, toolpath) # apply them again in case the tools overwrote them clone.Replace(**new) # Finally, apply any flags to be merged in if parse_flags: clone.MergeFlags(parse_flags) if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.EnvironmentClone') return clone def _changed_build(self, dependency, target, prev_ni, repo_node=None): if dependency.changed_state(target, prev_ni, repo_node): return 1 return self.decide_source(dependency, target, prev_ni, repo_node) def _changed_content(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_content(target, prev_ni, repo_node) def _changed_source(self, dependency, target, prev_ni, repo_node=None): target_env = dependency.get_build_env() type = target_env.get_tgt_sig_type() if type == 'source': return target_env.decide_source(dependency, target, prev_ni, repo_node) else: return target_env.decide_target(dependency, target, prev_ni, repo_node) def _changed_timestamp_then_content(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_then_content(target, prev_ni, repo_node) def _changed_timestamp_newer(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_newer(target, prev_ni, repo_node) def _changed_timestamp_match(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_match(target, prev_ni, repo_node) def Decider(self, function): self.cache_timestamp_newer = False if function in ('MD5', 'content'): # TODO: Handle if user requests MD5 and not content with deprecation notice function = self._changed_content elif function in ('MD5-timestamp', 'content-timestamp'): function = self._changed_timestamp_then_content elif function in ('timestamp-newer', 'make'): function = self._changed_timestamp_newer self.cache_timestamp_newer = True elif function == 'timestamp-match': function = self._changed_timestamp_match elif not callable(function): raise UserError("Unknown Decider value %s" % repr(function)) # We don't use AddMethod because we don't want to turn the # function, which only expects three arguments, into a bound # method, which would add self as an initial, fourth argument. self.decide_target = function self.decide_source = function def Detect(self, progs): """Return the first available program from one or more possibilities. Args: progs (str or list): one or more command names to check for """ if not is_List(progs): progs = [progs] for prog in progs: path = self.WhereIs(prog) if path: return prog return None def Dictionary(self, *args): r"""Return construction variables from an environment. Args: \*args (optional): variable names to look up Returns: If `args` omitted, the dictionary of all construction variables. If one arg, the corresponding value is returned. If more than one arg, a list of values is returned. Raises: KeyError: if any of `args` is not in the construction environment. """ if not args: return self._dict dlist = [self._dict[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist def Dump(self, key=None, format='pretty'): """ Return construction variables serialized to a string. Args: key (optional): if None, format the whole dict of variables. Else format the value of `key` (Default value = None) format (str, optional): specify the format to serialize to. `"pretty"` generates a pretty-printed string, `"json"` a JSON-formatted string. (Default value = `"pretty"`) """ if key: cvars = self.Dictionary(key) else: cvars = self.Dictionary() fmt = format.lower() if fmt == 'pretty': import pprint pp = pprint.PrettyPrinter(indent=2) # TODO: pprint doesn't do a nice job on path-style values # if the paths contain spaces (i.e. Windows), because the # algorithm tries to break lines on spaces, while breaking # on the path-separator would be more "natural". Is there # a better way to format those? return pp.pformat(cvars) elif fmt == 'json': import json def non_serializable(obj): return str(type(obj).__qualname__) return json.dumps(cvars, indent=4, default=non_serializable) else: raise ValueError("Unsupported serialization format: %s." % fmt) def FindIxes(self, paths, prefix, suffix): """Search a list of paths for something that matches the prefix and suffix. Args: paths: the list of paths or nodes. prefix: construction variable for the prefix. suffix: construction variable for the suffix. Returns: the matched path or None """ suffix = self.subst('$'+suffix) prefix = self.subst('$'+prefix) for path in paths: name = os.path.basename(str(path)) if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix: return path def ParseConfig(self, command, function=None, unique=True): """ Use the specified function to parse the output of the command in order to modify the current environment. The 'command' can be a string or a list of strings representing a command and its arguments. 'Function' is an optional argument that takes the environment, the output of the command, and the unique flag. If no function is specified, MergeFlags, which treats the output as the result of a typical 'X-config' command (i.e. gtk-config), will merge the output into the appropriate variables. """ if function is None: def parse_conf(env, cmd, unique=unique): return env.MergeFlags(cmd, unique) function = parse_conf if is_List(command): command = ' '.join(command) command = self.subst(command) return function(self, self.backtick(command)) def ParseDepends(self, filename, must_exist=None, only_one=False): """ Parse a mkdep-style file for explicit dependencies. This is completely abusable, and should be unnecessary in the "normal" case of proper SCons configuration, but it may help make the transition from a Make hierarchy easier for some people to swallow. It can also be genuinely useful when using a tool that can write a .d file, but for which writing a scanner would be too complicated. """ filename = self.subst(filename) try: with open(filename, 'r') as fp: lines = LogicalLines(fp).readlines() except IOError: if must_exist: raise return lines = [l for l in lines if l[0] != '#'] tdlist = [] for line in lines: try: target, depends = line.split(':', 1) except (AttributeError, ValueError): # Throws AttributeError if line isn't a string. Can throw # ValueError if line doesn't split into two or more elements. pass else: tdlist.append((target.split(), depends.split())) if only_one: targets = [] for td in tdlist: targets.extend(td[0]) if len(targets) > 1: raise UserError( "More than one dependency target found in `%s': %s" % (filename, targets)) for target, depends in tdlist: self.Depends(target, depends) def Platform(self, platform): platform = self.subst(platform) return SCons.Platform.Platform(platform)(self) def Prepend(self, **kw): """Prepend values to construction variables in an Environment. The variable is created if it is not already present. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): try: orig = self._dict[key] except KeyError: # No existing var in the environment so set to the new value. self._dict[key] = val continue try: # Check if the original looks like a dict: has .update? update_dict = orig.update except AttributeError: try: # Just try to add them together. This will work # in most cases, when the original and new values # are compatible types. self._dict[key] = val + orig except (KeyError, TypeError): try: # Check if the added value is a list: has .append? add_to_val = val.append except AttributeError: # The added value isn't a list, but the # original is (by process of elimination), # so insert the the new value in the original # (if there's one to insert). if val: orig.insert(0, val) else: # The added value is a list, so append # the original to it (if there's a value # to append) and replace the original. if orig: add_to_val(orig) self._dict[key] = val continue # The original looks like a dictionary, so update it # based on what we think the value looks like. # We can't just try adding the value because # dictionaries don't have __add__() methods, and # things like UserList will incorrectly coerce the # original dict to a list (which we don't want). if is_List(val): for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.scanner_map_delete(kw) def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1): """Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the front (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = PrependPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def PrependUnique(self, delete_existing=0, **kw): """Prepend values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to front. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): if is_List(val): val = _delete_duplicates(val, not delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif is_Dict(self._dict[key]) and is_Dict(val): self._dict[key].update(val) elif is_List(val): dk = self._dict[key] if not is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = val + dk else: dk = self._dict[key] if is_List(dk): # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = [val] + dk else: if val not in dk: self._dict[key] = [val] + dk else: if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = val + dk self.scanner_map_delete(kw) def Replace(self, **kw): """Replace existing construction variables in an Environment with new construction variables and/or values. """ try: kwbd = kw['BUILDERS'] except KeyError: pass else: kwbd = BuilderDict(kwbd,self) del kw['BUILDERS'] self.__setitem__('BUILDERS', kwbd) kw = copy_non_reserved_keywords(kw) self._update(semi_deepcopy(kw)) self.scanner_map_delete(kw) def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix): """ Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - construction variable for the new prefix. new_suffix - construction variable for the new suffix. """ old_prefix = self.subst('$'+old_prefix) old_suffix = self.subst('$'+old_suffix) new_prefix = self.subst('$'+new_prefix) new_suffix = self.subst('$'+new_suffix) dir,name = os.path.split(str(path)) if name[:len(old_prefix)] == old_prefix: name = name[len(old_prefix):] if name[-len(old_suffix):] == old_suffix: name = name[:-len(old_suffix)] return os.path.join(dir, new_prefix+name+new_suffix) def SetDefault(self, **kw): for k in list(kw.keys()): if k in self._dict: del kw[k] self.Replace(**kw) def _find_toolpath_dir(self, tp): return self.fs.Dir(self.subst(tp)).srcnode().get_abspath() def Tool(self, tool, toolpath=None, **kwargs) -> SCons.Tool.Tool: if is_String(tool): tool = self.subst(tool) if toolpath is None: toolpath = self.get('toolpath', []) toolpath = list(map(self._find_toolpath_dir, toolpath)) tool = SCons.Tool.Tool(tool, toolpath, **kwargs) tool(self) return tool def WhereIs(self, prog, path=None, pathext=None, reject=None): """Find prog in the path. """ if not prog: # nothing to search for, just give up return None if path is None: try: path = self['ENV']['PATH'] except KeyError: pass elif is_String(path): path = self.subst(path) if pathext is None: try: pathext = self['ENV']['PATHEXT'] except KeyError: pass elif is_String(pathext): pathext = self.subst(pathext) prog = CLVar(self.subst(prog)) # support "program --with-args" path = WhereIs(prog[0], path, pathext, reject) if path: return path return None ####################################################################### # Public methods for doing real "SCons stuff" (manipulating # dependencies, setting attributes on targets, etc.). These begin # with upper-case letters. The essential characteristic of methods # in this section is that they all *should* have corresponding # same-named global functions. ####################################################################### def Action(self, *args, **kw): def subst_string(a, self=self): if is_String(a): a = self.subst(a) return a nargs = list(map(subst_string, args)) nkw = self.subst_kw(kw) return SCons.Action.Action(*nargs, **nkw) def AddPreAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_pre_action(action) return nodes def AddPostAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_post_action(action) return nodes def Alias(self, target, source=[], action=None, **kw): tlist = self.arg2nodes(target, self.ans.Alias) if not is_List(source): source = [source] source = [_f for _f in source if _f] if not action: if not source: # There are no source files and no action, so just # return a target list of classic Alias Nodes, without # any builder. The externally visible effect is that # this will make the wrapping Script.BuildTask class # say that there's "Nothing to be done" for this Alias, # instead of that it's "up to date." return tlist # No action, but there are sources. Re-call all the target # builders to add the sources to each target. result = [] for t in tlist: bld = t.get_builder(AliasBuilder) result.extend(bld(self, t, source)) return result nkw = self.subst_kw(kw) nkw.update({ 'action' : SCons.Action.Action(action), 'source_factory' : self.fs.Entry, 'multi' : 1, 'is_explicit' : None, }) bld = SCons.Builder.Builder(**nkw) # Apply the Builder separately to each target so that the Aliases # stay separate. If we did one "normal" Builder call with the # whole target list, then all of the target Aliases would be # associated under a single Executor. result = [] for t in tlist: # Calling the convert() method will cause a new Executor to be # created from scratch, so we have to explicitly initialize # it with the target's existing sources, plus our new ones, # so nothing gets lost. b = t.get_builder() if b is None or b is AliasBuilder: b = bld else: nkw['action'] = b.action + action b = SCons.Builder.Builder(**nkw) t.convert() result.extend(b(self, t, t.sources + source)) return result def AlwaysBuild(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_always_build() return tlist def Builder(self, **kw): nkw = self.subst_kw(kw) return SCons.Builder.Builder(**nkw) def CacheDir(self, path, custom_class=None): if path is not None: path = self.subst(path) self._CacheDir_path = path if custom_class: self['CACHEDIR_CLASS'] = self.validate_CacheDir_class(custom_class) if SCons.Action.execute_actions: # Only initialize the CacheDir if -n/-no_exec was NOT specified. # Now initialized the CacheDir and prevent a race condition which can # happen when there's no existing cache dir and you are building with # multiple threads, but initializing it before the task walk starts self.get_CacheDir() def Clean(self, targets, files): global CleanTargets tlist = self.arg2nodes(targets, self.fs.Entry) flist = self.arg2nodes(files, self.fs.Entry) for t in tlist: try: CleanTargets[t].extend(flist) except KeyError: CleanTargets[t] = flist def Configure(self, *args, **kw): nargs = [self] if args: nargs = nargs + self.subst_list(args)[0] nkw = self.subst_kw(kw) nkw['_depth'] = kw.get('_depth', 0) + 1 try: nkw['custom_tests'] = self.subst_kw(nkw['custom_tests']) except KeyError: pass return SCons.SConf.SConf(*nargs, **nkw) def Command(self, target, source, action, **kw): """Builds the supplied target files from the supplied source files using the supplied action. Action may be any type that the Builder constructor will accept for an action.""" bkw = { 'action': action, 'target_factory': self.fs.Entry, 'source_factory': self.fs.Entry, } # source scanner try: bkw['source_scanner'] = kw['source_scanner'] except KeyError: pass else: del kw['source_scanner'] # target scanner try: bkw['target_scanner'] = kw['target_scanner'] except KeyError: pass else: del kw['target_scanner'] # source factory try: bkw['source_factory'] = kw['source_factory'] except KeyError: pass else: del kw['source_factory'] # target factory try: bkw['target_factory'] = kw['target_factory'] except KeyError: pass else: del kw['target_factory'] bld = SCons.Builder.Builder(**bkw) return bld(self, target, source, **kw) def Depends(self, target, dependency): """Explicity specify that 'target's depend on 'dependency'.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_dependency(dlist) return tlist def Dir(self, name, *args, **kw): """ """ s = self.subst(name) if is_Sequence(s): result=[] for e in s: result.append(self.fs.Dir(e, *args, **kw)) return result return self.fs.Dir(s, *args, **kw) def PyPackageDir(self, modulename): s = self.subst(modulename) if is_Sequence(s): result=[] for e in s: result.append(self.fs.PyPackageDir(e)) return result return self.fs.PyPackageDir(s) def NoClean(self, *targets): """Tags a target so that it will not be cleaned by -c""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_noclean() return tlist def NoCache(self, *targets): """Tags a target so that it will not be cached""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_nocache() return tlist def Entry(self, name, *args, **kw): """ """ s = self.subst(name) if is_Sequence(s): result=[] for e in s: result.append(self.fs.Entry(e, *args, **kw)) return result return self.fs.Entry(s, *args, **kw) def Environment(self, **kw): return SCons.Environment.Environment(**self.subst_kw(kw)) def Execute(self, action, *args, **kw): """Directly execute an action through an Environment """ action = self.Action(action, *args, **kw) result = action([], [], self) if isinstance(result, BuildError): errstr = result.errstr if result.filename: errstr = result.filename + ': ' + errstr sys.stderr.write("scons: *** %s\n" % errstr) return result.status else: return result def File(self, name, *args, **kw): """ """ s = self.subst(name) if is_Sequence(s): result=[] for e in s: result.append(self.fs.File(e, *args, **kw)) return result return self.fs.File(s, *args, **kw) def FindFile(self, file, dirs): file = self.subst(file) nodes = self.arg2nodes(dirs, self.fs.Dir) return SCons.Node.FS.find_file(file, tuple(nodes)) def Flatten(self, sequence): return flatten(sequence) def GetBuildPath(self, files): result = list(map(str, self.arg2nodes(files, self.fs.Entry))) if is_List(files): return result else: return result[0] def Glob(self, pattern, ondisk=True, source=False, strings=False, exclude=None): return self.fs.Glob(self.subst(pattern), ondisk, source, strings, exclude) def Ignore(self, target, dependency): """Ignore a dependency.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_ignore(dlist) return tlist def Literal(self, string): return SCons.Subst.Literal(string) def Local(self, *targets): ret = [] for targ in targets: if isinstance(targ, SCons.Node.Node): targ.set_local() ret.append(targ) else: for t in self.arg2nodes(targ, self.fs.Entry): t.set_local() ret.append(t) return ret def Precious(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_precious() return tlist def Pseudo(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_pseudo() return tlist def Repository(self, *dirs, **kw): dirs = self.arg2nodes(list(dirs), self.fs.Dir) self.fs.Repository(*dirs, **kw) def Requires(self, target, prerequisite): """Specify that 'prerequisite' must be built before 'target', (but 'target' does not actually depend on 'prerequisite' and need not be rebuilt if it changes).""" tlist = self.arg2nodes(target, self.fs.Entry) plist = self.arg2nodes(prerequisite, self.fs.Entry) for t in tlist: t.add_prerequisite(plist) return tlist def Scanner(self, *args, **kw): nargs = [] for arg in args: if is_String(arg): arg = self.subst(arg) nargs.append(arg) nkw = self.subst_kw(kw) return SCons.Scanner.ScannerBase(*nargs, **nkw) def SConsignFile(self, name=SCons.SConsign.current_sconsign_filename(), dbm_module=None): if name is not None: name = self.subst(name) if not os.path.isabs(name): name = os.path.join(str(self.fs.SConstruct_dir), name) if name: name = os.path.normpath(name) sconsign_dir = os.path.dirname(name) if sconsign_dir and not os.path.exists(sconsign_dir): self.Execute(SCons.Defaults.Mkdir(sconsign_dir)) SCons.SConsign.File(name, dbm_module) def SideEffect(self, side_effect, target): """Tell scons that side_effects are built as side effects of building targets.""" side_effects = self.arg2nodes(side_effect, self.fs.Entry) targets = self.arg2nodes(target, self.fs.Entry) added_side_effects = [] for side_effect in side_effects: if side_effect.multiple_side_effect_has_builder(): raise UserError("Multiple ways to build the same target were specified for: %s" % str(side_effect)) side_effect.add_source(targets) side_effect.side_effect = 1 self.Precious(side_effect) added = False for target in targets: if side_effect not in target.side_effects: target.side_effects.append(side_effect) added = True if added: added_side_effects.append(side_effect) return added_side_effects def Split(self, arg): """This function converts a string or list into a list of strings or Nodes. This makes things easier for users by allowing files to be specified as a white-space separated list to be split. The input rules are: - A single string containing names separated by spaces. These will be split apart at the spaces. - A single Node instance - A list containing either strings or Node instances. Any strings in the list are not split at spaces. In all cases, the function returns a list of Nodes and strings.""" if is_List(arg): return list(map(self.subst, arg)) elif is_String(arg): return self.subst(arg).split() else: return [self.subst(arg)] def Value(self, value, built_value=None, name=None): """ """ return SCons.Node.Python.ValueWithMemo(value, built_value, name) def VariantDir(self, variant_dir, src_dir, duplicate=1): variant_dir = self.arg2nodes(variant_dir, self.fs.Dir)[0] src_dir = self.arg2nodes(src_dir, self.fs.Dir)[0] self.fs.VariantDir(variant_dir, src_dir, duplicate) def FindSourceFiles(self, node='.'): """ returns a list of all source files. """ node = self.arg2nodes(node, self.fs.Entry)[0] sources = [] def build_source(ss): for s in ss: if isinstance(s, SCons.Node.FS.Dir): build_source(s.all_children()) elif s.has_builder(): build_source(s.sources) elif isinstance(s.disambiguate(), SCons.Node.FS.File): sources.append(s) build_source(node.all_children()) def final_source(node): while node != node.srcnode(): node = node.srcnode() return node sources = list(map(final_source, sources)) # remove duplicates return list(set(sources)) def FindInstalledFiles(self): """ returns the list of all targets of the Install and InstallAs Builder. """ from SCons.Tool import install if install._UNIQUE_INSTALLED_FILES is None: install._UNIQUE_INSTALLED_FILES = uniquer_hashables(install._INSTALLED_FILES) return install._UNIQUE_INSTALLED_FILES class OverrideEnvironment(Base): """A proxy that overrides variables in a wrapped construction environment by returning values from an overrides dictionary in preference to values from the underlying subject environment. This is a lightweight (I hope) proxy that passes through most use of attributes to the underlying Environment.Base class, but has just enough additional methods defined to act like a real construction environment with overridden values. It can wrap either a Base construction environment, or another OverrideEnvironment, which can in turn nest arbitrary OverrideEnvironments... Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we get most of those from proxying the attributes of the subject construction environment. But because we subclass SubstitutionEnvironment, this class also has inherited arg2nodes() and subst*() methods; those methods can't be proxied because they need *this* object's methods to fetch the values from the overrides dictionary. """ def __init__(self, subject, overrides=None): if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.OverrideEnvironment') self.__dict__['__subject'] = subject if overrides is None: self.__dict__['overrides'] = dict() else: self.__dict__['overrides'] = overrides # Methods that make this class act like a proxy. def __getattr__(self, name): attr = getattr(self.__dict__['__subject'], name) # Here we check if attr is one of the Wrapper classes. For # example when a pseudo-builder is being called from an # OverrideEnvironment. # # These wrappers when they're constructed capture the # Environment they are being constructed with and so will not # have access to overrided values. So we rebuild them with the # OverrideEnvironment so they have access to overrided values. if isinstance(attr, MethodWrapper): return attr.clone(self) else: return attr def __setattr__(self, name, value): setattr(self.__dict__['__subject'], name, value) # Methods that make this class act like a dictionary. def __getitem__(self, key): try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].__getitem__(key) def __setitem__(self, key, value): if not is_valid_construction_var(key): raise UserError("Illegal construction variable `%s'" % key) self.__dict__['overrides'][key] = value def __delitem__(self, key): try: del self.__dict__['overrides'][key] except KeyError: deleted = 0 else: deleted = 1 try: result = self.__dict__['__subject'].__delitem__(key) except KeyError: if not deleted: raise result = None return result def get(self, key, default=None): """Emulates the get() method of dictionaries.""" try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].get(key, default) def __contains__(self, key): if key in self.__dict__['overrides']: return True return key in self.__dict__['__subject'] def Dictionary(self, *args): d = self.__dict__['__subject'].Dictionary().copy() d.update(self.__dict__['overrides']) if not args: return d dlist = [d[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist def items(self): """Emulates the items() method of dictionaries.""" return self.Dictionary().items() def keys(self): """Emulates the keys() method of dictionaries.""" return self.Dictionary().keys() def values(self): """Emulates the values() method of dictionaries.""" return self.Dictionary().values() def setdefault(self, key, default=None): """Emulates the setdefault() method of dictionaries.""" try: return self.__getitem__(key) except KeyError: self.__dict__['overrides'][key] = default return default # Overridden private construction environment methods. def _update(self, other): self.__dict__['overrides'].update(other) def _update_onlynew(self, other): for k, v in other.items(): if k not in self.__dict__['overrides']: self.__dict__['overrides'][k] = v def gvars(self): return self.__dict__['__subject'].gvars() def lvars(self): lvars = self.__dict__['__subject'].lvars() lvars.update(self.__dict__['overrides']) return lvars # Overridden public construction environment methods. def Replace(self, **kw): kw = copy_non_reserved_keywords(kw) self.__dict__['overrides'].update(semi_deepcopy(kw)) # The entry point that will be used by the external world # to refer to a construction environment. This allows the wrapper # interface to extend a construction environment for its own purposes # by subclassing SCons.Environment.Base and then assigning the # class to SCons.Environment.Environment. Environment = Base def NoSubstitutionProxy(subject): """ An entry point for returning a proxy subclass instance that overrides the subst*() methods so they don't actually perform construction variable substitution. This is specifically intended to be the shim layer in between global function calls (which don't want construction variable substitution) and the DefaultEnvironment() (which would substitute variables if left to its own devices). We have to wrap this in a function that allows us to delay definition of the class until it's necessary, so that when it subclasses Environment it will pick up whatever Environment subclass the wrapper interface might have assigned to SCons.Environment.Environment. """ class _NoSubstitutionProxy(Environment): def __init__(self, subject): self.__dict__['__subject'] = subject def __getattr__(self, name): return getattr(self.__dict__['__subject'], name) def __setattr__(self, name, value): return setattr(self.__dict__['__subject'], name, value) def executor_to_lvars(self, kwdict): if 'executor' in kwdict: kwdict['lvars'] = kwdict['executor'].get_lvars() del kwdict['executor'] else: kwdict['lvars'] = {} def raw_to_mode(self, dict): try: raw = dict['raw'] except KeyError: pass else: del dict['raw'] dict['mode'] = raw def subst(self, string, *args, **kwargs): return string def subst_kw(self, kw, *args, **kwargs): return kw def subst_list(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.Subst.scons_subst_list(*nargs, **nkw) def subst_target_source(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.Subst.scons_subst(*nargs, **nkw) return _NoSubstitutionProxy(subject) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
PypiClean
/Cartridge-1.3.4-py3-none-any.whl/cartridge/shop/defaults.py
from socket import gethostname from django.utils.translation import gettext_lazy as _ from mezzanine.conf import register_setting #################################################################### # This first set of settings already exists in Mezzanine but can # # be overridden or appended to here with Cartridge values. # #################################################################### # Add shop admin modules to the admin menu. register_setting( name="ADMIN_MENU_ORDER", description=_("Controls the ordering and grouping of the admin menu."), editable=False, default=( ( _("Content"), ( "pages.Page", "blog.BlogPost", "generic.ThreadedComment", (_("Media Library"), "fb_browse"), ), ), ( _("Shop"), ( "shop.Product", "shop.ProductOption", "shop.DiscountCode", "shop.Sale", "shop.Order", ), ), (_("Site"), ("sites.Site", "redirects.Redirect", "conf.Setting")), ( _("Users"), ( "auth.User", "auth.Group", ), ), ), ) # Add the product model to the list of search choices. register_setting( name="SEARCH_MODEL_CHOICES", description=_( "Sequence of models that will be provided by default as " "choices in the search form. Each model should be in the format " "``app_label.model_name``. Only models that subclass " "``mezzanine.core.models.Displayable`` should be used." ), editable=False, default=("shop.Product",), append=True, ) # Add the checkout URLs prefix to those forced to run over SSL. # Only relevant if SSL_ENABLED (defined in Mezzanine) is True. register_setting( name="SSL_FORCE_URL_PREFIXES", description="Sequence of URL prefixes that will be forced to run over " "SSL when ``SSL_ENABLED`` is ``True``. i.e. " "('/admin', '/example') would force all URLs beginning with " "/admin or /example to run over SSL.", editable=False, default=("/shop/checkout",), append=True, ) # Append the Cartridge settings used in templates to the list of settings # accessible in templates. register_setting( name="TEMPLATE_ACCESSIBLE_SETTINGS", description=_("Sequence of setting names available within templates."), editable=False, default=( "SHOP_CARD_TYPES", "SHOP_CATEGORY_USE_FEATURED_IMAGE", "SHOP_CHECKOUT_STEPS_SPLIT", "SHOP_PAYMENT_STEP_ENABLED", "SHOP_PRODUCT_SORT_OPTIONS", "SHOP_USE_RATINGS", "SHOP_USE_WISHLIST", "SHOP_USE_RELATED_PRODUCTS", "SHOP_USE_UPSELL_PRODUCTS", ), append=True, ) ########################################### # Remaining settings are all defined by # # Cartridge, prefixed with "SHOP_". # ########################################### register_setting( name="SHOP_CARD_TYPES", description="Sequence of available credit card types for payment.", editable=False, default=("Mastercard", "Visa", "Diners", "Amex"), ) register_setting( name="SHOP_CART_EXPIRY_MINUTES", description="Number of minutes of inactivity until carts are abandoned.", editable=False, default=30, ) register_setting( name="SHOP_CATEGORY_USE_FEATURED_IMAGE", description=_("Enable featured images in shop categories"), editable=False, default=False, ) register_setting( name="SHOP_CHECKOUT_ACCOUNT_REQUIRED", label=_("Checkout account required"), description=_("If True, users must create a login for the checkout process."), editable=True, default=False, ) register_setting( name="SHOP_CHECKOUT_STEPS_SPLIT", description="If True, the checkout process is split into separate " "billing/shipping and payment steps.", editable=False, default=True, ) register_setting( name="SHOP_CHECKOUT_STEPS_CONFIRMATION", description="If True, the checkout process has a final confirmation " "step before completion.", editable=False, default=True, ) register_setting( name="SHOP_PAYMENT_STEP_ENABLED", label=_("Payment Enabled"), description=_("If False, there is no payment step on the checkout process."), editable=False, default=True, ) register_setting( name="SHOP_CURRENCY_LOCALE", label=_("Currency Locale"), description="Controls the formatting of monetary values according to " "the locale module in the python standard library. If an empty " "string is used, will fall back to the system's locale.", editable=False, default="", translatable=True, ) register_setting( name="SHOP_DEFAULT_SHIPPING_VALUE", label=_("Default Shipping Cost"), description=_("Default cost of shipping when no custom shipping is implemented."), editable=True, default=10.0, ) register_setting( name="SHOP_DEFAULT_TAX_RATE", label=_("Default Tax Rate"), description=_("Default tax rate in % when no custom tax handling is implemented."), editable=True, default=0.0, ) register_setting( name="SHOP_DISCOUNT_FIELD_IN_CART", label=_("Discount in Cart"), description=_("Discount codes can be entered on the cart page."), editable=True, default=True, ) register_setting( name="SHOP_DISCOUNT_FIELD_IN_CHECKOUT", label=_("Discount in Checkout"), description=_("Discount codes can be entered on the first checkout step."), editable=True, default=True, ) register_setting( name="SHOP_HANDLER_BILLING_SHIPPING", label=_("Billing & Shipping Handler"), description="Dotted package path and class name of the function " "called upon submission of the billing/shipping checkout step. This " "is where shipping calculations can be performed and set using the " "function ``cartridge.shop.utils.set_shipping``.", editable=False, default="cartridge.shop.checkout.default_billship_handler", ) register_setting( name="SHOP_HANDLER_TAX", label=_("Tax Handler"), description="Dotted package path and class name of the function " "called upon submission of the billing/shipping checkout step. This " "is where tax calculations can be performed and set using the " "function ``cartridge.shop.utils.set_tax``.", editable=False, default="cartridge.shop.checkout.default_tax_handler", ) register_setting( name="SHOP_HANDLER_ORDER", label=_("Order Handler"), description="Dotted package path and class name of the function that " "is called once an order is successful and all of the order " "object's data has been created. This is where any custom order " "processing should be implemented.", editable=False, default="cartridge.shop.checkout.default_order_handler", ) register_setting( name="SHOP_HANDLER_PAYMENT", label=_("Payment Handler"), description="Dotted package path and class name of the function that " "is called upon submission of the payment checkout step. This is " "where integration with a payment gateway should be implemented.", editable=False, default="cartridge.shop.checkout.default_payment_handler", ) register_setting( name="SHOP_OPTION_TYPE_CHOICES", description="Sequence of value/name pairs for types of product options " "(e.g. Size, Colour).", editable=False, default=( (1, _("Size")), (2, _("Colour")), ), ) register_setting( name="SHOP_OPTION_ADMIN_ORDER", description="Sequence of indexes from the ``SHOP_OPTION_TYPE_CHOICES`` " "setting that control how the options should be ordered in the " "admin, eg given the default for ``SHOP_OPTION_ADMIN_ORDER``, to " "order by Colour then Size we'd use (2, 1)", editable=False, default=(), ) register_setting( name="SHOP_ORDER_EMAIL_SUBJECT", label=_("Order Email Subject"), description=_("Subject to be used when sending the order receipt email."), editable=True, default=_("Order Receipt"), translatable=True, ) register_setting( name="SHOP_ORDER_FROM_EMAIL", label=_("From Email"), description=_("Email address from which order receipts should be emailed."), editable=True, default="do_not_reply@%s" % gethostname(), ) register_setting( name="SHOP_ORDER_EMAIL_BCC", label=_("BCC receipts to"), description=_("All order receipts will be BCCd to this address."), editable=True, default="", ) register_setting( name="SHOP_ORDER_STATUS_CHOICES", description="Sequence of value/name pairs for order statuses.", editable=False, default=( (1, _("Unprocessed")), (2, _("Processed")), ), ) register_setting( name="SHOP_PER_PAGE_CATEGORY", label=_("Products Per Category Page"), description=_("Number of products to display per category page."), editable=True, default=12, ) register_setting( name="SHOP_PRODUCT_SORT_OPTIONS", description="Sequence of description/field+direction pairs defining " "the options available for sorting a list of products.", editable=False, default=( (_("Recently added"), "-date_added"), (_("Highest rated"), "-rating_average"), (_("Least expensive"), "unit_price"), (_("Most expensive"), "-unit_price"), ), ) register_setting( name="SHOP_TAX_INCLUDED", label=_("Tax included"), description="If True, tax is already included in a product's price.", editable=False, default=False, ) register_setting( name="SHOP_USE_VARIATIONS", label=_("Use product variations"), description="Use product variations.", editable=False, default=True, ) register_setting( name="SHOP_USE_RATINGS", label=_("Use product ratings"), description="Show the product rating form, and allow browsing by rating.", editable=False, default=True, ) register_setting( name="SHOP_USE_WISHLIST", label=_("Use product wishlist"), description="Show the links to the wishlist, and allow adding products to it.", editable=False, default=True, ) register_setting( name="SHOP_USE_RELATED_PRODUCTS", label=_("Use related products"), description="Show related products in templates, and allow " "editing them in the admin.", editable=False, default=True, ) register_setting( name="SHOP_USE_UPSELL_PRODUCTS", label=_("Use upsell products"), description="Show upsell products in templates, and allow " "editing them in the admin.", editable=False, default=True, )
PypiClean
/CellProfiler-4.2.6.tar.gz/CellProfiler-4.2.6/cellprofiler/modules/maskobjects.py
import matplotlib.cm import numpy import scipy.ndimage from cellprofiler_core.constants.measurement import ( COLTYPE_INTEGER, FF_PARENT, FF_CHILDREN_COUNT, ) from cellprofiler_core.module import Identify from cellprofiler_core.object import Objects from cellprofiler_core.preferences import get_primary_outline_color from cellprofiler_core.preferences import get_secondary_outline_color from cellprofiler_core.setting import Binary from cellprofiler_core.setting.choice import Choice from cellprofiler_core.setting.subscriber import LabelSubscriber, ImageSubscriber from cellprofiler_core.setting.text import Float, LabelName from cellprofiler_core.utilities.core.module.identify import ( add_object_count_measurements, add_object_location_measurements, get_object_measurement_columns, ) from cellprofiler_core.utilities.core.object import size_similarly from centrosome.cpmorphology import fixup_scipy_ndimage_result from centrosome.outline import outline from cellprofiler.modules import _help __doc__ = """\ MaskObjects =========== **MaskObjects** removes objects outside of a specified region or regions. This module allows you to delete the objects or portions of objects that are outside of a region (mask) you specify. For example, after identifying nuclei and tissue regions in previous **Identify** modules, you might want to exclude all nuclei that are outside of a tissue region. If using a masking image, the mask is composed of the foreground (white portions); if using a masking object, the mask is composed of the area within the object. You can choose to remove only the portion of each object that is outside of the region, remove the whole object if it is partially or fully outside of the region, or retain the whole object unless it is fully outside of the region. | ============ ============ =============== Supports 2D? Supports 3D? Respects masks? ============ ============ =============== YES NO YES ============ ============ =============== See also ^^^^^^^^ {HELP_ON_SAVING_OBJECTS} Measurements made by this module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ **Parent object measurements:** - *Count:* The number of new masked objects created from each parent object. **Masked object measurements:** - *Parent:* The label number of the parent object. - *Location_X, Location_Y:* The pixel (X,Y) coordinates of the center of mass of the masked objects. """.format( **{"HELP_ON_SAVING_OBJECTS": _help.HELP_ON_SAVING_OBJECTS} ) MC_OBJECTS = "Objects" MC_IMAGE = "Image" P_MASK = "Keep overlapping region" P_REMOVE = "Remove" P_KEEP = "Keep" P_REMOVE_PERCENTAGE = "Remove depending on overlap" R_RETAIN = "Retain" R_RENUMBER = "Renumber" # This dictionary is used by upgrade_settings to keep track of changes # to the above names. If you change them, please put the text of the # new names into the dictionary. S_DICTIONARY = { "Objects": MC_OBJECTS, "Image": MC_IMAGE, "Keep overlapping region": P_MASK, "Remove": P_REMOVE, "Remove depending on overlap": P_REMOVE_PERCENTAGE, "Keep": P_KEEP, "Retain": R_RETAIN, "Renumber": R_RENUMBER, } def s_lookup(x): """Look up the current value for a setting choice w/backwards compatibility x - setting value from pipeline """ return S_DICTIONARY.get(x, x) class MaskObjects(Identify): category = "Object Processing" module_name = "MaskObjects" variable_revision_number = 3 def create_settings(self): """Create the settings that control this module""" self.object_name = LabelSubscriber( "Select objects to be masked", "None", doc="""\ Select the objects that will be masked (that is, excluded in whole or in part based on the other settings in the module). You can choose from any objects created by a previous object processing module, such as **IdentifyPrimaryObjects**, **IdentifySecondaryObjects** or **IdentifyTertiaryObjects**. """, ) self.remaining_objects = LabelName( "Name the masked objects", "MaskedNuclei", doc="""\ Enter a name for the objects that remain after the masking operation. You can refer to the masked objects in subsequent modules by this name. """, ) self.mask_choice = Choice( "Mask using a region defined by other objects or by binary image?", [MC_OBJECTS, MC_IMAGE], doc="""\ You can mask your objects by defining a region using objects you previously identified in your pipeline (*%(MC_OBJECTS)s*) or by defining a region based on the white regions in a binary image previously loaded or created in your pipeline (*%(MC_IMAGE)s*). """ % globals(), ) self.masking_objects = LabelSubscriber( "Select the masking object", "None", doc="""\ *(Used only if mask is to be made from objects)* Select the objects that will be used to define the masking region. You can choose from any objects created by a previous object processing module, such as **IdentifyPrimaryObjects**, **IdentifySecondaryObjects**, or **IdentifyTertiaryObjects**. """, ) self.masking_image = ImageSubscriber( "Select the masking image", "None", doc="""\ *(Used only if mask is to be made from an image)* Select an image that was either loaded or created by a previous module. The image should be a binary image where the white portion of the image is the region(s) you will use for masking. Binary images can be loaded from disk using the **NamesAndTypes** module by selecting “Binary mask” for the image type. You can also create a binary image from a grayscale image using **ApplyThreshold**. """, ) self.wants_inverted_mask = Binary( "Invert the mask?", False, doc="""\ This option reverses the foreground/background relationship of the mask. - Select "*No*" for the mask to be composed of the foreground (white portion) of the masking image or the area within the masking objects. - Select "*Yes*" for the mask to instead be composed of the *background* (black portions) of the masking image or the area *outside* the masking objects. """ % globals(), ) self.overlap_choice = Choice( "Handling of objects that are partially masked", [P_MASK, P_KEEP, P_REMOVE, P_REMOVE_PERCENTAGE], doc="""\ An object might partially overlap the mask region, with pixels both inside and outside the region. **MaskObjects** can handle this in one of three ways: - *%(P_MASK)s:* Choosing this option will reduce the size of partially overlapping objects. The part of the object that overlaps the masking region will be retained. The part of the object that is outside of the masking region will be removed. - *%(P_KEEP)s:* If you choose this option, **MaskObjects** will keep the whole object if any part of it overlaps the masking region. - *%(P_REMOVE)s:* Objects that are partially outside of the masking region will be completely removed if you choose this option. - *%(P_REMOVE_PERCENTAGE)s:* Determine whether to remove or keep an object depending on how much of the object overlaps the masking region. **MaskObjects** will keep an object if at least a certain fraction (which you enter below) of the object falls within the masking region. **MaskObjects** completely removes the object if too little of it overlaps the masking region.""" % globals(), ) self.overlap_fraction = Float( "Fraction of object that must overlap", 0.5, minval=0, maxval=1, doc="""\ *(Used only if removing based on overlap)* Specify the minimum fraction of an object that must overlap the masking region for that object to be retained. For instance, if the fraction is 0.75, then 3/4 of an object must be within the masking region for that object to be retained. """, ) self.retain_or_renumber = Choice( "Numbering of resulting objects", [R_RENUMBER, R_RETAIN], doc="""\ Choose how to number the objects that remain after masking, which controls how remaining objects are associated with their predecessors: - *%(R_RENUMBER)s:* The objects that remain will be renumbered using consecutive numbers. This is a good choice if you do not plan to use measurements from the original objects; your object measurements for the masked objects will not have gaps (where removed objects are missing). - *%(R_RETAIN)s:* The original labels for the objects will be retained. This allows any measurements you make from the masked objects to be directly aligned with measurements you might have made of the original, unmasked objects (or objects directly associated with them). """ % globals(), ) def settings(self): """The settings as they appear in the pipeline""" return [ self.object_name, self.remaining_objects, self.mask_choice, self.masking_objects, self.masking_image, self.overlap_choice, self.overlap_fraction, self.retain_or_renumber, self.wants_inverted_mask, ] def help_settings(self): """The settings as they appear in the pipeline""" return [ self.object_name, self.remaining_objects, self.mask_choice, self.masking_objects, self.masking_image, self.wants_inverted_mask, self.overlap_choice, self.overlap_fraction, self.retain_or_renumber, ] def visible_settings(self): """The settings as they appear in the UI""" result = [ self.object_name, self.remaining_objects, self.mask_choice, self.masking_image if self.mask_choice == MC_IMAGE else self.masking_objects, self.wants_inverted_mask, self.overlap_choice, ] if self.overlap_choice == P_REMOVE_PERCENTAGE: result += [self.overlap_fraction] result += [self.retain_or_renumber] return result def run(self, workspace): """Run the module on an image set""" object_name = self.object_name.value remaining_object_name = self.remaining_objects.value original_objects = workspace.object_set.get_objects(object_name) if self.mask_choice == MC_IMAGE: mask = workspace.image_set.get_image( self.masking_image.value, must_be_binary=True ) mask = mask.pixel_data else: masking_objects = workspace.object_set.get_objects( self.masking_objects.value ) mask = masking_objects.segmented > 0 if self.wants_inverted_mask: mask = ~mask # # Load the labels # labels = original_objects.segmented.copy() nobjects = numpy.max(labels) # # Resize the mask to cover the objects # mask, m1 = size_similarly(labels, mask) mask[~m1] = False # # Apply the mask according to the overlap choice. # if nobjects == 0: pass elif self.overlap_choice == P_MASK: labels = labels * mask else: pixel_counts = fixup_scipy_ndimage_result( scipy.ndimage.sum( mask, labels, numpy.arange(1, nobjects + 1, dtype=numpy.int32) ) ) if self.overlap_choice == P_KEEP: keep = pixel_counts > 0 else: total_pixels = fixup_scipy_ndimage_result( scipy.ndimage.sum( numpy.ones(labels.shape), labels, numpy.arange(1, nobjects + 1, dtype=numpy.int32), ) ) if self.overlap_choice == P_REMOVE: keep = pixel_counts == total_pixels elif self.overlap_choice == P_REMOVE_PERCENTAGE: fraction = self.overlap_fraction.value keep = pixel_counts / total_pixels >= fraction else: raise NotImplementedError( "Unknown overlap-handling choice: %s", self.overlap_choice.value ) keep = numpy.hstack(([False], keep)) labels[~keep[labels]] = 0 # # Renumber the labels matrix if requested # if self.retain_or_renumber == R_RENUMBER: unique_labels = numpy.unique(labels[labels != 0]) indexer = numpy.zeros(nobjects + 1, int) indexer[unique_labels] = numpy.arange(1, len(unique_labels) + 1) labels = indexer[labels] parent_objects = unique_labels else: parent_objects = numpy.arange(1, nobjects + 1) # # Add the objects # remaining_objects = Objects() remaining_objects.segmented = labels remaining_objects.unedited_segmented = original_objects.unedited_segmented workspace.object_set.add_objects(remaining_objects, remaining_object_name) # # Add measurements # m = workspace.measurements m.add_measurement( remaining_object_name, FF_PARENT % object_name, parent_objects, ) if numpy.max(original_objects.segmented) == 0: child_count = numpy.array([], int) else: child_count = fixup_scipy_ndimage_result( scipy.ndimage.sum( labels, original_objects.segmented, numpy.arange(1, nobjects + 1, dtype=numpy.int32), ) ) child_count = (child_count > 0).astype(int) m.add_measurement( object_name, FF_CHILDREN_COUNT % remaining_object_name, child_count, ) if self.retain_or_renumber == R_RETAIN: remaining_object_count = nobjects else: remaining_object_count = len(unique_labels) add_object_count_measurements(m, remaining_object_name, remaining_object_count) add_object_location_measurements(m, remaining_object_name, labels) # # Save the input, mask and output images for display # if self.show_window: workspace.display_data.original_labels = original_objects.segmented workspace.display_data.final_labels = labels workspace.display_data.mask = mask def display(self, workspace, figure): """Create an informative display for the module""" import matplotlib original_labels = workspace.display_data.original_labels final_labels = workspace.display_data.final_labels mask = workspace.display_data.mask # # Create a composition of the final labels and mask # outlines = outline(original_labels) > 0 cm = figure.return_cmap(numpy.max(original_labels)) sm = matplotlib.cm.ScalarMappable(cmap=cm) # # Paint the labels in color # image = sm.to_rgba(final_labels, norm=False)[:, :, :3] image[final_labels == 0, :] = 0 # # Make the mask a dark gray # image[(final_labels == 0) & mask, :] = 0.25 # # Make the outlines of the kept objects the primary color # and the outlines of removed objects red. # final_outlines = outline(final_labels) > 0 original_color = numpy.array(get_secondary_outline_color()[0:3], float) / 255 final_color = numpy.array(get_primary_outline_color()[0:3], float) / 255 image[outlines, :] = original_color[numpy.newaxis, :] image[final_outlines, :] = final_color[numpy.newaxis, :] figure.set_subplots((2, 1)) figure.subplot_imshow_labels( 0, 0, original_labels, title=self.object_name.value, colormap=sm, ) figure.subplot_imshow_color( 1, 0, image, title=self.remaining_objects.value, sharexy=figure.subplot(0, 0), colormap=sm, ) def get_measurement_columns(self, pipeline): """Return column definitions for measurements made by this module""" object_name = self.object_name.value remaining_object_name = self.remaining_objects.value columns = get_object_measurement_columns(self.remaining_objects.value) columns += [ (object_name, FF_CHILDREN_COUNT % remaining_object_name, COLTYPE_INTEGER,), (remaining_object_name, FF_PARENT % object_name, COLTYPE_INTEGER,), ] return columns def get_categories(self, pipeline, object_name): """Return the categories of measurements that this module produces object_name - return measurements made on this object (or 'Image' for image measurements) """ object_dictionary = self.get_object_dictionary() return self.get_object_categories(pipeline, object_name, object_dictionary) def get_object_dictionary(self): """Get the dictionary of parent child relationships see Identify.get_object_categories, Identify.get_object_measurements """ object_dictionary = {self.remaining_objects.value: [self.object_name.value]} return object_dictionary def get_measurements(self, pipeline, object_name, category): """Return names of the measurements made by this module pipeline - pipeline being run object_name - object being measured (or Image) category - category of measurement, for instance, "Location" """ return self.get_object_measurements( pipeline, object_name, category, self.get_object_dictionary() ) def validate_module(self, pipeline): """Bypass Identify.validate_module""" pass def upgrade_settings(self, setting_values, variable_revision_number, module_name): if variable_revision_number == 1: # Added "wants_inverted_mask" setting_values = setting_values + ["No"] variable_revision_number = 2 if variable_revision_number == 2: setting_values = setting_values[:-3] + setting_values[-1:] variable_revision_number = 3 setting_values = list(setting_values) setting_values[5] = s_lookup(setting_values[5]) setting_values[7] = s_lookup(setting_values[7]) return setting_values, variable_revision_number
PypiClean
/FEV_KEGG-1.1.4.tar.gz/FEV_KEGG-1.1.4/FEV_KEGG/Drawing/Export.py
from FEV_KEGG.Graph import Models import networkx.classes import os from enum import Enum from FEV_KEGG.Graph.SubstanceGraphs import SubstanceEcGraph import math from FEV_KEGG import settings LABEL_NAME = 'custom_label' """ Name of the attribute of the graph to be used for storing the label. """ COLOUR_NAME = 'colour' """ Name of the attribute of the graph to be used for storing the colour. """ DESCRIPTION_NAME = 'custom_description' """ Name of the attribute of the graph to be used for storing the description. """ ID_NAME = 'custom_id' """ Name of the attribute of the graph to be used for storing the id. """ REACTION_NAME = 'custom_reaction' """ Name of the attribute of the graph to be used for storing the reaction. """ MAJORITY_NAME = 'custom_majority' """ Name of the attribute of the graph to be used for storing the majority percentage. """ URL_NAME = 'URL' """ Name of the attribute of the graph to be used for storing the URL. """ def addLabelAttribute(nxGraph: networkx.classes.MultiGraph): """ Adds the "custom_label" attribute to each node and edge. Add an attribute to nodes and edges called "custom_label" (see module variable :attr:`LABEL_NAME`) containing the string of the node's label, or the edge's key's label, repectively. A label is defined as either the `.name` field, or if that is *None*, the id. This is especially useful if the tool you import this file into does not regularly read the XML's id parameter. For example, Cytoscape does not for edges. Parameters ---------- nxGraph : networkx.classes.MultiGraph A NetworkX graph object. """ if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError() # add label to edges edges = nxGraph.edges(keys = True) attributeDict = dict() for edge in edges: try: name = edge[2].name except AttributeError: name = None attributeDict[edge] = name if name is not None else edge[2].__str__() networkx.set_edge_attributes(nxGraph, attributeDict, LABEL_NAME) # add label to nodes nodes = nxGraph.nodes attributeDict = dict() for node in nodes: try: name = node.name except AttributeError: name = None attributeDict[node] = name if name is not None else node.__str__() networkx.set_node_attributes(nxGraph, attributeDict, LABEL_NAME) def addIdAttribute(nxGraph: networkx.classes.MultiGraph): """ Adds the "custom_id" attribute to each node and edge. Add an attribute to nodes and edges called "custom_id" (see module variable :attr:`ID_NAME`) containing the string of the node's id, or the edge's key's id, repectively. Parameters ---------- nxGraph : networkx.classes.MultiGraph A NetworkX graph object. """ if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError() # add label to edges edges = nxGraph.edges(keys = True) attributeDict = dict() for edge in edges: attributeDict[edge] = edge[2].__str__() networkx.set_edge_attributes(nxGraph, attributeDict, ID_NAME) # add label to nodes nodes = nxGraph.nodes attributeDict = dict() for node in nodes: attributeDict[node] = node.__str__() networkx.set_node_attributes(nxGraph, attributeDict, ID_NAME) def addDescriptionAttribute(nxGraph: networkx.classes.MultiGraph): """ Adds the "custom_description" attribute to each node and edge. Add an attribute to nodes and edges called "custom_description" (see module variable :attr:`DESCRIPTION_NAME`) containing the node's or edge's `.description` field, if there is any. Parameters ---------- nxGraph : networkx.classes.MultiGraph A NetworkX graph object. """ if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError() # add description to edges edges = nxGraph.edges(keys = True) attributeDict = dict() for edge in edges: try: attributeDict[edge] = edge[2].description if edge[2].description is not None else '' except AttributeError: continue networkx.set_edge_attributes(nxGraph, attributeDict, DESCRIPTION_NAME) # add description to nodes nodes = nxGraph.nodes attributeDict = dict() for node in nodes: try: attributeDict[node] = node.description if node.description is not None else '' except AttributeError: continue networkx.set_node_attributes(nxGraph, attributeDict, DESCRIPTION_NAME) def addReactionAttribute(nxGraph: networkx.classes.MultiGraph): """ Adds the "custom_reaction" attribute to each edge. Add an attribute to edges called "custom_reaction" (see module variable :attr:`REACTION_NAME`) containing the edge's `.reaction` field, if there is any. Parameters ---------- nxGraph : networkx.classes.MultiGraph A NetworkX graph object. """ if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError() # add reaction to edges edges = nxGraph.edges(keys = True) attributeDict = dict() for edge in edges: try: attributeDict[edge] = edge[2].reaction if edge[2].reaction is not None else '' except AttributeError: continue networkx.set_edge_attributes(nxGraph, attributeDict, REACTION_NAME) def addMajorityAttribute(graph: Models.CommonGraphApi, totalNumberOfOrganisms: int): """ Adds the "custom_majority" attribute to each node and edge. Add an attribute to nodes and edges called "custom_majority" (see module variable :attr:`MAJORITY_NAME`). It contains each node's or edge's majority percentage, if the graph contains counts (`graph.nodeCounts` or `graph.edgeCounts`, see :class:`FEV_KEGG.Graph.Models.CommonGraphApi`). For example, say edge A were to occur in 52 of all organisms used to create the `graph`, then ```graph.edgeCounts[A] == 52```. Now we have also ```totalNumberOfOrganisms == 76```. Then, we will write ```ceil(52/76*100) = 68``` into the "custom_majority" attribute. Parameters ---------- graph : Models.CommonGraphApi A graph object. totalNumberOfOrganisms : int Total number of organisms which were involved in creating the `graph`. This is used to calculate the percentage of counts. 100% == `totalNumberOfOrganisms`. """ nxGraph = graph.underlyingRawGraph if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError("This graph model can not be annotated for majority, yet.") # add majority to edges if graph.edgeCounts is not None: attributeDict = dict() for edge in graph.getEdges(): attributeDict[edge] = math.ceil(graph.edgeCounts.get(edge, 0) / totalNumberOfOrganisms * 100) networkx.set_edge_attributes(nxGraph, attributeDict, MAJORITY_NAME) # add majority to nodes if graph.nodeCounts is not None: attributeDict = dict() for node in graph.getNodes(): attributeDict[node] = math.ceil(graph.nodeCounts.get(node, 0) / totalNumberOfOrganisms * 100) networkx.set_node_attributes(nxGraph, attributeDict, MAJORITY_NAME) def addUrlAttribute(nxGraph: networkx.classes.MultiGraph): """ Adds the "URL" attribute to each edge. Add an attribute to edges called "URL" (see module variable :attr:`URL_NAME`) containing the edge's or node's URL to KEGG. Parameters ---------- nxGraph : networkx.classes.MultiGraph A NetworkX graph object. """ if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError() # add label to edges edges = nxGraph.edges(keys = True) attributeDict = dict() for edge in edges: attributeDict[edge] = edge[2].getUrl() if edge[2].getUrl() is not None else '' networkx.set_edge_attributes(nxGraph, attributeDict, URL_NAME) # add label to nodes nodes = nxGraph.nodes attributeDict = dict() for node in nodes: attributeDict[node] = node.getUrl() if node.getUrl() is not None else '' networkx.set_node_attributes(nxGraph, attributeDict, URL_NAME) class Colour(Enum): BLUE = '#4444FF' RED = '#FF5555' PINK = '#FF66FF' GREEN = '#55FF55' YELLOW = '#FFFF55' TURQUOISE = '#55FFFF' def addColourAttribute(graph: Models.CommonGraphApi, colour : Colour, nodes = False, edges = False): """ Adds the "colour" attribute to selected nodes/edges. If both, `nodes` and `edges` are *False*, nothing is coloured. Adds an attribute to nodes and edges called "colour" (see module variable :attr:`COLOUR_NAME`) containing the string of a hex value of a colour in RGB, see :class:`Colour`. Parameters ---------- graph : Models.CommonGraphApi A graph object. colour : Colour Colour to use. nodes : Iterable[NodeView] or bool, optional Nodes to be coloured, i.e. annotated with the "colour" attribute containing `colour`. If *True*, all nodes are coloured. edges : Iterable[EdgeView] or bool, optional Edges to be coloured, i.e. annotated with the "colour" attribute containing `colour`. If *True*, all edges are coloured. Warnings ---- Any operation on the resulting graph, e.g. :func:`FEV_KEGG.Graph.Models.CommonGraphApi.intersection`, removes the colouring. It actually removes all attributes. """ nxGraph = graph.underlyingRawGraph if not isinstance(nxGraph, networkx.classes.graph.Graph): raise NotImplementedError("This graph model can not be coloured, yet.") # add color to edges if edges is not False: # colour something if edges is True: # colour everything edgesToColour = nxGraph.edges else: # colour what is in `edges` edgesToColour = edges attributeDict = dict() for edge in edgesToColour: attributeDict[edge] = colour.value networkx.set_edge_attributes(nxGraph, attributeDict, COLOUR_NAME) # add color to nodes if nodes is not False: # colour something if nodes is True: # colour everything nodesToColour = nxGraph.nodes else: # colour what is in `nodes` nodesToColour = nodes attributeDict = dict() for node in nodesToColour: attributeDict[node] = colour.value networkx.set_node_attributes(nxGraph, attributeDict, COLOUR_NAME) def toGraphML(graph: Models.CommonGraphApi, file, inCacheFolder = False): """ Export `graph` to `file` in GraphML format. Each of the graph element's attributes is translated into a column. Parameters ---------- graph : Models.CommonGraphApi The graph to be exported. file : str Path and name of the exported file. See `inCacheFolder`. inCacheFolder : bool, optional If *True*, interpret `file` relative to the cache folder. See :attr:`FEV_KEGG.settings.cachePath`. If *False*, interpret `file` relative to the current working directory. Raises ------ NotImplementedError If `graph` is not of a NetworkX type. """ nxGraph = graph.underlyingRawGraph if isinstance(nxGraph, networkx.classes.graph.Graph): if inCacheFolder is True: file = os.path.join(settings.cachePath, file) dirName = os.path.dirname(file) if not os.path.isdir(dirName) and dirName != '': os.makedirs(os.path.dirname(file)) networkx.write_graphml(nxGraph, file + '.graphml', prettyprint=False) else: raise NotImplementedError() def toGML(graph: Models.CommonGraphApi, file, inCacheFolder = False): """ Export `graph` to `file` in GML format. Each of the graph element's attributes is translated into a column. Parameters ---------- graph : Models.CommonGraphApi The graph to be exported. file : str Path and name of the exported file. See `inCacheFolder`. inCacheFolder : bool, optional If *True*, interpret `file` relative to the cache folder. See :attr:`FEV_KEGG.settings.cachePath`. If *False*, interpret `file` relative to the current working directory. Raises ------ NotImplementedError If `graph` is not of a NetworkX type. """ nxGraph = graph.underlyingRawGraph if isinstance(nxGraph, networkx.classes.graph.Graph): if inCacheFolder is True: file = os.path.join(settings.cachePath, file) dirName = os.path.dirname(file) if not os.path.isdir(dirName) and dirName != '': os.makedirs(os.path.dirname(file)) networkx.write_gml(nxGraph, file + '.gml', lambda x: x.__str__()) else: raise NotImplementedError() def forCytoscape(graph: Models.CommonGraphApi, file, inCacheFolder = False, addDescriptions = True, totalNumberOfOrganisms: int = None): """ Export `graph` to `file` in GraphML format, including some tweaks for Cytoscape. Parameters ---------- graph : Models.CommonGraphApi The graph to be exported. file : str Path and name of the exported file. See `inCacheFolder`. inCacheFolder : bool, optional If *True*, interpret `file` relative to the cache folder. See :attr:`FEV_KEGG.settings.cachePath`. If *False*, interpret `file` relative to the current working directory. addDescriptions : bool, optional If *True*, downloads additional descriptions for substance totalNumberOfOrganisms : int, optional Total number of organisms which were involved in creating the `graph`. This is used to calculate the percentage of counts. 100% == `totalNumberOfOrganisms`. If *None*, no majority attribute is added. Only relevant if `graph` has counts, which it usually does not. See :func:`addMajorityAttribute` for more info. Raises ------ NotImplementedError If `graph` is not of a NetworkX type. Warnings -------- Adding extra descriptions, when `addDescriptions` == *True* (default!) is a lengthy process and can take some minutes. """ # fetch extra descriptions, so they can be saved in attributes if addDescriptions is True: graph.addSubstanceDescriptions() if isinstance(graph, SubstanceEcGraph): graph.addEcDescriptions() # add certain attributes to the graph, so they can be stored in the resulting XML addLabelAttribute(graph.underlyingRawGraph) addIdAttribute(graph.underlyingRawGraph) addDescriptionAttribute(graph.underlyingRawGraph) addUrlAttribute(graph.underlyingRawGraph) if addDescriptions is True and isinstance(graph, SubstanceEcGraph): addReactionAttribute(graph.underlyingRawGraph) if totalNumberOfOrganisms is not None: addMajorityAttribute(graph, totalNumberOfOrganisms) toGraphML(graph, file, inCacheFolder=inCacheFolder)
PypiClean
/FITS_tools-0.2.tar.gz/FITS_tools-0.2/astropy_helpers/astropy_helpers/utils.py
from __future__ import absolute_import, unicode_literals import contextlib import functools import imp import inspect import os import sys import glob import textwrap import types import warnings try: from importlib import machinery as import_machinery # Python 3.2 does not have SourceLoader if not hasattr(import_machinery, 'SourceLoader'): import_machinery = None except ImportError: import_machinery = None # Python 3.3's importlib caches filesystem reads for faster imports in the # general case. But sometimes it's necessary to manually invalidate those # caches so that the import system can pick up new generated files. See # https://github.com/astropy/astropy/issues/820 if sys.version_info[:2] >= (3, 3): from importlib import invalidate_caches else: def invalidate_caches(): return None # Python 2/3 compatibility if sys.version_info[0] < 3: string_types = (str, unicode) # noqa else: string_types = (str,) # Note: The following Warning subclasses are simply copies of the Warnings in # Astropy of the same names. class AstropyWarning(Warning): """ The base warning class from which all Astropy warnings should inherit. Any warning inheriting from this class is handled by the Astropy logger. """ class AstropyDeprecationWarning(AstropyWarning): """ A warning class to indicate a deprecated feature. """ class AstropyPendingDeprecationWarning(PendingDeprecationWarning, AstropyWarning): """ A warning class to indicate a soon-to-be deprecated feature. """ def _get_platlib_dir(cmd): """ Given a build command, return the name of the appropriate platform-specific build subdirectory directory (e.g. build/lib.linux-x86_64-2.7) """ plat_specifier = '.{0}-{1}'.format(cmd.plat_name, sys.version[0:3]) return os.path.join(cmd.build_base, 'lib' + plat_specifier) def get_numpy_include_path(): """ Gets the path to the numpy headers. """ # We need to go through this nonsense in case setuptools # downloaded and installed Numpy for us as part of the build or # install, since Numpy may still think it's in "setup mode", when # in fact we're ready to use it to build astropy now. if sys.version_info[0] >= 3: import builtins if hasattr(builtins, '__NUMPY_SETUP__'): del builtins.__NUMPY_SETUP__ import imp import numpy imp.reload(numpy) else: import __builtin__ if hasattr(__builtin__, '__NUMPY_SETUP__'): del __builtin__.__NUMPY_SETUP__ import numpy reload(numpy) try: numpy_include = numpy.get_include() except AttributeError: numpy_include = numpy.get_numpy_include() return numpy_include class _DummyFile(object): """A noop writeable object.""" errors = '' # Required for Python 3.x def write(self, s): pass def flush(self): pass @contextlib.contextmanager def silence(): """A context manager that silences sys.stdout and sys.stderr.""" old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = _DummyFile() sys.stderr = _DummyFile() exception_occurred = False try: yield except: exception_occurred = True # Go ahead and clean up so that exception handling can work normally sys.stdout = old_stdout sys.stderr = old_stderr raise if not exception_occurred: sys.stdout = old_stdout sys.stderr = old_stderr if sys.platform == 'win32': import ctypes def _has_hidden_attribute(filepath): """ Returns True if the given filepath has the hidden attribute on MS-Windows. Based on a post here: http://stackoverflow.com/questions/284115/cross-platform-hidden-file-detection """ if isinstance(filepath, bytes): filepath = filepath.decode(sys.getfilesystemencoding()) try: attrs = ctypes.windll.kernel32.GetFileAttributesW(filepath) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result else: def _has_hidden_attribute(filepath): return False def is_path_hidden(filepath): """ Determines if a given file or directory is hidden. Parameters ---------- filepath : str The path to a file or directory Returns ------- hidden : bool Returns `True` if the file is hidden """ name = os.path.basename(os.path.abspath(filepath)) if isinstance(name, bytes): is_dotted = name.startswith(b'.') else: is_dotted = name.startswith('.') return is_dotted or _has_hidden_attribute(filepath) def walk_skip_hidden(top, onerror=None, followlinks=False): """ A wrapper for `os.walk` that skips hidden files and directories. This function does not have the parameter `topdown` from `os.walk`: the directories must always be recursed top-down when using this function. See also -------- os.walk : For a description of the parameters """ for root, dirs, files in os.walk( top, topdown=True, onerror=onerror, followlinks=followlinks): # These lists must be updated in-place so os.walk will skip # hidden directories dirs[:] = [d for d in dirs if not is_path_hidden(d)] files[:] = [f for f in files if not is_path_hidden(f)] yield root, dirs, files def write_if_different(filename, data): """Write `data` to `filename`, if the content of the file is different. Parameters ---------- filename : str The file name to be written to. data : bytes The data to be written to `filename`. """ assert isinstance(data, bytes) if os.path.exists(filename): with open(filename, 'rb') as fd: original_data = fd.read() else: original_data = None if original_data != data: with open(filename, 'wb') as fd: fd.write(data) def import_file(filename, name=None): """ Imports a module from a single file as if it doesn't belong to a particular package. The returned module will have the optional ``name`` if given, or else a name generated from the filename. """ # Specifying a traditional dot-separated fully qualified name here # results in a number of "Parent module 'astropy' not found while # handling absolute import" warnings. Using the same name, the # namespaces of the modules get merged together. So, this # generates an underscore-separated name which is more likely to # be unique, and it doesn't really matter because the name isn't # used directly here anyway. mode = 'U' if sys.version_info[0] < 3 else 'r' if name is None: basename = os.path.splitext(filename)[0] name = '_'.join(os.path.relpath(basename).split(os.sep)[1:]) if import_machinery: loader = import_machinery.SourceFileLoader(name, filename) mod = loader.load_module() else: with open(filename, mode) as fd: mod = imp.load_module(name, fd, filename, ('.py', mode, 1)) return mod def resolve_name(name): """Resolve a name like ``module.object`` to an object and return it. Raise `ImportError` if the module or name is not found. """ parts = name.split('.') cursor = len(parts) - 1 module_name = parts[:cursor] attr_name = parts[-1] while cursor > 0: try: ret = __import__('.'.join(module_name), fromlist=[attr_name]) break except ImportError: if cursor == 0: raise cursor -= 1 module_name = parts[:cursor] attr_name = parts[cursor] ret = '' for part in parts[cursor:]: try: ret = getattr(ret, part) except AttributeError: raise ImportError(name) return ret if sys.version_info[0] >= 3: def iteritems(dictionary): return dictionary.items() else: def iteritems(dictionary): return dictionary.iteritems() def extends_doc(extended_func): """ A function decorator for use when wrapping an existing function but adding additional functionality. This copies the docstring from the original function, and appends to it (along with a newline) the docstring of the wrapper function. Example ------- >>> def foo(): ... '''Hello.''' ... >>> @extends_doc(foo) ... def bar(): ... '''Goodbye.''' ... >>> print(bar.__doc__) Hello. Goodbye. """ def decorator(func): if not (extended_func.__doc__ is None or func.__doc__ is None): func.__doc__ = '\n\n'.join([extended_func.__doc__.rstrip('\n'), func.__doc__.lstrip('\n')]) return func return decorator # Duplicated from astropy.utils.decorators.deprecated # When fixing issues in this function fix them in astropy first, then # port the fixes over to astropy-helpers def deprecated(since, message='', name='', alternative='', pending=False, obj_type=None): """ Used to mark a function or class as deprecated. To mark an attribute as deprecated, use `deprecated_attribute`. Parameters ------------ since : str The release at which this API became deprecated. This is required. message : str, optional Override the default deprecation message. The format specifier ``func`` may be used for the name of the function, and ``alternative`` may be used in the deprecation message to insert the name of an alternative to the deprecated function. ``obj_type`` may be used to insert a friendly name for the type of object being deprecated. name : str, optional The name of the deprecated function or class; if not provided the name is automatically determined from the passed in function or class, though this is useful in the case of renamed functions, where the new function is just assigned to the name of the deprecated function. For example:: def new_function(): ... oldFunction = new_function alternative : str, optional An alternative function or class name that the user may use in place of the deprecated object. The deprecation warning will tell the user about this alternative if provided. pending : bool, optional If True, uses a AstropyPendingDeprecationWarning instead of a AstropyDeprecationWarning. obj_type : str, optional The type of this object, if the automatically determined one needs to be overridden. """ method_types = (classmethod, staticmethod, types.MethodType) def deprecate_doc(old_doc, message): """ Returns a given docstring with a deprecation message prepended to it. """ if not old_doc: old_doc = '' old_doc = textwrap.dedent(old_doc).strip('\n') new_doc = (('\n.. deprecated:: %(since)s' '\n %(message)s\n\n' % {'since': since, 'message': message.strip()}) + old_doc) if not old_doc: # This is to prevent a spurious 'unexpected unindent' warning from # docutils when the original docstring was blank. new_doc += r'\ ' return new_doc def get_function(func): """ Given a function or classmethod (or other function wrapper type), get the function object. """ if isinstance(func, method_types): func = func.__func__ return func def deprecate_function(func, message): """ Returns a wrapped function that displays an ``AstropyDeprecationWarning`` when it is called. """ if isinstance(func, method_types): func_wrapper = type(func) else: func_wrapper = lambda f: f func = get_function(func) def deprecated_func(*args, **kwargs): if pending: category = AstropyPendingDeprecationWarning else: category = AstropyDeprecationWarning warnings.warn(message, category, stacklevel=2) return func(*args, **kwargs) # If this is an extension function, we can't call # functools.wraps on it, but we normally don't care. # This crazy way to get the type of a wrapper descriptor is # straight out of the Python 3.3 inspect module docs. if type(func) != type(str.__dict__['__add__']): deprecated_func = functools.wraps(func)(deprecated_func) deprecated_func.__doc__ = deprecate_doc( deprecated_func.__doc__, message) return func_wrapper(deprecated_func) def deprecate_class(cls, message): """ Returns a wrapper class with the docstrings updated and an __init__ function that will raise an ``AstropyDeprectationWarning`` warning when called. """ # Creates a new class with the same name and bases as the # original class, but updates the dictionary with a new # docstring and a wrapped __init__ method. __module__ needs # to be manually copied over, since otherwise it will be set # to *this* module (astropy.utils.misc). # This approach seems to make Sphinx happy (the new class # looks enough like the original class), and works with # extension classes (which functools.wraps does not, since # it tries to modify the original class). # We need to add a custom pickler or you'll get # Can't pickle <class ..>: it's not found as ... # errors. Picklability is required for any class that is # documented by Sphinx. members = cls.__dict__.copy() members.update({ '__doc__': deprecate_doc(cls.__doc__, message), '__init__': deprecate_function(get_function(cls.__init__), message), }) return type(cls.__name__, cls.__bases__, members) def deprecate(obj, message=message, name=name, alternative=alternative, pending=pending): if obj_type is None: if isinstance(obj, type): obj_type_name = 'class' elif inspect.isfunction(obj): obj_type_name = 'function' elif inspect.ismethod(obj) or isinstance(obj, method_types): obj_type_name = 'method' else: obj_type_name = 'object' else: obj_type_name = obj_type if not name: name = get_function(obj).__name__ altmessage = '' if not message or type(message) == type(deprecate): if pending: message = ('The %(func)s %(obj_type)s will be deprecated in a ' 'future version.') else: message = ('The %(func)s %(obj_type)s is deprecated and may ' 'be removed in a future version.') if alternative: altmessage = '\n Use %s instead.' % alternative message = ((message % { 'func': name, 'name': name, 'alternative': alternative, 'obj_type': obj_type_name}) + altmessage) if isinstance(obj, type): return deprecate_class(obj, message) else: return deprecate_function(obj, message) if type(message) == type(deprecate): return deprecate(message) return deprecate def deprecated_attribute(name, since, message=None, alternative=None, pending=False): """ Used to mark a public attribute as deprecated. This creates a property that will warn when the given attribute name is accessed. To prevent the warning (i.e. for internal code), use the private name for the attribute by prepending an underscore (i.e. ``self._name``). Parameters ---------- name : str The name of the deprecated attribute. since : str The release at which this API became deprecated. This is required. message : str, optional Override the default deprecation message. The format specifier ``name`` may be used for the name of the attribute, and ``alternative`` may be used in the deprecation message to insert the name of an alternative to the deprecated function. alternative : str, optional An alternative attribute that the user may use in place of the deprecated attribute. The deprecation warning will tell the user about this alternative if provided. pending : bool, optional If True, uses a AstropyPendingDeprecationWarning instead of a AstropyDeprecationWarning. Examples -------- :: class MyClass: # Mark the old_name as deprecated old_name = misc.deprecated_attribute('old_name', '0.1') def method(self): self._old_name = 42 """ private_name = '_' + name @deprecated(since, name=name, obj_type='attribute') def get(self): return getattr(self, private_name) @deprecated(since, name=name, obj_type='attribute') def set(self, val): setattr(self, private_name, val) @deprecated(since, name=name, obj_type='attribute') def delete(self): delattr(self, private_name) return property(get, set, delete) def minversion(module, version, inclusive=True, version_path='__version__'): """ Returns `True` if the specified Python module satisfies a minimum version requirement, and `False` if not. By default this uses `pkg_resources.parse_version` to do the version comparison if available. Otherwise it falls back on `distutils.version.LooseVersion`. Parameters ---------- module : module or `str` An imported module of which to check the version, or the name of that module (in which case an import of that module is attempted-- if this fails `False` is returned). version : `str` The version as a string that this module must have at a minimum (e.g. ``'0.12'``). inclusive : `bool` The specified version meets the requirement inclusively (i.e. ``>=``) as opposed to strictly greater than (default: `True`). version_path : `str` A dotted attribute path to follow in the module for the version. Defaults to just ``'__version__'``, which should work for most Python modules. Examples -------- >>> import astropy >>> minversion(astropy, '0.4.4') True """ if isinstance(module, types.ModuleType): module_name = module.__name__ elif isinstance(module, string_types): module_name = module try: module = resolve_name(module_name) except ImportError: return False else: raise ValueError('module argument must be an actual imported ' 'module, or the import name of the module; ' 'got {0!r}'.format(module)) if '.' not in version_path: have_version = getattr(module, version_path) else: have_version = resolve_name('.'.join([module.__name__, version_path])) try: from pkg_resources import parse_version except ImportError: from distutils.version import LooseVersion as parse_version if inclusive: return parse_version(have_version) >= parse_version(version) else: return parse_version(have_version) > parse_version(version) # Copy of the classproperty decorator from astropy.utils.decorators class classproperty(property): """ Similar to `property`, but allows class-level properties. That is, a property whose getter is like a `classmethod`. The wrapped method may explicitly use the `classmethod` decorator (which must become before this decorator), or the `classmethod` may be omitted (it is implicit through use of this decorator). .. note:: classproperty only works for *read-only* properties. It does not currently allow writeable/deleteable properties, due to subtleties of how Python descriptors work. In order to implement such properties on a class a metaclass for that class must be implemented. Parameters ---------- fget : callable The function that computes the value of this property (in particular, the function when this is used as a decorator) a la `property`. doc : str, optional The docstring for the property--by default inherited from the getter function. lazy : bool, optional If True, caches the value returned by the first call to the getter function, so that it is only called once (used for lazy evaluation of an attribute). This is analogous to `lazyproperty`. The ``lazy`` argument can also be used when `classproperty` is used as a decorator (see the third example below). When used in the decorator syntax this *must* be passed in as a keyword argument. Examples -------- :: >>> class Foo(object): ... _bar_internal = 1 ... @classproperty ... def bar(cls): ... return cls._bar_internal + 1 ... >>> Foo.bar 2 >>> foo_instance = Foo() >>> foo_instance.bar 2 >>> foo_instance._bar_internal = 2 >>> foo_instance.bar # Ignores instance attributes 2 As previously noted, a `classproperty` is limited to implementing read-only attributes:: >>> class Foo(object): ... _bar_internal = 1 ... @classproperty ... def bar(cls): ... return cls._bar_internal ... @bar.setter ... def bar(cls, value): ... cls._bar_internal = value ... Traceback (most recent call last): ... NotImplementedError: classproperty can only be read-only; use a metaclass to implement modifiable class-level properties When the ``lazy`` option is used, the getter is only called once:: >>> class Foo(object): ... @classproperty(lazy=True) ... def bar(cls): ... print("Performing complicated calculation") ... return 1 ... >>> Foo.bar Performing complicated calculation 1 >>> Foo.bar 1 If a subclass inherits a lazy `classproperty` the property is still re-evaluated for the subclass:: >>> class FooSub(Foo): ... pass ... >>> FooSub.bar Performing complicated calculation 1 >>> FooSub.bar 1 """ def __new__(cls, fget=None, doc=None, lazy=False): if fget is None: # Being used as a decorator--return a wrapper that implements # decorator syntax def wrapper(func): return cls(func, lazy=lazy) return wrapper return super(classproperty, cls).__new__(cls) def __init__(self, fget, doc=None, lazy=False): self._lazy = lazy if lazy: self._cache = {} fget = self._wrap_fget(fget) super(classproperty, self).__init__(fget=fget, doc=doc) # There is a buglet in Python where self.__doc__ doesn't # get set properly on instances of property subclasses if # the doc argument was used rather than taking the docstring # from fget if doc is not None: self.__doc__ = doc def __get__(self, obj, objtype=None): if self._lazy and objtype in self._cache: return self._cache[objtype] if objtype is not None: # The base property.__get__ will just return self here; # instead we pass objtype through to the original wrapped # function (which takes the class as its sole argument) val = self.fget.__wrapped__(objtype) else: val = super(classproperty, self).__get__(obj, objtype=objtype) if self._lazy: if objtype is None: objtype = obj.__class__ self._cache[objtype] = val return val def getter(self, fget): return super(classproperty, self).getter(self._wrap_fget(fget)) def setter(self, fset): raise NotImplementedError( "classproperty can only be read-only; use a metaclass to " "implement modifiable class-level properties") def deleter(self, fdel): raise NotImplementedError( "classproperty can only be read-only; use a metaclass to " "implement modifiable class-level properties") @staticmethod def _wrap_fget(orig_fget): if isinstance(orig_fget, classmethod): orig_fget = orig_fget.__func__ # Using stock functools.wraps instead of the fancier version # found later in this module, which is overkill for this purpose @functools.wraps(orig_fget) def fget(obj): return orig_fget(obj.__class__) # Set the __wrapped__ attribute manually for support on Python 2 fget.__wrapped__ = orig_fget return fget def find_data_files(package, pattern): """ Include files matching ``pattern`` inside ``package``. Parameters ---------- package : str The package inside which to look for data files pattern : str Pattern (glob-style) to match for the data files (e.g. ``*.dat``). This supports the Python 3.5 ``**``recursive syntax. For example, ``**/*.fits`` matches all files ending with ``.fits`` recursively. Only one instance of ``**`` can be included in the pattern. """ if sys.version_info[:2] >= (3, 5): return glob.glob(os.path.join(package, pattern), recursive=True) else: if '**' in pattern: start, end = pattern.split('**') if end.startswith(('/', os.sep)): end = end[1:] matches = glob.glob(os.path.join(package, start, end)) for root, dirs, files in os.walk(os.path.join(package, start)): for dirname in dirs: matches += glob.glob(os.path.join(root, dirname, end)) return matches else: return glob.glob(os.path.join(package, pattern))
PypiClean
/GDAL-3.7.1.1.tar.gz/GDAL-3.7.1.1/gdal-utils/osgeo_utils/gdal_merge.py
import math import sys import time from osgeo import gdal from osgeo_utils.auxiliary.util import GetOutputDriverFor progress = gdal.TermProgress_nocb __version__ = "$id$"[5:-1] # ============================================================================= def raster_copy( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n, t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n, nodata=None, verbose=0, ): if verbose != 0: print( "Copy %d,%d,%d,%d to %d,%d,%d,%d." % (s_xoff, s_yoff, s_xsize, s_ysize, t_xoff, t_yoff, t_xsize, t_ysize) ) if nodata is not None: return raster_copy_with_nodata( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n, t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n, nodata, ) s_band = s_fh.GetRasterBand(s_band_n) m_band = None # Works only in binary mode and doesn't take into account # intermediate transparency values for compositing. if s_band.GetMaskFlags() != gdal.GMF_ALL_VALID: m_band = s_band.GetMaskBand() elif s_band.GetColorInterpretation() == gdal.GCI_AlphaBand: m_band = s_band if m_band is not None: return raster_copy_with_mask( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n, t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n, m_band, ) s_band = s_fh.GetRasterBand(s_band_n) t_band = t_fh.GetRasterBand(t_band_n) data = s_band.ReadRaster( s_xoff, s_yoff, s_xsize, s_ysize, t_xsize, t_ysize, t_band.DataType ) t_band.WriteRaster( t_xoff, t_yoff, t_xsize, t_ysize, data, t_xsize, t_ysize, t_band.DataType ) return 0 # ============================================================================= def raster_copy_with_nodata( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n, t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n, nodata, ): import numpy as np s_band = s_fh.GetRasterBand(s_band_n) t_band = t_fh.GetRasterBand(t_band_n) data_src = s_band.ReadAsArray(s_xoff, s_yoff, s_xsize, s_ysize, t_xsize, t_ysize) data_dst = t_band.ReadAsArray(t_xoff, t_yoff, t_xsize, t_ysize) if not np.isnan(nodata): nodata_test = np.equal(data_src, nodata) else: nodata_test = np.isnan(data_src) to_write = np.choose(nodata_test, (data_src, data_dst)) t_band.WriteArray(to_write, t_xoff, t_yoff) return 0 # ============================================================================= def raster_copy_with_mask( s_fh, s_xoff, s_yoff, s_xsize, s_ysize, s_band_n, t_fh, t_xoff, t_yoff, t_xsize, t_ysize, t_band_n, m_band, ): import numpy as np s_band = s_fh.GetRasterBand(s_band_n) t_band = t_fh.GetRasterBand(t_band_n) data_src = s_band.ReadAsArray(s_xoff, s_yoff, s_xsize, s_ysize, t_xsize, t_ysize) data_mask = m_band.ReadAsArray(s_xoff, s_yoff, s_xsize, s_ysize, t_xsize, t_ysize) data_dst = t_band.ReadAsArray(t_xoff, t_yoff, t_xsize, t_ysize) mask_test = np.equal(data_mask, 0) to_write = np.choose(mask_test, (data_src, data_dst)) t_band.WriteArray(to_write, t_xoff, t_yoff) return 0 # ============================================================================= def names_to_fileinfos(names): """ Translate a list of GDAL filenames, into file_info objects. names -- list of valid GDAL dataset names. Returns a list of file_info objects. There may be less file_info objects than names if some of the names could not be opened as GDAL files. """ file_infos = [] for name in names: fi = file_info() if fi.init_from_name(name) == 1: file_infos.append(fi) return file_infos # ***************************************************************************** class file_info(object): """A class holding information about a GDAL file.""" def __init__(self): self.band_type = None self.bands = None self.ct = None self.filename = None self.geotransform = None self.lrx = None self.lry = None self.projection = None self.ulx = None self.uly = None self.xsize = None self.ysize = None def init_from_name(self, filename): """ Initialize file_info from filename filename -- Name of file to read. Returns 1 on success or 0 if the file can't be opened. """ fh = gdal.Open(filename) if fh is None: return 0 self.filename = filename self.bands = fh.RasterCount self.xsize = fh.RasterXSize self.ysize = fh.RasterYSize self.band_type = fh.GetRasterBand(1).DataType self.projection = fh.GetProjection() self.geotransform = fh.GetGeoTransform() self.ulx = self.geotransform[0] self.uly = self.geotransform[3] self.lrx = self.ulx + self.geotransform[1] * self.xsize self.lry = self.uly + self.geotransform[5] * self.ysize ct = fh.GetRasterBand(1).GetRasterColorTable() if ct is not None: self.ct = ct.Clone() else: self.ct = None return 1 def report(self): print("Filename: " + self.filename) print("File Size: %dx%dx%d" % (self.xsize, self.ysize, self.bands)) print("Pixel Size: %f x %f" % (self.geotransform[1], self.geotransform[5])) print("UL:(%f,%f) LR:(%f,%f)" % (self.ulx, self.uly, self.lrx, self.lry)) def copy_into(self, t_fh, s_band=1, t_band=1, nodata_arg=None, verbose=0): """ Copy this files image into target file. This method will compute the overlap area of the file_info objects file, and the target gdal.Dataset object, and copy the image data for the common window area. It is assumed that the files are in a compatible projection ... no checking or warping is done. However, if the destination file is a different resolution, or different image pixel type, the appropriate resampling and conversions will be done (using normal GDAL promotion/demotion rules). t_fh -- gdal.Dataset object for the file into which some or all of this file may be copied. Returns 1 on success (or if nothing needs to be copied), and zero one failure. """ t_geotransform = t_fh.GetGeoTransform() t_ulx = t_geotransform[0] t_uly = t_geotransform[3] t_lrx = t_geotransform[0] + t_fh.RasterXSize * t_geotransform[1] t_lry = t_geotransform[3] + t_fh.RasterYSize * t_geotransform[5] # figure out intersection region tgw_ulx = max(t_ulx, self.ulx) tgw_lrx = min(t_lrx, self.lrx) if t_geotransform[5] < 0: tgw_uly = min(t_uly, self.uly) tgw_lry = max(t_lry, self.lry) else: tgw_uly = max(t_uly, self.uly) tgw_lry = min(t_lry, self.lry) # do they even intersect? if tgw_ulx >= tgw_lrx: return 1 if t_geotransform[5] < 0 and tgw_uly <= tgw_lry: return 1 if t_geotransform[5] > 0 and tgw_uly >= tgw_lry: return 1 # compute target window in pixel coordinates. tw_xoff = int((tgw_ulx - t_geotransform[0]) / t_geotransform[1] + 0.1) tw_yoff = int((tgw_uly - t_geotransform[3]) / t_geotransform[5] + 0.1) tw_xsize = ( int((tgw_lrx - t_geotransform[0]) / t_geotransform[1] + 0.5) - tw_xoff ) tw_ysize = ( int((tgw_lry - t_geotransform[3]) / t_geotransform[5] + 0.5) - tw_yoff ) if tw_xsize < 1 or tw_ysize < 1: return 1 # Compute source window in pixel coordinates. sw_xoff = int((tgw_ulx - self.geotransform[0]) / self.geotransform[1] + 0.1) sw_yoff = int((tgw_uly - self.geotransform[3]) / self.geotransform[5] + 0.1) sw_xsize = ( int((tgw_lrx - self.geotransform[0]) / self.geotransform[1] + 0.5) - sw_xoff ) sw_ysize = ( int((tgw_lry - self.geotransform[3]) / self.geotransform[5] + 0.5) - sw_yoff ) if sw_xsize < 1 or sw_ysize < 1: return 1 # Open the source file, and copy the selected region. s_fh = gdal.Open(self.filename) return raster_copy( s_fh, sw_xoff, sw_yoff, sw_xsize, sw_ysize, s_band, t_fh, tw_xoff, tw_yoff, tw_xsize, tw_ysize, t_band, nodata_arg, verbose, ) # ============================================================================= def Usage(): print("Usage: gdal_merge.py [-o out_filename] [-of out_format] [-co NAME=VALUE]*") print( " [-ps pixelsize_x pixelsize_y] [-tap] [-separate] [-q] [-v] [-pct]" ) print(' [-ul_lr ulx uly lrx lry] [-init "value [value...]"]') print(" [-n nodata_value] [-a_nodata output_nodata_value]") print(" [-ot datatype] [-createonly] input_files") print(" [--help-general]") print("") return 2 def gdal_merge(argv=None): verbose = 0 quiet = 0 names = [] driver_name = None out_file = "out.tif" ulx = None psize_x = None separate = 0 copy_pct = 0 nodata = None a_nodata = None create_options = [] pre_init = [] band_type = None createonly = 0 bTargetAlignedPixels = False start_time = time.time() if argv is None: argv = argv argv = gdal.GeneralCmdLineProcessor(argv) if argv is None: return 0 # Parse command line arguments. i = 1 while i < len(argv): arg = argv[i] if arg == "-o": i = i + 1 out_file = argv[i] elif arg == "-v": verbose = 1 elif arg == "-q" or arg == "-quiet": quiet = 1 elif arg == "-createonly": createonly = 1 elif arg == "-separate": separate = 1 elif arg == "-seperate": separate = 1 elif arg == "-pct": copy_pct = 1 elif arg == "-ot": i = i + 1 band_type = gdal.GetDataTypeByName(argv[i]) if band_type == gdal.GDT_Unknown: print("Unknown GDAL data type: %s" % argv[i]) return 1 elif arg == "-init": i = i + 1 str_pre_init = argv[i].split() for x in str_pre_init: pre_init.append(float(x)) elif arg == "-n": i = i + 1 nodata = float(argv[i]) elif arg == "-a_nodata": i = i + 1 a_nodata = float(argv[i]) elif arg == "-f" or arg == "-of": i = i + 1 driver_name = argv[i] elif arg == "-co": i = i + 1 create_options.append(argv[i]) elif arg == "-ps": psize_x = float(argv[i + 1]) psize_y = -1 * abs(float(argv[i + 2])) i = i + 2 elif arg == "-tap": bTargetAlignedPixels = True elif arg == "-ul_lr": ulx = float(argv[i + 1]) uly = float(argv[i + 2]) lrx = float(argv[i + 3]) lry = float(argv[i + 4]) i = i + 4 elif arg[:1] == "-": print("Unrecognized command option: %s" % arg) return Usage() else: names.append(arg) i = i + 1 if not names: print("No input files selected.") return Usage() if driver_name is None: driver_name = GetOutputDriverFor(out_file) driver = gdal.GetDriverByName(driver_name) if driver is None: print("Format driver %s not found, pick a supported driver." % driver_name) return 1 DriverMD = driver.GetMetadata() if "DCAP_CREATE" not in DriverMD: print( "Format driver %s does not support creation and piecewise writing.\nPlease select a format that does, such as GTiff (the default) or HFA (Erdas Imagine)." % driver_name ) return 1 # Collect information on all the source files. file_infos = names_to_fileinfos(names) if ulx is None: ulx = file_infos[0].ulx uly = file_infos[0].uly lrx = file_infos[0].lrx lry = file_infos[0].lry for fi in file_infos: ulx = min(ulx, fi.ulx) uly = max(uly, fi.uly) lrx = max(lrx, fi.lrx) lry = min(lry, fi.lry) if psize_x is None: psize_x = file_infos[0].geotransform[1] psize_y = file_infos[0].geotransform[5] if band_type is None: band_type = file_infos[0].band_type # Try opening as an existing file. with gdal.quiet_errors(), gdal.ExceptionMgr(useExceptions=False): t_fh = gdal.Open(out_file, gdal.GA_Update) # Create output file if it does not already exist. if t_fh is None: if bTargetAlignedPixels: ulx = math.floor(ulx / psize_x) * psize_x lrx = math.ceil(lrx / psize_x) * psize_x lry = math.floor(lry / -psize_y) * -psize_y uly = math.ceil(uly / -psize_y) * -psize_y geotransform = [ulx, psize_x, 0, uly, 0, psize_y] xsize = int((lrx - ulx) / geotransform[1] + 0.5) ysize = int((lry - uly) / geotransform[5] + 0.5) if separate != 0: bands = 0 for fi in file_infos: bands = bands + fi.bands else: bands = file_infos[0].bands t_fh = driver.Create(out_file, xsize, ysize, bands, band_type, create_options) if t_fh is None: print("Creation failed, terminating gdal_merge.") return 1 t_fh.SetGeoTransform(geotransform) t_fh.SetProjection(file_infos[0].projection) if copy_pct: t_fh.GetRasterBand(1).SetRasterColorTable(file_infos[0].ct) else: if separate != 0: bands = 0 for fi in file_infos: bands = bands + fi.bands if t_fh.RasterCount < bands: print( "Existing output file has less bands than the input files. You should delete it before. Terminating gdal_merge." ) return 1 else: bands = min(file_infos[0].bands, t_fh.RasterCount) # Do we need to set nodata value ? if a_nodata is not None: for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).SetNoDataValue(a_nodata) # Do we need to pre-initialize the whole mosaic file to some value? if pre_init is not None: if t_fh.RasterCount <= len(pre_init): for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).Fill(pre_init[i]) elif len(pre_init) == 1: for i in range(t_fh.RasterCount): t_fh.GetRasterBand(i + 1).Fill(pre_init[0]) # Copy data from source files into output file. t_band = 1 if quiet == 0 and verbose == 0: progress(0.0) fi_processed = 0 for fi in file_infos: if createonly != 0: continue if verbose != 0: print("") print( "Processing file %5d of %5d, %6.3f%% completed in %d minutes." % ( fi_processed + 1, len(file_infos), fi_processed * 100.0 / len(file_infos), int(round((time.time() - start_time) / 60.0)), ) ) fi.report() if separate == 0: for band in range(1, bands + 1): fi.copy_into(t_fh, band, band, nodata, verbose) else: for band in range(1, fi.bands + 1): fi.copy_into(t_fh, band, t_band, nodata, verbose) t_band = t_band + 1 fi_processed = fi_processed + 1 if quiet == 0 and verbose == 0: progress(fi_processed / float(len(file_infos))) # Force file to be closed. t_fh = None def main(argv=sys.argv): return gdal_merge(argv) if __name__ == "__main__": sys.exit(main(sys.argv))
PypiClean
/Nuitka_winsvc-1.7.10-cp310-cp310-win_amd64.whl/nuitka/__past__.py
import pkgutil import sys from abc import ABCMeta # pylint: disable=invalid-name,self-assigning-variable if str is bytes: import __builtin__ as builtins # Python2 code, pylint: disable=import-error else: import builtins # Work around for CPython 3.x renaming "long" to "int". if str is bytes: long = long # Python2 code, pylint: disable=undefined-variable else: long = int # Work around for CPython 3.x renaming "unicode" to "str". if str is bytes: unicode = unicode # Python2 code, pylint: disable=undefined-variable else: unicode = str if str is bytes: def iterItems(d): return d.iteritems() else: def iterItems(d): return d.items() if str is not bytes: raw_input = input xrange = range basestring = str else: raw_input = raw_input xrange = xrange basestring = basestring if str is bytes: from urllib import ( # pylint: disable=I0021,import-error,no-name-in-module urlretrieve, ) else: from urllib.request import urlretrieve if str is bytes: from cStringIO import StringIO # Python2 code, pylint: disable=import-error else: from io import StringIO if str is bytes: BytesIO = StringIO else: from io import BytesIO try: from functools import total_ordering except ImportError: # Lame replacement for functools.total_ordering, which does not exist on # Python2.6, this requires "<" and "=" and adds all other operations. def total_ordering(cls): cls.__ne__ = lambda self, other: not self == other cls.__le__ = lambda self, other: self == other or self < other cls.__gt__ = lambda self, other: self != other and not self < other cls.__ge__ = lambda self, other: self == other and not self < other return cls if str is bytes: # Python2 only code, pylint: disable=deprecated-class,no-name-in-module from collections import Iterable, MutableSet else: from collections.abc import Iterable, MutableSet if str is bytes: intern = intern # Python2 code, pylint: disable=undefined-variable else: intern = sys.intern if str is bytes: to_byte = chr from_byte = ord else: def to_byte(value): assert type(value) is int and 0 <= value < 256 return bytes((value,)) def from_byte(value): assert type(value) is bytes and len(value) == 1, value return value[0] try: from typing import GenericAlias except ImportError: GenericAlias = None try: from types import UnionType except ImportError: UnionType = None def getMetaClassBase(meta_class_prefix): """For Python2/3 compatible source, we create a base class that has the metaclass used and doesn't require making a choice. """ class MetaClass(ABCMeta): pass MetaClassBase = MetaClass("%sMetaClassBase" % meta_class_prefix, (object,), {}) return MetaClassBase if str is bytes: try: import subprocess32 as subprocess except ImportError: import subprocess else: import subprocess # Just to make this not Windows-specific. WindowsError = OSError # pylint: disable=I0021,redefined-builtin # Make it available for Python2 as well PermissionError = ( # pylint: disable=redefined-builtin PermissionError if str is not bytes else OSError ) if not hasattr(pkgutil, "ModuleInfo"): # Python3.5 or lower do not return namedtuple, but it's nicer to read code with it. from collections import namedtuple ModuleInfo = namedtuple("ModuleInfo", "module_finder name ispkg") def iter_modules(path=None, prefix=""): for item in pkgutil.iter_modules(path, prefix): yield ModuleInfo(*item) else: iter_modules = pkgutil.iter_modules try: ExceptionGroup = ExceptionGroup except NameError: ExceptionGroup = None try: BaseExceptionGroup = BaseExceptionGroup except NameError: BaseExceptionGroup = None # For PyLint to be happy. assert long assert unicode assert urlretrieve assert StringIO assert BytesIO assert type(xrange) is type, xrange assert total_ordering assert intern assert builtins assert Iterable assert MutableSet assert subprocess assert GenericAlias or intern assert UnionType or intern
PypiClean
/Flashflood-0.13.0.tar.gz/Flashflood-0.13.0/flashflood/static.py
import collections from tornado import process from chorus import molutil, wclogp from chorus.draw.svg import mol_to_svg from flashflood.lod import ListOfDict JOB_RESULT_SCHEMA = "https://mojaie.github.io/flashflood/_static/specs/job_result_v1.0.json" """ Option module availability """ try: from chorus import rdkit RDK_AVAILABLE = True except ImportError: RDK_AVAILABLE = False try: import cython NUMERIC_MODULE = "Cython" except ImportError: try: import numexpr NUMERIC_MODULE = "NumExpr" except ImportError: NUMERIC_MODULE = "Numpy" """ Server status """ PROCESSES = process.cpu_count() """ Field definition """ # TODO: move to server_config? INDEX_FIELD = {"key": "index", "name": "Index", "d3_format": "d"} COMPID_FIELD = {"key": "compound_id", "name": "Compound ID", "format": "compound_id"} NAME_FIELD = {"key": "name", "name": "Name", "format": "text"} MOLJSON_FIELD = {"key": "__moljson", "name": "Molecule JSON", "format": "json"} MOLPICKLE_FIELD = {"key": "__molpickle", "name": "Pickled molecule", "format": "pickle"} MOLOBJ_FIELD = {"key": "__molobj", "name": "Molecule object", "format": "pyobject"} # TODO: move to node.chem.descriptor? Descriptor = collections.namedtuple( "Descriptor", ("function", "name", "format_type", "format")) MOL_DESCS = collections.OrderedDict([ ("structure", Descriptor(mol_to_svg, "Structure", "format", "svg")), ("_mw", Descriptor(molutil.mw, "MW", "d3_format", ".2f")), ("_mw_wo_sw", Descriptor(molutil.mw_wo_sw, "MW w/o salt and water", "d3_format", ".2f")), ("_formula", Descriptor(molutil.formula, "Formula", "format", "text")), ("_logp", Descriptor(wclogp.wclogp, "WCLogP", "d3_format", ".1f")), ("_nonH", Descriptor(molutil.non_hydrogen_count, "Non-H atom count", "d3_format", "d")) ]) MOL_DESC_KEYS = list(MOL_DESCS.keys()) # OrderedDict.key is not picklable MOL_DESC_FIELDS = ListOfDict({ "key": key, "name": desc.name, desc.format_type: desc.format } for key, desc in MOL_DESCS.items())
PypiClean
/GxDoxybook-1.1.0.tar.gz/GxDoxybook-1.1.0/doxybook/node.py
import os import re import traceback from xml.etree import ElementTree from xml.etree.ElementTree import Element as Element from doxybook.constants import Kind, Visibility, OVERLOAD_OPERATORS from doxybook.cache import Cache from doxybook.xml_parser import XmlParser from doxybook.markdown import escape from doxybook.utils import split_safe from doxybook.property import Property class Node: _output_dir = '' def __init__(self, xml_file: str, xml: Element, cache: Cache, parser: XmlParser, \ parent: 'Node', refid: str = None, position: str = None , \ doc_type = 'all', rel_path = ''): self._children: ['Node'] = [] self._cache: Cache = cache self._parser: XmlParser = parser self._parent = parent self._position = position self.doc_type = doc_type self.rel_path = rel_path if xml_file == 'root': self._refid = 'root' self._kind = Kind.from_str('root') self._name = 'root' self._xml = None elif xml is None: print('Loading XML from: ' + xml_file) self._dirname = os.path.dirname(xml_file) self._position = self._dirname self._xml = ElementTree.parse(xml_file).getroot().find('compounddef') if self._xml is None: raise Exception('File ' + xml_file + ' has no <compounddef>') self._kind = Kind.from_str(self._xml.get('kind')) self._refid = self._xml.get('id') self._name = self._xml.find('compoundname').text self._cache.add_onname(self._name, self) self._cache.add(self._refid, self) self._static = False print('Parsing: ' + self._refid) self._check_for_children() title = self._xml.find('title') if title is not None: self._title = title.text else: self._title = self._name else: self._xml = xml if self._parent.kind == Kind.ENUM: self._kind = Kind.from_str('enumvalue') else: self._kind = Kind.from_str(self._xml.get('kind')) if refid is not None: self._refid = refid else: self._refid = self._xml.get('id') self._cache.add(self._refid, self) self._check_attrs() self._title = self._name self._cache.add_onname(self._name, self) if self._kind == Kind.ENUM: enumvalues = self._xml.findall('enumvalue') for enumvalue in enumvalues: if not enumvalue.get('id'): continue child = Node(None, enumvalue, self._cache, self._parser, self, position = self._position) self.add_child(child) self._details = Property.Details(self._xml, parser, self._kind) self._brief = Property.Brief(self._xml, parser, self._kind) self._includes = Property.Includes(self._xml, parser, self._kind) self._type = Property.Type(self._xml, parser, self._kind) self._location = Property.Location(self._xml, parser, self._kind) self._params = Property.Params(self._xml, parser, self._kind) self._templateparams = Property.TemplateParams(self._xml, parser, self._kind) self._specifiers = Property.Specifiers(self._xml, parser, self._kind) self._values = Property.Values(self._xml, parser, self._kind) self._initializer = Property.Initializer(self._xml, parser, self._kind) self._definition = Property.Definition(self._xml, parser, self._kind) self._programlisting = Property.Programlisting(self._xml, parser, self._kind) self._CodeBlock = Property.CodeBlock(self._xml, parser, self._kind) self._output_dir = '' if xml_file: self._output_dir = os.path.basename(os.path.dirname(xml_file)) elif self._parent: self._output_dir = self._parent._output_dir else: print('No found output dir') pass #def node_replace(rep, replace, node): def list_node(self, node, leval = 0): n = leval print('\t'*n, node._kind, node._name, 'now') if node.has_children: n += 1 for child in node._children: print('\t'*n, child._kind, child._name, 'children') if child.has_children: self.list_node(child, n) def add_child(self, child: 'Node'): self._children.append(child) def sort_children(self): self._children.sort(key=lambda x: x._name, reverse=False) def _check_for_children(self): for innergroup in self._xml.findall('innergroup'): refid = innergroup.get('refid') if self._kind == Kind.GROUP or self._kind == Kind.DIR or self._kind == Kind.FILE: try: child = self._cache.get(refid) self.add_child(child) continue except: pass child = Node(os.path.join(self._dirname, refid + '.xml'), None, self._cache, self._parser, self, \ doc_type = self.doc_type, rel_path = self.rel_path) child._visibility = Visibility.PUBLIC self.add_child(child) for innerclass in self._xml.findall('innerclass'): refid = innerclass.get('refid') prot = Visibility(innerclass.get('prot')) if prot == Visibility.PRIVATE: continue if self._kind == Kind.GROUP or self._kind == Kind.DIR or self._kind == Kind.FILE: try: child = self._cache.get(refid) self.add_child(child) continue except: pass try: child = Node(os.path.join(self._dirname, refid + '.xml'), None, self._cache, self._parser, self, doc_type = self.doc_type, rel_path = self.rel_path) except FileNotFoundError as e: child = Node(os.path.join(self._dirname, refid + '.xml'), Element('compounddef'), self._cache, self._parser, self, refid=refid, \ doc_type = self.doc_type, rel_path = self.rel_path) child._name = innerclass.text child._visibility = prot self.add_child(child) for innerfile in self._xml.findall('innerfile'): refid = innerfile.get('refid') if self._kind == Kind.DIR: try: child = self._cache.get(refid) self.add_child(child) continue except: pass child = Node(os.path.join(self._dirname, refid + '.xml'), None, self._cache, self._parser, self, \ doc_type = self.doc_type, rel_path = self.rel_path) child._visibility = Visibility.PUBLIC self.add_child(child) for innerdir in self._xml.findall('innerdir'): refid = innerdir.get('refid') if self._kind == Kind.DIR: try: child = self._cache.get(refid) self.add_child(child) continue except: pass child = Node(os.path.join(self._dirname, refid + '.xml'), None, self._cache, self._parser, self, \ doc_type = self.doc_type, rel_path = self.rel_path) child._visibility = Visibility.PUBLIC self.add_child(child) for innernamespace in self._xml.findall('innernamespace'): refid = innernamespace.get('refid') if self._kind == Kind.GROUP or self._kind == Kind.DIR or self._kind == Kind.FILE: try: child = self._cache.get(refid) self.add_child(child) continue except: pass child = Node(os.path.join(self._dirname, refid + '.xml'), None, self._cache, self._parser, self, \ doc_type = self.doc_type, rel_path = self.rel_path) child._visibility = Visibility.PUBLIC self.add_child(child) for sectiondef in self._xml.findall('sectiondef'): for memberdef in sectiondef.findall('memberdef'): kind = Kind.from_str(memberdef.get('kind')) if kind.is_language(): if self._kind == Kind.GROUP or self._kind == Kind.DIR or self._kind == Kind.FILE: refid = memberdef.get('id') try: child = self._cache.get(refid) self.add_child(child) continue except: pass child = Node(None, memberdef, self._cache, self._parser, self, position = self._position, \ doc_type = self.doc_type, rel_path = self.rel_path) #if child._kind == Kind.ENUM: # print('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa') # print(child.name) # print(child._position) # print(memberdef.get('enumvalue')) self.add_child(child) def _check_attrs(self): prot = self._xml.get('prot') self._visibility = Visibility(prot) if prot is not None else Visibility.PUBLIC static = self._xml.get('static') self._static = static == 'yes' explicit = self._xml.get('explicit') self._explicit = explicit == 'yes' mutable = self._xml.get('mutable') self._mutable = mutable == 'yes' inline = self._xml.get('inline') self._inline = inline == 'yes' const = self._xml.get('inline') self._const = const == 'yes' name = self._xml.find('name') if name is not None: self._name = name.text else: self._name = '' virt = self._xml.get('virt') if virt: self._virtual = virt == 'virtual' or virt == 'pure-virtual' self._pure = virt == 'pure-virtual' else: self._virtual = False self._pure = False def has(self, visibility: str, kinds: [str], static: bool) -> bool: return len(self.query(visibility, kinds, static)) > 0 def query(self, visibility: str, kinds: [str], static: bool) -> ['Node']: ret = [] visibility = Visibility(visibility) kinds = list(map(lambda kind: Kind.from_str(kind), kinds)) for child in self._children: if child._visibility == visibility and child._kind in kinds and child._static == static: ret.append(child) return ret @property def is_static(self) -> bool: return self._static @property def is_explicit(self) -> bool: return self._explicit @property def is_const(self) -> bool: return self._const @property def is_inline(self) -> bool: return self._inline @property def is_mutable(self) -> bool: return self._mutable @property def is_virtual(self) -> bool: return self._virtual @property def output_dir(self) -> str: return self._output_dir @property def is_pure(self) -> bool: return self._pure @property def has_children(self) -> bool: return len(self._children) > 0 @property def children(self) -> ['Node']: return self._children @property def parent(self) -> 'Node': return self._parent @property def is_function(self) -> bool: return self._kind.is_function() @property def is_variable(self) -> bool: return self._kind.is_variable() @property def is_namespace(self) -> bool: return self._kind.is_namespace() @property def is_class(self) -> bool: return self._kind.is_class() @property def is_struct(self) -> bool: return self._kind.is_struct() @property def is_enum(self) -> bool: return self._kind.is_enum() @property def is_class_or_struct(self) -> bool: return self._kind.is_class_or_struct() @property def is_interface(self) -> bool: return self._kind.is_interface() @property def is_typedef(self) -> bool: return self._kind.is_typedef() @property def is_define(self) -> bool: return self._kind.is_define() @property def is_union(self) -> bool: return self._kind.is_union() @property def is_group(self) -> bool: return self._kind.is_group() @property def is_language(self) -> bool: return self._kind.is_language() @property def is_root(self) -> bool: return self._kind.is_root() @property def is_parent(self) -> bool: return self._kind.is_parent() @property def is_friend(self) -> bool: return self._kind.is_friend() @property def is_file(self) -> bool: return self._kind.is_file() @property def is_function(self) -> bool: return self._kind.is_function() @property def is_dir(self) -> bool: return self._kind.is_dir() @property def is_page(self) -> bool: return self._kind.is_page() @property def name(self) -> str: return self._name @property def title(self) -> str: return self._title @property def refid(self) -> str: return self._refid @property def kind(self) -> str: return self._kind @property def is_operator(self) -> bool: return self._name in OVERLOAD_OPERATORS @property def operators_total(self) -> int: total = 0 for child in self.children: if child.name in OVERLOAD_OPERATORS: total += 1 return total @property def operator_num(self) -> int: total = 0 for child in self.parent.children: if child.is_function and child.name.replace(' ', '') in OVERLOAD_OPERATORS: total += 1 if child.refid == self._refid: break return total @property def name_url_safe(self) -> str: name = self.name_tokens[-1] name = name.replace(' ', '-').replace('_', '-').replace('=', '').replace('~', '').lower() return name @property def anchor(self) -> str: name = '' if self._name.replace(' ', '') in OVERLOAD_OPERATORS: num = self.operator_num if num > 1: name = 'operator-' + str(self.operator_num) else: name = 'operator' elif self.is_overloaded: name = self.name_url_safe + '-' + str(self.overload_num) + '-' + str(self.overload_total) else: name = self.name_url_safe if name.startswith('-'): name = name[1:] return self._kind.value + '-' + name @property def url(self) -> str: book = '' if self.doc_type == 'part': book = 'book' book = os.path.join(self.rel_path, book) book = os.path.join('/', book) if self.is_parent or self.is_typedef or self.is_group or self.is_file or self.is_dir or self.is_page or self.is_function: if self._position: dirs = self._position.split('/') rootdir = '' is_getxml = False for dir in dirs: if dir == 'XML': rootdir = '/' is_getxml = True continue if is_getxml: rootdir = rootdir + dir + '/' if self.is_typedef: return book + rootdir + 'typedeflist.md#' + self.anchor #/home/gx/goxceed/docs/XML/gxdownloader return book + rootdir + self._refid + '.md' #return '../' + os.path.basename(self._position) + '/' + self._refid + '.md' else: return book + rootdir + self._refid + '.md' elif self.is_enum: return book + '/' + self._refid + '.md' else: return self._parent.url + '#' + self.anchor @property def url_source(self) -> str: if self.is_parent or self.is_group or self.is_file or self.is_dir: return self._refid + '_source.md' else: return self._refid + '.md' @property def filename(self) -> str: return self._refid + '.md' @property def root(self) -> 'Node': if self._kind == Kind.ROOT: return self else: return self._parent.root @property def name_tokens(self) -> [str]: if self.is_dir or self.is_file: return self._name.split('/') return split_safe(self._name, '::') @property def name_short(self) -> str: return escape(self.name_tokens[-1]) @property def name_long(self) -> str: try: if self._parent.is_parent: return self._parent.name_long + '::' + escape(self.name_tokens[-1]) else: return escape(self._name) except Exception as e: raise e @property def name_full_unescaped(self) -> str: if self._parent is not None and not self._parent.is_root and self._parent.is_parent: return self._parent.name_full_unescaped + '::' + self.name_tokens[-1] else: return self.name_tokens[-1] @property def overload_total(self) -> int: if self._parent is not None: if self._parent.is_class_or_struct: count = 0 for neighbour in self._parent.children: if neighbour.name == self.name: count += 1 return count return 0 @property def overload_num(self) -> int: if self._parent is not None: if self._parent.is_class_or_struct: count = 0 for neighbour in self._parent.children: if neighbour.name == self.name: count += 1 if neighbour.refid == self.refid: break return count return 0 @property def is_overloaded(self) -> bool: return self.overload_total > 1 @property def overload_suffix(self) -> str: if self.is_operator: return '' total = self.overload_total if total > 1: return '[' + str(self.overload_num) + '/' + str(total) + ']' else: return '' @property def parents(self) -> ['Node']: if self._refid == 'dir_e76b55871a3ceedcbe1f9359e5753575': print(id(self)) print('debugger') ret = [] if self._parent is not None: if self._parent.is_language or self._parent.is_dir: ret.extend(self.parent.parents) ret.append(self) return ret @property def suffix(self) -> str: if self.is_parent: if self._templateparams.has(): return '&lt;' + ', '.join(self._templateparams.array(notype=True)) + '&gt;' else: return '' elif self.is_function: return self._specifiers.md() elif self.is_variable: if self._initializer.has(): return ' = ' + self._initializer.md() else: return '' elif self.is_define: params = self._params.md() test = self._initializer.md() # Do not use variable_initializer if it is if '\n' in test: return ' (' + params + ')' return '(' + params + ') ' + test else: return '' @property def prefix(self) -> str: if self.is_function: ret = [] if self.is_virtual: ret.append('virtual') return ' '.join(ret) elif self.kind is Kind.VARIABLE: return '' else: return self.kind.value @property def codeblock(self) -> str: code = [] if self.is_function or self.is_friend: if self._templateparams.has(): code.append('template<' + self._templateparams.plain() + '>') typ = self._type.plain() if typ: typ += ' ' if self.is_virtual: typ = 'virtual ' + typ if self.is_explicit: typ = 'explicit ' + typ if self.is_inline: typ = 'inline ' + typ if self.is_static: typ = 'static ' + typ #if self._params.has(): # code.append(typ + self.name_full_unescaped + ' (') # params = self._params.array(plain=True) # for i, param in enumerate(params): # if i + 1 >= len(params): # code.append(' ' + param) # else: # code.append(' ' + param + ',') # code.append(') ' + self._specifiers.plain()) #else: f_code = typ + self.name_full_unescaped + self._specifiers.plain() f_code = re.sub('\(', '(\n ', f_code) f_code = re.sub(',', ',\n ', f_code) f_code = re.sub('\)', '\n)', f_code) code.append( f_code ) elif self.is_enum: if self._values.has(): code.append('enum ' + self.name_full_unescaped + ' {') values = self._values.array(plain=True) for i, value in enumerate(values): value = re.sub('\*\*', '', value) value = re.sub('\\\\', '', value) if i + 1 >= len(values): code.append(' ' + value) else: code.append(' ' + value + ',') code.append('};') else: code.append('enum ' + self.name_full_unescaped + ';') elif self.is_define: if self._params.has(): code.append('#define ' + self.name_full_unescaped + ' (') params = self._params.array(plain=True) for i, param in enumerate(params): if i + 1 >= len(params): code.append(' ' + param) else: code.append(' ' + param + ',') code.append(') ' + self._initializer.plain()) else: code.append('#define ' + self.name_full_unescaped + ' () ' + self._specifiers.plain()) elif self.is_struct or self.is_union: pass if self.is_struct: code.append('struct ' + self.name_full_unescaped + ' {') else: name = self.name_full_unescaped name = re.sub('.+::','',name) code.append('union ' + name + ' {') if self.has_children: definitions = [] for child in self._children: if child.name and child.type: definitions.append(child._definition.plain()) typ = child._type.plain(); unioncode = '' if 'union' in typ: if '::' in typ: typ = re.sub('.+::','',typ) if typ[0] == '@': typ = '' node = None if not '@' in child._type.plain(): typ = 'union ' + typ nodename = re.sub('union ','',child._type.plain()) node = self._cache.get_on_name(nodename) unioncode = re.sub('union.+{', '{', node.codeblock) else: nodename = child.name node = self._cache.get_on_name(nodename) typ = 'union' #unioncode = 'union ' unioncode = re.sub('\n','\n ', unioncode) name = child.name; if unioncode: code.append(' ' + typ + unioncode + name + ';') else: if child.has_specifiers: code.append(' ' + typ + ' ' + name + child.specifiers + ';') else: code.append(' ' + typ + ' ' + name + ';') for child in self._children: if child.name and ( not child.type): get_union = 0 for definition1 in definitions: if 'union ' + child.name in definition1: continue get_union = 1 if get_union: continue unioncode = child.codeblock if 'union' in unioncode: unioncode = re.sub(' .+::', ' ', unioncode) unioncode = ' ' + unioncode + ';' unioncode = re.sub('\n', '\n ', unioncode) code.append(unioncode) code.append('}') else: code.append(self._definition.plain()) return '\n'.join(code) @property def has_base_classes(self) -> bool: return len(self._xml.findall('basecompoundref')) > 0 @property def has_derived_classes(self) -> bool: return len(self._xml.findall('derivedcompoundref')) > 0 @property def base_classes(self) -> ['Node']: ret = [] for basecompoundref in self._xml.findall('basecompoundref'): refid = basecompoundref.get('refid') if refid is None: ret.append(basecompoundref.text) else: ret.append(self._cache.get(refid)) return ret @property def derived_classes(self) -> ['Node']: ret = [] for derivedcompoundref in self._xml.findall('derivedcompoundref'): refid = derivedcompoundref.get('refid') if refid is None: ret.append(derivedcompoundref.text) else: ret.append(self._cache.get(refid)) return ret @property def has_details(self) -> bool: return self._details.has() def gxdocref_process(self, source_str): dist_str = source_str # doxygen 在生成xml时,把一部分gxdocref当作\ref处理,这里把这部分转换回原型 dist_str = re.sub("(gxdocref )\[\*\*(\S+)\*\*\]\(\S*\)", "\g<1>\g<2> ", dist_str) if re.findall('gxdocref \[', dist_str): dist_str = re.sub('gxdocref \[','[',dist_str) return dist_str # name = self._name.replace('_', '\\_') #refs = re.findall('gxdocref +[\S]+', dist_str) refs = re.findall('gxdocref +[^ \n\r\t\v\f、。,;,.;]+', dist_str) if refs: for ref in refs: refname = re.sub('gxdocref[\s]+', '', ref) refname = refname.replace('\\','') node = self._cache.get_on_name(refname) if not node: continue refname = refname.replace('_','\\\\_') #dist_str = re.sub('gxdocref *'+refname,'[**'+refname+'**]('+ # node.url + ')', dist_str) if self.doc_type == 'all': dist_str = re.sub('gxdocref *'+refname,'[**'+refname+'**]('+ node.url + ')', dist_str) else: #elif self.doc_type == 'part': dist_str = re.sub('gxdocref *'+refname,'[**'+refname+'**]('+ \ node.url + ')', dist_str) return dist_str @property def details(self) -> str: details = self._details.md() details = self.gxdocref_process(details) return details @property def has_brief(self) -> bool: return self._brief.has() @property def brief(self) -> str: brief = self._brief.md() brief = self.gxdocref_process(brief) return brief @property def has_includes(self) -> bool: return self._includes.has() @property def includes(self) -> str: return self._includes.plain() @property def has_type(self) -> bool: return self._type.has() @property def typedefstructtype(self) -> bool: type = self.type if "struct " in type: return True return False @property def type(self) -> str: return self._type.md() @property def typerefid(self) -> str: node = self._cache.get_on_name( self.type ) if node == None: return self.type + "NotFound" while node.is_typedef: node = self.cache.get_on_name( node.type ) if node == None: return self.type + "NotFound" return node.refid @property def has_location(self) -> bool: return self._location.has() @property def location(self) -> str: return self._location.plain() @property def has_params(self) -> bool: return self._params.has() @property def params(self) -> str: if self._params.has(): return '(' + self._params.md() + ')' elif self.is_function: return '()' else: return '' @property def has_templateparams(self) -> bool: return self._templateparams.has() @property def templateparams(self) -> str: return self._templateparams.md() @property def has_specifiers(self) -> bool: return self._specifiers.has() @property def specifiers(self) -> str: return self._specifiers.plain() @property def has_values(self) -> bool: return self._values.has() @property def values(self) -> str: return self._values.md() @property def has_initializer(self) -> bool: return self._initializer.has() @property def initializer(self) -> str: return self._initializer.md() @property def has_definition(self) -> bool: return self._definition.has() @property def definition(self) -> str: return self._definition.plain() @property def has_programlisting(self) -> bool: return self._programlisting.has() @property def programlisting(self) -> str: return self._programlisting.md() @property def is_resolved(self) -> bool: return True @property def reimplements(self) -> 'Node': reimp = self._xml.find('reimplements') if reimp is not None: return self._cache.get(reimp.get('refid')) else: return None class DummyNode: def __init__(self, name_long: str, derived_classes: [Node], kind: Kind): self.name_long = name_long self.derived_classes = derived_classes self.kind = kind @property def is_resolved(self) -> bool: return False
PypiClean
/Better-Than-You-Found-It-0.9.1.tar.gz/Better-Than-You-Found-It-0.9.1/pep8radius/main.py
from __future__ import print_function import os import sys try: from configparser import ConfigParser as SafeConfigParser, NoSectionError except ImportError: # py2, pragma: no cover from ConfigParser import SafeConfigParser, NoSectionError from pep8radius.radius import Radius, RadiusFromDiff from pep8radius.shell import CalledProcessError # with 2.6 compat __version__ = version = '0.9.1' DEFAULT_IGNORE = 'E24' DEFAULT_INDENT_SIZE = 4 if sys.platform == 'win32': # pragma: no cover DEFAULT_CONFIG = os.path.expanduser(r'~\.pep8') else: DEFAULT_CONFIG = os.path.join(os.getenv('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'pep8') PROJECT_CONFIG = ('setup.cfg', 'tox.ini', '.pep8') def main(args=None, vc=None, cwd=None, apply_config=False): """PEP8 clean only the parts of the files touched since the last commit, a previous commit or branch.""" import signal try: # pragma: no cover # Exit on broken pipe. signal.signal(signal.SIGPIPE, signal.SIG_DFL) except AttributeError: # pragma: no cover # SIGPIPE is not available on Windows. pass try: if args is None: args = [] try: # Note: argparse on py 2.6 you can't pass a set # TODO neater solution for this! args_set = set(args) except TypeError: args_set = args # args is a Namespace if '--version' in args_set or getattr(args_set, 'version', 0): print(version) sys.exit(0) if '--list-fixes' in args_set or getattr(args_set, 'list_fixes', 0): from autopep8 import supported_fixes for code, description in sorted(supported_fixes()): print('{code} - {description}'.format( code=code, description=description)) sys.exit(0) try: try: args = parse_args(args, apply_config=apply_config) except TypeError: pass # args is already a Namespace (testing) if args.from_diff: # pragma: no cover r = Radius.from_diff(args.from_diff.read(), options=args, cwd=cwd) else: r = Radius(rev=args.rev, options=args, vc=vc, cwd=cwd) except NotImplementedError as e: # pragma: no cover print(e) sys.exit(1) except CalledProcessError as c: # pragma: no cover # cut off usage and exit output = c.output.splitlines()[0] print(output) sys.exit(c.returncode) r.fix() except KeyboardInterrupt: # pragma: no cover return 1 def create_parser(): """Create the parser for the pep8radius CLI.""" from argparse import ArgumentParser, FileType description = ("PEP8 clean only the parts of the files which you have " "touched since the last commit, a previous commit or " "(the merge-base of) a branch.") epilog = ("Run before you commit, against a previous commit or " "branch before merging.") parser = ArgumentParser(description=description, epilog=epilog, prog='pep8radius') parser.add_argument('rev', help='commit or name of branch to compare against', nargs='?') parser.add_argument('--version', help='print version number and exit', action='store_true') parser.add_argument('-d', '--diff', action='store_true', dest='diff', help='print the diff of fixed source vs original') parser.add_argument('-i', '--in-place', action='store_true', help="make the fixes in place; modify the files") parser.add_argument('--no-color', action='store_true', help='do not print diffs in color ' '(default is to use color)') parser.add_argument('-v', '--verbose', action='count', dest='verbose', default=0, help='print verbose messages; ' 'multiple -v result in more verbose messages ' '(one less -v is passed to autopep8)') parser.add_argument('--from-diff', type=FileType('r'), metavar='DIFF', help="Experimental: rather than calling out to version" " control, just pass in a diff; " "the modified lines will be fixed") ap = parser.add_argument_group('pep8', 'Pep8 options to pass to autopep8.') ap.add_argument('-p', '--pep8-passes', metavar='n', default=-1, type=int, help='maximum number of additional pep8 passes ' '(default: infinite)') ap.add_argument('-a', '--aggressive', action='count', default=0, help='enable non-whitespace changes; ' 'multiple -a result in more aggressive changes') ap.add_argument('--experimental', action='store_true', help='enable experimental fixes') ap.add_argument('--exclude', metavar='globs', help='exclude file/directory names that match these ' 'comma-separated globs') ap.add_argument('--list-fixes', action='store_true', help='list codes for fixes and exit; ' 'used by --ignore and --select') ap.add_argument('--ignore', metavar='errors', default='', help='do not fix these errors/warnings ' '(default: {0})'.format(DEFAULT_IGNORE)) ap.add_argument('--select', metavar='errors', default='', help='fix only these errors/warnings (e.g. E4,W)') ap.add_argument('--max-line-length', metavar='n', default=79, type=int, help='set maximum allowed line length ' '(default: %(default)s)') ap.add_argument('--indent-size', default=DEFAULT_INDENT_SIZE, type=int, metavar='n', help='number of spaces per indent level ' '(default %(default)s)') df = parser.add_argument_group('docformatter', 'Fix docstrings for PEP257.') df.add_argument('-f', '--docformatter', action='store_true', help='Use docformatter') df.add_argument('--no-blank', dest='post_description_blank', action='store_false', help='Do not add blank line after description') df.add_argument('--pre-summary-newline', action='store_true', help='add a newline before the summary of a ' 'multi-line docstring') df.add_argument('--force-wrap', action='store_true', help='force descriptions to be wrapped even if it may ' 'result in a mess') cg = parser.add_argument_group('config', 'Change default options based on global ' 'or local (project) config files.') cg.add_argument('--global-config', default=DEFAULT_CONFIG, metavar='filename', help='path to global pep8 config file; ' + " if this file does not exist then this is ignored" + '(default: %s)' % DEFAULT_CONFIG) cg.add_argument('--ignore-local-config', action='store_true', help="don't look for and apply local config files; " 'if not passed, defaults are updated with any ' "config files in the project's root directory") return parser def parse_args(arguments=None, root=None, apply_config=False): """Parse the arguments from the CLI. If apply_config then we first look up and apply configs using apply_config_defaults. """ if arguments is None: arguments = [] parser = create_parser() args = parser.parse_args(arguments) if apply_config: parser = apply_config_defaults(parser, args, root=root) args = parser.parse_args(arguments) # sanity check args (from autopep8) if args.max_line_length <= 0: # pragma: no cover parser.error('--max-line-length must be greater than 0') if args.select: args.select = _split_comma_separated(args.select) if args.ignore: args.ignore = _split_comma_separated(args.ignore) elif not args.select and args.aggressive: # Enable everything by default if aggressive. args.select = ['E', 'W'] else: args.ignore = _split_comma_separated(DEFAULT_IGNORE) if args.exclude: args.exclude = _split_comma_separated(args.exclude) else: args.exclude = [] return args def apply_config_defaults(parser, args, root): """Update the parser's defaults from either the arguments' config_arg or the config files given in config_files(root).""" if root is None: try: from pep8radius.vcs import VersionControl root = VersionControl.which().root_dir() except NotImplementedError: pass # don't update local, could be using as module config = SafeConfigParser() config.read(args.global_config) if root and not args.ignore_local_config: config.read(local_config_files(root)) try: defaults = dict((k.lstrip('-').replace('-', '_'), v) for k, v in config.items("pep8")) parser.set_defaults(**defaults) except NoSectionError: pass # just do nothing, potentially this could raise ? return parser def local_config_files(root): """Returns a list of (possible) config files in the project root directory.""" return [os.path.join(root, c) for c in PROJECT_CONFIG] def _split_comma_separated(string): """Return a set of strings.""" return set(filter(None, string.split(','))) def _main(args=None, vc=None, cwd=None): # pragma: no cover if args is None: args = sys.argv[1:] return main(args=args, vc=vc, cwd=cwd, apply_config=True) if __name__ == "__main__": # pragma: no cover _main()
PypiClean
/AutoTransform-1.1.1a8-py3-none-any.whl/autotransform/step/action/reviewers.py
# @black_format """All Actions associated with a Change's reviewers.""" from typing import Any, ClassVar, Dict, List from pydantic import Field, root_validator, validator from autotransform.change.base import Change from autotransform.step.action.base import Action, ActionName class AddReviewersAction(Action): """Adds reviewers to an existing Change. Attributes: reviewers(optional, List[str]): The list of reviewers to add. Defaults to []. team_reviewers(optional, List[str]): The list of team reviewers to add. Defaults to []. name (ClassVar[ActionName]): The name of the component. """ reviewers: List[str] = Field(default_factory=list) team_reviewers: List[str] = Field(default_factory=list) name: ClassVar[ActionName] = ActionName.ADD_REVIEWERS # pylint: disable=invalid-name @validator("reviewers") @classmethod def labels_must_be_non_empty(cls, v: List[str]) -> List[str]: """Validates the reviewers are not empty strings. Args: v (List[str]): The reviewers to add to the Change. Raises: ValueError: Raises an error if a reviewer is an empty string. Returns: List[str]: The unmodified reviewers to add. """ if any(reviewer == "" for reviewer in v): raise ValueError("Reviewers must be non-empty strings") return v # pylint: disable=invalid-name @validator("team_reviewers") @classmethod def team_reviewers_must_be_non_empty(cls, v: List[str]) -> List[str]: """Validates the team reviewers are not empty strings. Args: v (List[str]): The team reviewers to add to the Change. Raises: ValueError: Raises an error if a team reviewer is an empty string. Returns: List[str]: The unmodified team reviewers to add. """ if any(team_reviewer == "" for team_reviewer in v): raise ValueError("Team reviewers must be non-empty strings") return v @root_validator @classmethod def some_reviewers_must_be_provided(cls, values: Dict[str, Any]) -> Dict[str, Any]: """Checks that either reviewers or team reviewers are supplied. Args: values (Dict[str, Any]): The values for the action. Raises: ValueError: Raises an error if neither reviewers nor team reviewers are supplied. Returns: Dict[str, Any]: The unmodified values. """ reviewers, team_reviewers = values.get("reviewers"), values.get("team_reviewers") if not reviewers and not team_reviewers: raise ValueError("Either reviewers or team reviewers must be supplied") return values def run(self, change: Change) -> bool: """Adds reviewers to the specified Change. Args: change (Change): The Change to add reviewers to. Returns: bool: Whether the reviewers were added successful. """ return change.add_reviewers(self.reviewers, self.team_reviewers) class AddOwnersAsReviewersAction(Action): """Adds the owners of a Schema as reviewers for the Change. Attributes: name (ClassVar[ActionName]): The name of the component. """ name: ClassVar[ActionName] = ActionName.ADD_OWNERS_AS_REVIEWERS def run(self, change: Change) -> bool: """Adds owners as reviewers to the specified Change. Args: change (Change): The Change to add reviewers to. Returns: bool: Whether the reviewers were added successful. """ return change.add_reviewers(change.get_schema().config.owners, []) class AddOwnersAsTeamReviewersAction(Action): """Adds the owners of a Schema as team reviewers for the Change. Attributes: name (ClassVar[ActionName]): The name of the component. """ name: ClassVar[ActionName] = ActionName.ADD_OWNERS_AS_TEAM_REVIEWERS def run(self, change: Change) -> bool: """Adds owners as team reviewers to the specified Change. Args: change (Change): The Change to add team reviewers to. Returns: bool: Whether the team reviewers were added successful. """ return change.add_reviewers([], change.get_schema().config.owners)
PypiClean
/CellProfiler-4.2.6.tar.gz/CellProfiler-4.2.6/cellprofiler/gui/module_view/_filter_panel_controller.py
import logging import wx from cellprofiler_core.setting.filter import Filter, FilterPredicate from cellprofiler_core.setting.filter._filter import ( AND_PREDICATE, OR_PREDICATE, LITERAL_PREDICATE, ) from ._module_view import ModuleView from ..utilities.module_view import edit_control_name class FilterPanelController(object): """Handle representation of the filter panel The code for handling the filter UI is moderately massive, so it gets its own class, if for no other reason than to organize the code. """ def __init__(self, module_view, v, panel): assert isinstance(module_view, ModuleView) assert isinstance(v, Filter) self.module_view = module_view self.v = v self.panel = wx.Panel( self.module_view.module_panel, style=wx.TAB_TRAVERSAL, name=edit_control_name(self.v), ) self.panel.Sizer = wx.BoxSizer(wx.VERTICAL) self.sizer_dict = {} self.sizer_item_dict = {} self.stretch_spacer_dict = {} self.hide_show_dict = {} self.update() def get_sizer(self, address): """Find or create the sizer that's associated with a particular address""" key = tuple(address) line_name = self.line_name(address) self.hide_show_dict[line_name] = True if key in self.sizer_dict: if len(address) > 0: self.hide_show_dict[self.remove_button_name(address)] = True self.hide_show_dict[self.add_button_name(address)] = True self.hide_show_dict[self.add_group_button_name(address)] = True return self.sizer_dict[key] # # Four possibilities: # # * The sizer is the top level one # * There is a sizer at the same level whose last address is one more. # * There are sizers at the same level whose next to last to address is # one more than the next to last address of the address and whose # last address is zero. # * None of the above which means the sizer can be added at the end. # line_style = wx.LI_HORIZONTAL | wx.BORDER_SUNKEN sizer = wx.BoxSizer(wx.HORIZONTAL) self.indent(sizer, address) self.stretch_spacer_dict[key] = sizer.AddStretchSpacer() line = wx.StaticLine( self.panel, -1, style=line_style, name=self.line_name(address) ) if len(address) == 0: key = None else: sizer.Add( self.make_delete_button(address), 0, wx.ALIGN_CENTER_VERTICAL, ) sizer.Add( self.make_add_rule_button(address), 0, wx.ALIGN_CENTER_VERTICAL, ) sizer.Add( self.make_add_rules_button(address), 0, wx.ALIGN_CENTER_VERTICAL, ) key = tuple(address[:-1] + [address[-1] + 1]) if key not in self.sizer_dict: if len(address) == 1: key = None else: key = tuple(address[:-2] + [address[-2] + 1]) if key not in self.sizer_dict: key = None if key is not None: next_sizer = self.sizer_dict[key] idx = self.get_sizer_index(self.panel.Sizer, next_sizer) self.panel.Sizer.Insert(idx, sizer, 0, wx.EXPAND) self.panel.Sizer.Insert(idx + 1, line, 0, wx.EXPAND) else: self.panel.Sizer.Add(sizer, 0, wx.EXPAND) self.panel.Sizer.Add(line, 0, wx.EXPAND) self.sizer_dict[tuple(address)] = sizer return sizer def get_tokens(self): try: tokens = self.v.parse() except Exception as e: logging.debug( "Failed to parse filter (value=%s): %s", self.v.value_text, str(e) ) tokens = self.v.default() # # Always require an "and" or "or" clause # if len(tokens) == 0 or (tokens[0] not in (AND_PREDICATE, OR_PREDICATE,)): tokens = [AND_PREDICATE, tokens] return tokens def update(self): self.inside_update = True try: structure = self.get_tokens() for key in self.hide_show_dict: self.hide_show_dict[key] = False self.populate_subpanel(structure, []) for key, value in list(self.hide_show_dict.items()): self.panel.FindWindowByName(key).Show(value) self.panel.Layout() except: logging.exception("Threw exception while updating filter") finally: self.inside_update = False ANY_ALL_PREDICATES = [ AND_PREDICATE, OR_PREDICATE, ] def any_all_choices(self): return [x.display_name for x in self.ANY_ALL_PREDICATES] @staticmethod def indent(sizer, address): assert isinstance(sizer, wx.Sizer) if len(address) == 0: return sizer.AddSpacer(len(address) * 20) def find_and_mark(self, name): """Find a control and mark it to be shown""" ctrl = self.panel.FindWindowByName(name) self.hide_show_dict[name] = True return ctrl @staticmethod def get_sizer_index(sizer, item): if isinstance(item, wx.Sizer): indexes = [ i for i, s in enumerate(sizer.GetChildren()) if s.IsSizer() and s.GetSizer() is item ] elif isinstance(item, wx.Window): indexes = [ i for i, s in enumerate(sizer.GetChildren()) if s.IsWindow() and s.GetWindow() is item ] elif isinstance(item, wx.SizerItem): return sizer.GetChildren().index(item) if len(indexes) > 0: return indexes[0] return None def on_value_change(self, event, new_text, timeout=None): if not self.inside_update: self.module_view.on_value_change( self.v, self.panel, new_text, event, timeout ) def make_delete_button(self, address): name = self.remove_button_name(address) button = self.find_and_mark(name) if button is not None: return button button = wx.Button(self.panel, -1, "-", name=name, style=wx.BU_EXACTFIT) button.Bind(wx.EVT_BUTTON, lambda event: self.on_delete_rule(event, address)) return button def on_delete_rule(self, event, address): logging.debug("Delete row at " + str(address)) structure = self.v.parse() sequence = self.find_address(structure, address[:-1]) del sequence[address[-1] + 1] new_text = self.v.build_string(structure) self.on_value_change(event, new_text) def make_add_rule_button(self, address): name = self.add_button_name(address) button = self.find_and_mark(name) if button is not None: return button button = wx.Button(self.panel, -1, "+", name=name, style=wx.BU_EXACTFIT) button.Bind(wx.EVT_BUTTON, lambda event: self.on_add_rule(event, address)) return button def on_add_rule(self, event, address): logging.debug("Add rule after " + str(address)) structure = self.v.parse() sequence = self.find_address(structure, address[:-1]) new_rule = self.v.default() sequence.insert(address[-1] + 2, new_rule) new_text = self.v.build_string(structure) self.on_value_change(event, new_text) def make_add_rules_button(self, address): name = self.add_group_button_name(address) button = self.find_and_mark(name) if button is not None: return button button = wx.Button(self.panel, -1, "...", name=name, style=wx.BU_EXACTFIT) button.Bind(wx.EVT_BUTTON, lambda event: self.on_add_rules(event, address)) return button def on_add_rules(self, event, address): logging.debug("Add rules after " + str(address)) structure = self.v.parse() sequence = self.find_address(structure, address[:-1]) new_rule = [OR_PREDICATE, self.v.default()] sequence.insert(address[-1] + 2, new_rule) new_text = self.v.build_string(structure) self.on_value_change(event, new_text) def make_predicate_choice(self, predicates, index, address, sizer): name = self.choice_name(index, address) choice_ctrl = self.find_and_mark(name) choices = [x.display_name for x in predicates] if choice_ctrl is not None: items = choice_ctrl.GetItems() if len(items) != len(choices) or any( [choice not in items for choice in choices] ): choice_ctrl.SetItems(choices) return choice_ctrl choice_ctrl = wx.Choice(self.panel, -1, choices=choices, name=name) choice_ctrl.Bind( wx.EVT_CHOICE, lambda event: self.on_predicate_changed(event, index, address), ) choice_ctrl.Bind(wx.EVT_MOUSEWHEEL, self.ignore_mousewheel) self.add_to_sizer(sizer, choice_ctrl, index, address) return choice_ctrl def on_predicate_changed(self, event, index, address): logging.debug( "Predicate choice at %d / %s changed" % (index, self.saddress(address)) ) structure = self.v.parse() sequence = self.find_address(structure, address) while len(sequence) <= index: # The sequence is bad (e.g., bad pipeline or metadata collection) # Fill in enough to deal # sequence.append( self.v.predicates[0] if len(sequence) == 0 else sequence[-1].subpredicates[0] ) if index == 0: predicates = self.v.predicates else: predicates = sequence[index - 1].subpredicates new_predicate = predicates[event.GetSelection()] sequence[index] = new_predicate predicates = new_predicate.subpredicates # # Make sure following predicates are legal # for index in range(index + 1, len(sequence)): if isinstance(sequence[index], str): is_good = LITERAL_PREDICATE in predicates else: matches = [p for p in predicates if sequence[index].symbol == p.symbol] is_good = len(matches) == 1 if is_good: sequence[index] = matches[0] if not is_good: del sequence[index:] sequence += self.v.default(predicates) break if not isinstance(sequence[index], FilterPredicate): break predicates = sequence[index].subpredicates new_text = self.v.build_string(structure) self.on_value_change(event, new_text) def add_to_sizer(self, sizer, item, index, address): """Insert the item in the sizer at the right location sizer - sizer for the line item - the control to be added index - index of the control within the sizer address - address of the sizer """ key = tuple(address + [index]) next_key = tuple(address + [index + 1]) if next_key in self.sizer_item_dict: next_ctrl = self.sizer_item_dict[next_key] else: next_ctrl = self.stretch_spacer_dict[tuple(address)] index = self.get_sizer_index(sizer, next_ctrl) sizer.Insert(index, item, 0, wx.ALIGN_LEFT) if key not in self.sizer_item_dict: self.sizer_item_dict[key] = item def make_literal(self, token, index, address, sizer): name = self.literal_name(index, address) literal_ctrl = self.find_and_mark(name) if literal_ctrl is not None: if literal_ctrl.GetValue() != token: literal_ctrl.SetValue(token) return literal_ctrl literal_ctrl = wx.TextCtrl(self.panel, -1, token, name=name) literal_ctrl.Bind( wx.EVT_TEXT, lambda event: self.on_literal_changed(event, index, address) ) self.add_to_sizer(sizer, literal_ctrl, index, address) return literal_ctrl def on_literal_changed(self, event, index, address): logging.debug("Literal at %d / %s changed" % (index, self.saddress(address))) try: structure = self.v.parse() sequence = self.find_address(structure, address) while len(sequence) <= index: # The sequence is bad (e.g., bad pipeline or metadata collection) # Fill in enough to deal # sequence.append( self.v.predicates[0] if len(sequence) == 0 else sequence[-1].subpredicates[0] ) sequence[index] = event.GetString() except: structure = self.v.default() new_text = self.v.build_string(structure) self.on_value_change( event, new_text, timeout=None if self.v.reset_view else False ) def make_anyall_ctrl(self, address): anyall = wx.Choice( self.panel, -1, choices=self.any_all_choices(), name=self.anyall_choice_name(address), ) anyall.Bind(wx.EVT_CHOICE, lambda event: self.on_anyall_changed(event, address)) anyall.Bind(wx.EVT_MOUSEWHEEL, self.ignore_mousewheel) return anyall def on_anyall_changed(self, event, address): logging.debug("Any / all choice at %s changed" % self.saddress(address)) structure = self.v.parse() sequence = self.find_address(structure, address) predicate = self.ANY_ALL_PREDICATES[event.GetSelection()] sequence[0] = predicate new_text = self.v.build_string(structure) self.on_value_change(event, new_text) def find_address(self, sequence, address): """Find the sequence with the given address""" if len(address) == 0: return sequence subsequence = sequence[address[0] + 1] return self.find_address(subsequence, address[1:]) def populate_subpanel(self, structure, address): parent_sizer = self.panel.Sizer any_all_name = self.anyall_choice_name(address) anyall = self.find_and_mark(any_all_name) self.hide_show_dict[self.static_text_name(0, address)] = True if len(address) == 0: self.hide_show_dict[self.static_text_name(1, address)] = True if anyall is None: anyall = self.make_anyall_ctrl(address) sizer = self.get_sizer(address) idx = self.get_sizer_index(sizer, self.stretch_spacer_dict[tuple(address)]) if len(address) == 0: text = wx.StaticText( self.panel, -1, "Match", name=self.static_text_name(0, address) ) sizer.Insert(idx, text, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL) sizer.Insert(idx + 1, 3, 0) sizer.Insert( idx + 2, anyall, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL ) sizer.Insert(idx + 3, 3, 0) text = wx.StaticText( self.panel, -1, "of the following rules", name=self.static_text_name(1, address), ) sizer.Insert(idx + 4, text, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL) else: sizer.Insert( idx, anyall, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.RIGHT ) sizer.Insert(idx + 1, 3, 0) text = wx.StaticText( self.panel, -1, "of the following are true", name=self.static_text_name(0, address), ) sizer.Insert(idx + 2, text, 0, wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL) else: self.hide_show_dict[self.line_name(address)] = True if len(address) > 0: # # Show the buttons for the anyall if not top level # self.hide_show_dict[self.remove_button_name(address)] = True self.hide_show_dict[self.add_button_name(address)] = True self.hide_show_dict[self.add_group_button_name(address)] = True if anyall.GetStringSelection() != structure[0].display_name: anyall.SetStringSelection(structure[0].display_name) anyall.SetToolTip(structure[0].doc) # # Now each subelement should be a list. # for subindex, substructure in enumerate(structure[1:]): subaddress = address + [subindex] if substructure[0].subpredicates is list: # A sublist self.populate_subpanel(substructure, subaddress) else: # A list of predicates sizer = self.get_sizer(subaddress) predicates = self.v.predicates for i, token in enumerate(substructure): if isinstance(token, str): literal_ctrl = self.make_literal(token, i, subaddress, sizer) predicates = [] else: choice_ctrl = self.make_predicate_choice( predicates, i, subaddress, sizer ) if choice_ctrl.GetStringSelection() != token.display_name: choice_ctrl.SetStringSelection(token.display_name) if token.doc is not None: choice_ctrl.SetToolTip(token.doc) predicates = token.subpredicates i = len(substructure) while len(predicates) > 0: # # We can get here if there's a badly constructed token # list - for instance if an invalid subpredicate was # chosen or none existed because of some error, but now # they do. # if len(predicates) == 1 and predicates[0] is LITERAL_PREDICATE: self.make_literal("", i, subaddress, sizer) else: self.make_predicate_choice(predicates, i, subaddress, sizer) i += 1 predicates = predicates[0].subpredicates # # Don't allow delete of only rule # name = self.remove_button_name(address + [0]) delete_button = self.panel.FindWindowByName(name) delete_button.Enable(len(structure) > 2) @property def key(self): return str(self.v.key()) @staticmethod def saddress(address): return "_".join([str(x) for x in address]) def anyall_choice_name(self, address): return "%s_filter_anyall_%s" % (self.key, self.saddress(address)) def choice_name(self, index, address): return "%s_choice_%d_%s" % (self.key, index, self.saddress(address)) def literal_name(self, index, address): return "%s_literal_%d_%s" % (self.key, index, self.saddress(address)) def remove_button_name(self, address): return "%s_remove_%s" % (self.key, self.saddress(address)) def add_button_name(self, address): return "%s_add_%s" % (self.key, self.saddress(address)) def add_group_button_name(self, address): return "%s_group_%s" % (self.key, self.saddress(address)) def line_name(self, address): return "%s_line_%s" % (self.key, self.saddress(address)) def static_text_name(self, index, address): return "%s_static_text_%d_%s" % (self.key, index, self.saddress(address)) def ignore_mousewheel(self, event): return
PypiClean
/EOxServer-1.2.12-py3-none-any.whl/eoxserver/services/ows/wcs/interfaces.py
class WCSCapabilitiesRendererInterface(object): """ Interface for WCS Capabilities renderers. """ def render(self, params): """ Render the capabilities including information about the given coverages. """ def supports(self, params): """ Returns a boolean value to indicate whether or not the renderer is able to render the capabilities with the given parameters. """ class WCSCoverageDescriptionRendererInterface(object): """ Interface for coverage description renderers. """ def render(self, params): """ Render the description of the given coverages. """ def supports(self, params): """ Returns a boolean value to indicate whether or not the renderer is able to render the coverage and the given WCS version. """ class WCSCoverageRendererInterface(object): """ Interface for coverage renderers. """ def render(self, params): """ Render the coverage with the given parameters. """ def supports(self, params): """ Returns a boolean value to indicate whether or not the renderer is able to render the coverage with the given parameters. """ class PackageWriterInterface(object): """ Interface for package writers. """ def supports(self, format, params): """ Return a boolen value, whether or not a writer supports a given format. """ def create_package(self, filename, format, params): """ Create a package, which the encoder can later add items to with the `cleanup` and `add_to_package` method. """ def cleanup(self, package): """ Perform any necessary cleanups, like closing files, etc. """ def add_to_package(self, package, file_obj, size, location): """ Add the file object to the package, that is returned by the `create_package` method. """ def get_mime_type(self, package, format, params): """ Retrieve the output mime type for the given package and/or format specifier. """ def get_file_extension(self, package, format, params): """ Retrieve the file extension for the given package and format specifier. """ class EncodingExtensionInterface(object): def supports(self, format, options): """ Return a boolen value, whether or not an encoding extension supports a given format. """ def parse_encoding_params(self, request): """ Return a dict, containing all additional encoding parameters from a given request. """
PypiClean
/DI_engine-0.4.9-py3-none-any.whl/ding/entry/cli.py
from typing import List, Union import os import copy import click from click.core import Context, Option import numpy as np from ding import __TITLE__, __VERSION__, __AUTHOR__, __AUTHOR_EMAIL__ from ding.config import read_config from .predefined_config import get_predefined_config def print_version(ctx: Context, param: Option, value: bool) -> None: if not value or ctx.resilient_parsing: return click.echo('{title}, version {version}.'.format(title=__TITLE__, version=__VERSION__)) click.echo('Developed by {author}, {email}.'.format(author=__AUTHOR__, email=__AUTHOR_EMAIL__)) ctx.exit() def print_registry(ctx: Context, param: Option, value: str): if value is None: return from ding.utils import registries # noqa if value not in registries: click.echo('[ERROR]: not support registry name: {}'.format(value)) else: registered_info = registries[value].query_details() click.echo('Available {}: [{}]'.format(value, '|'.join(registered_info.keys()))) for alias, info in registered_info.items(): click.echo('\t{}: registered at {}#{}'.format(alias, info[0], info[1])) ctx.exit() CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option( '-v', '--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True, help="Show package's version information." ) @click.option( '-q', '--query-registry', type=str, callback=print_registry, expose_value=False, is_eager=True, help='query registered module or function, show name and path' ) @click.option( '-m', '--mode', type=click.Choice( [ 'serial', 'serial_onpolicy', 'serial_sqil', 'serial_dqfd', 'serial_trex', 'serial_trex_onpolicy', 'parallel', 'dist', 'eval', 'serial_reward_model', 'serial_gail', 'serial_offline', 'serial_ngu', ] ), help='serial-train or parallel-train or dist-train or eval' ) @click.option('-c', '--config', type=str, help='Path to DRL experiment config') @click.option( '-s', '--seed', type=int, default=[0], multiple=True, help='random generator seed(for all the possible package: random, numpy, torch and user env)' ) @click.option('-e', '--env', type=str, help='RL env name') @click.option('-p', '--policy', type=str, help='DRL policy name') @click.option('--exp-name', type=str, help='experiment directory name') @click.option('--train-iter', type=str, default='1e8', help='Maximum policy update iterations in training') @click.option('--env-step', type=str, default='1e8', help='Maximum collected environment steps for training') @click.option('--load-path', type=str, default=None, help='Path to load ckpt') @click.option('--replay-path', type=str, default=None, help='Path to save replay') # the following arguments are only applied to dist mode @click.option('--enable-total-log', type=bool, help='whether enable the total DI-engine system log', default=False) @click.option('--disable-flask-log', type=bool, help='whether disable flask log', default=True) @click.option( '-P', '--platform', type=click.Choice(['local', 'slurm', 'k8s']), help='local or slurm or k8s', default='local' ) @click.option( '-M', '--module', type=click.Choice(['config', 'collector', 'learner', 'coordinator', 'learner_aggregator', 'spawn_learner']), help='dist module type' ) @click.option('--module-name', type=str, help='dist module name') @click.option('-cdh', '--coordinator-host', type=str, help='coordinator host', default='0.0.0.0') @click.option('-cdp', '--coordinator-port', type=int, help='coordinator port') @click.option('-lh', '--learner-host', type=str, help='learner host', default='0.0.0.0') @click.option('-lp', '--learner-port', type=int, help='learner port') @click.option('-clh', '--collector-host', type=str, help='collector host', default='0.0.0.0') @click.option('-clp', '--collector-port', type=int, help='collector port') @click.option('-agh', '--aggregator-host', type=str, help='aggregator slave host', default='0.0.0.0') @click.option('-agp', '--aggregator-port', type=int, help='aggregator slave port') @click.option('--add', type=click.Choice(['collector', 'learner']), help='add replicas type') @click.option('--delete', type=click.Choice(['collector', 'learner']), help='delete replicas type') @click.option('--restart', type=click.Choice(['collector', 'learner']), help='restart replicas type') @click.option('--kubeconfig', type=str, default=None, help='the path of Kubernetes configuration file') @click.option('-cdn', '--coordinator-name', type=str, default=None, help='coordinator name') @click.option('-ns', '--namespace', type=str, default=None, help='job namespace') @click.option('-rs', '--replicas', type=int, default=1, help='number of replicas to add/delete/restart') @click.option('-rpn', '--restart-pod-name', type=str, default=None, help='restart pod name') @click.option('--cpus', type=int, default=0, help='The requested CPU, read the value from DIJob yaml by default') @click.option('--gpus', type=int, default=0, help='The requested GPU, read the value from DIJob yaml by default') @click.option( '--memory', type=str, default=None, help='The requested Memory, read the value from DIJob yaml by default' ) @click.option( '--profile', type=str, default=None, help='profile Time cost by cProfile, and save the files into the specified folder path' ) def cli( # serial/eval mode: str, config: str, seed: Union[int, List], exp_name: str, env: str, policy: str, train_iter: str, # transform into int env_step: str, # transform into int load_path: str, replay_path: str, # parallel/dist platform: str, coordinator_host: str, coordinator_port: int, learner_host: str, learner_port: int, collector_host: str, collector_port: int, aggregator_host: str, aggregator_port: int, enable_total_log: bool, disable_flask_log: bool, module: str, module_name: str, # add/delete/restart add: str, delete: str, restart: str, kubeconfig: str, coordinator_name: str, namespace: str, replicas: int, cpus: int, gpus: int, memory: str, restart_pod_name: str, profile: str, ): if profile is not None: from ..utils.profiler_helper import Profiler profiler = Profiler() profiler.profile(profile) train_iter = int(float(train_iter)) env_step = int(float(env_step)) def run_single_pipeline(seed, config): if config is None: config = get_predefined_config(env, policy) else: config = read_config(config) if exp_name is not None: config[0].exp_name = exp_name if mode == 'serial': from .serial_entry import serial_pipeline serial_pipeline(config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_onpolicy': from .serial_entry_onpolicy import serial_pipeline_onpolicy serial_pipeline_onpolicy(config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_sqil': from .serial_entry_sqil import serial_pipeline_sqil expert_config = input("Enter the name of the config you used to generate your expert model: ") serial_pipeline_sqil(config, expert_config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_reward_model': from .serial_entry_reward_model_offpolicy import serial_pipeline_reward_model_offpolicy serial_pipeline_reward_model_offpolicy(config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_gail': from .serial_entry_gail import serial_pipeline_gail expert_config = input("Enter the name of the config you used to generate your expert model: ") serial_pipeline_gail( config, expert_config, seed, max_train_iter=train_iter, max_env_step=env_step, collect_data=True ) elif mode == 'serial_dqfd': from .serial_entry_dqfd import serial_pipeline_dqfd expert_config = input("Enter the name of the config you used to generate your expert model: ") assert (expert_config == config[:config.find('_dqfd')] + '_dqfd_config.py'), "DQFD only supports "\ + "the models used in q learning now; However, one should still type the DQFD config in this "\ + "place, i.e., {}{}".format(config[:config.find('_dqfd')], '_dqfd_config.py') serial_pipeline_dqfd(config, expert_config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_trex': from .serial_entry_trex import serial_pipeline_trex serial_pipeline_trex(config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_trex_onpolicy': from .serial_entry_trex_onpolicy import serial_pipeline_trex_onpolicy serial_pipeline_trex_onpolicy(config, seed, max_train_iter=train_iter, max_env_step=env_step) elif mode == 'serial_offline': from .serial_entry_offline import serial_pipeline_offline serial_pipeline_offline(config, seed, max_train_iter=train_iter) elif mode == 'serial_ngu': from .serial_entry_ngu import serial_pipeline_ngu serial_pipeline_ngu(config, seed, max_train_iter=train_iter) elif mode == 'parallel': from .parallel_entry import parallel_pipeline parallel_pipeline(config, seed, enable_total_log, disable_flask_log) elif mode == 'dist': from .dist_entry import dist_launch_coordinator, dist_launch_collector, dist_launch_learner, \ dist_prepare_config, dist_launch_learner_aggregator, dist_launch_spawn_learner, \ dist_add_replicas, dist_delete_replicas, dist_restart_replicas if module == 'config': dist_prepare_config( config, seed, platform, coordinator_host, learner_host, collector_host, coordinator_port, learner_port, collector_port ) elif module == 'coordinator': dist_launch_coordinator(config, seed, coordinator_port, disable_flask_log) elif module == 'learner_aggregator': dist_launch_learner_aggregator( config, seed, aggregator_host, aggregator_port, module_name, disable_flask_log ) elif module == 'collector': dist_launch_collector(config, seed, collector_port, module_name, disable_flask_log) elif module == 'learner': dist_launch_learner(config, seed, learner_port, module_name, disable_flask_log) elif module == 'spawn_learner': dist_launch_spawn_learner(config, seed, learner_port, module_name, disable_flask_log) elif add in ['collector', 'learner']: dist_add_replicas(add, kubeconfig, replicas, coordinator_name, namespace, cpus, gpus, memory) elif delete in ['collector', 'learner']: dist_delete_replicas(delete, kubeconfig, replicas, coordinator_name, namespace) elif restart in ['collector', 'learner']: dist_restart_replicas(restart, kubeconfig, coordinator_name, namespace, restart_pod_name) else: raise Exception elif mode == 'eval': from .application_entry import eval eval(config, seed, load_path=load_path, replay_path=replay_path) if mode is None: raise RuntimeError("Please indicate at least one argument.") if isinstance(seed, (list, tuple)): assert len(seed) > 0, "Please input at least 1 seed" if len(seed) == 1: # necessary run_single_pipeline(seed[0], config) else: if exp_name is None: multi_exp_root = os.path.basename(config).split('.')[0] + '_result' else: multi_exp_root = exp_name if not os.path.exists(multi_exp_root): os.makedirs(multi_exp_root) abs_config_path = os.path.abspath(config) origin_root = os.getcwd() for s in seed: seed_exp_root = os.path.join(multi_exp_root, 'seed{}'.format(s)) if not os.path.exists(seed_exp_root): os.makedirs(seed_exp_root) os.chdir(seed_exp_root) run_single_pipeline(s, abs_config_path) os.chdir(origin_root) else: raise TypeError("invalid seed type: {}".format(type(seed)))
PypiClean
/Kr0nOs_Bot-3.3.11-py3-none-any.whl/redbot/core/utils/common_filters.py
import re __all__ = [ "URL_RE", "INVITE_URL_RE", "MASS_MENTION_RE", "filter_urls", "filter_invites", "filter_mass_mentions", "filter_various_mentions", "normalize_smartquotes", "escape_spoilers", "escape_spoilers_and_mass_mentions", ] # regexes URL_RE = re.compile(r"(https?|s?ftp)://(\S+)", re.I) INVITE_URL_RE = re.compile(r"(discord\.(?:gg|io|me|li)|discordapp\.com\/invite)\/(\S+)", re.I) MASS_MENTION_RE = re.compile(r"(@)(?=everyone|here)") # This only matches the @ for sanitizing OTHER_MENTION_RE = re.compile(r"(<)(@[!&]?|#)(\d+>)") SMART_QUOTE_REPLACEMENT_DICT = { "\u2018": "'", # Left single quote "\u2019": "'", # Right single quote "\u201C": '"', # Left double quote "\u201D": '"', # Right double quote } SMART_QUOTE_REPLACE_RE = re.compile("|".join(SMART_QUOTE_REPLACEMENT_DICT.keys())) SPOILER_CONTENT_RE = re.compile( r"(?s)(?<!\\)(?P<OPEN>\|{2})(?P<SPOILERED>.*?)(?<!\\)(?P<CLOSE>\|{2})" ) # convenience wrappers def filter_urls(to_filter: str) -> str: """Get a string with URLs sanitized. This will match any URLs starting with these protocols: - ``http://`` - ``https://`` - ``ftp://`` - ``sftp://`` Parameters ---------- to_filter : str The string to filter. Returns ------- str The sanitized string. """ return URL_RE.sub("[SANITIZED URL]", to_filter) def filter_invites(to_filter: str) -> str: """Get a string with discord invites sanitized. Will match any discord.gg, discordapp.com/invite, discord.me, or discord.io/discord.li invite URL. Parameters ---------- to_filter : str The string to filter. Returns ------- str The sanitized string. """ return INVITE_URL_RE.sub("[SANITIZED INVITE]", to_filter) def filter_mass_mentions(to_filter: str) -> str: """Get a string with mass mentions sanitized. Will match any *here* and/or *everyone* mentions. Parameters ---------- to_filter : str The string to filter. Returns ------- str The sanitized string. """ return MASS_MENTION_RE.sub("@\u200b", to_filter) def filter_various_mentions(to_filter: str) -> str: """ Get a string with role, user, and channel mentions sanitized. This is mainly for use on user display names, not message content, and should be applied sparingly. Parameters ---------- to_filter : str The string to filter. Returns ------- str The sanitized string. """ return OTHER_MENTION_RE.sub(r"\1\\\2\3", to_filter) def normalize_smartquotes(to_normalize: str) -> str: """ Get a string with smart quotes replaced with normal ones Parameters ---------- to_normalize : str The string to normalize. Returns ------- str The normalized string. """ def replacement_for(obj): return SMART_QUOTE_REPLACEMENT_DICT.get(obj.group(0), "") return SMART_QUOTE_REPLACE_RE.sub(replacement_for, to_normalize) def escape_spoilers(content: str) -> str: """ Get a string with spoiler syntax escaped. Parameters ---------- content : str The string to escape. Returns ------- str The escaped string. """ return SPOILER_CONTENT_RE.sub(r"\\\g<OPEN>\g<SPOILERED>\\\g<CLOSE>", content) def escape_spoilers_and_mass_mentions(content: str) -> str: """ Get a string with spoiler syntax and mass mentions escaped Parameters ---------- content : str The string to escape. Returns ------- str The escaped string. """ return escape_spoilers(filter_mass_mentions(content))
PypiClean
/BobBuildTool-0.23.1.tar.gz/BobBuildTool-0.23.1/pym/bob/cmds/misc.py
# Bob build tool # Copyright (C) 2016 TechniSat Digital GmbH # # SPDX-License-Identifier: GPL-3.0-or-later from ..input import RecipeSet from ..errors import ParseError, BuildError from ..utils import processDefines import argparse import codecs import sys import os, os.path try: # test if stdout can handle box drawing characters codecs.encode("└├│─", sys.stdout.encoding) LS_SEP_1 = u"└── " LS_SEP_2 = u"├── " LS_SEP_3 = u" " LS_SEP_4 = u"│   " except UnicodeEncodeError: # fall back to ASCII LS_SEP_1 = "\\-- " LS_SEP_2 = "|-- " LS_SEP_3 = " " LS_SEP_4 = "| " class PackagePrinter: def __init__(self, showAll, showOrigin, recurse, unsorted): self.showAll = showAll self.showOrigin = showOrigin self.recurse = recurse if unsorted: self.sort = lambda x: x else: self.sort = sorted def __getChilds(self, package): return [ (name, child.node, " ({})".format(child.origin) if (self.showOrigin and child.origin) else "") for (name, child) in self.sort(package.items()) if (self.showAll or child.direct) ] def showTree(self, package, prefix=""): i = 0 packages = self.__getChilds(package) for (n, p, o) in packages: last = (i >= len(packages)-1) print("{}{}{}{}".format(prefix, LS_SEP_1 if last else LS_SEP_2, n, o)) self.showTree(p, prefix + (LS_SEP_3 if last else LS_SEP_4)) i += 1 def showPrefixed(self, package, showAliases, stack=[], level=0): for p in showAliases: print(p) for (n, p, o) in self.__getChilds(package): newStack = stack[:] newStack.append(n) print("{}{}".format("/".join(newStack), o)) if self.recurse: self.showPrefixed(p, [], newStack, level+1) def doLS(argv, bobRoot): parser = argparse.ArgumentParser(prog="bob ls", description='List packages.') parser.add_argument('package', type=str, nargs='?', default="", help="Sub-package to start listing from") parser.add_argument('-a', '--all', default=False, action='store_true', help="Show indirect dependencies too") parser.add_argument('-A', '--alternates', default=False, action='store_true', help="Show all alternate paths to identical packages too") parser.add_argument('-o', '--origin', default=False, action='store_true', help="Show origin of indirect dependencies") parser.add_argument('-r', '--recursive', default=False, action='store_true', help="Recursively display dependencies") parser.add_argument('-u', '--unsorted', default=False, action='store_true', help="Show packages in recipe order (unsorted)") group = parser.add_mutually_exclusive_group() group.add_argument('-p', '--prefixed', default=False, action='store_true', help="Prints the full path prefix for each package") group.add_argument('-d', '--direct', default=False, action='store_true', help="List packages themselves, not their contents") parser.add_argument('-D', default=[], action='append', dest="defines", help="Override default environment variable") parser.add_argument('-c', dest="configFile", default=[], action='append', help="Use config File") group = parser.add_mutually_exclusive_group() group.add_argument('--sandbox', action='store_true', default=False, help="Enable sandboxing") group.add_argument('--no-sandbox', action='store_false', dest='sandbox', help="Disable sandboxing") args = parser.parse_args(argv) defines = processDefines(args.defines) recipes = RecipeSet() recipes.setConfigFiles(args.configFile) recipes.parse(defines) packages = recipes.generatePackages(lambda s,m: "unused", args.sandbox) showAliases = packages.getAliases() if args.package == "" else [] printer = PackagePrinter(args.all, args.origin, args.recursive, args.unsorted) showAlternates = args.alternates and (args.prefixed or args.direct) for (stack, root) in packages.queryTreePath(args.package, showAlternates): if args.prefixed: printer.showPrefixed(root, showAliases, stack) elif args.direct: print("/".join(stack) if stack else "/") elif args.recursive: print("/".join(stack) if stack else "/") printer.showTree(root) else: printer.showPrefixed(root, showAliases) class Default(dict): def __init__(self, default, *args, **kwargs): self.__default = default super().__init__(*args, **kwargs) def __missing__(self, key): return self.__default def doQueryMeta(argv, bobRoot): parser = argparse.ArgumentParser(prog="bob query-meta", formatter_class=argparse.RawDescriptionHelpFormatter, description="""Query meta information of packages.""") parser.add_argument('packages', nargs='+', help="(Sub-)packages to query") parser.add_argument('-D', default=[], action='append', dest="defines", help="Override default environment variable") parser.add_argument('-c', dest="configFile", default=[], action='append', help="Use config File") parser.add_argument('-r', '--recursive', default=False, action='store_true', help="Recursively display dependencies") group = parser.add_mutually_exclusive_group() group.add_argument('--sandbox', action='store_true', default=False, help="Enable sandboxing") group.add_argument('--no-sandbox', action='store_false', dest='sandbox', help="Disable sandboxing") args = parser.parse_args(argv) defines = processDefines(args.defines) recipes = RecipeSet() recipes.setConfigFiles(args.configFile) recipes.parse(defines) packages = recipes.generatePackages(lambda s,m: "unused", args.sandbox) def showPackage(package, recurse, done): # Show each package only once. Meta variables are fixed and not variant # dependent. key = package.getName() if key not in done: for (var, val) in package.getMetaEnv().items(): print(package.getName() + " " + var + "=" + val) done.add(key) # recurse package tree if requested if recurse: for ps in package.getDirectDepSteps(): showPackage(ps.getPackage(), recurse, done) done = set() for p in args.packages: for package in packages.queryPackagePath(p): showPackage(package, args.recursive, done) def doQuerySCM(argv, bobRoot): parser = argparse.ArgumentParser(prog="bob query-scm", formatter_class=argparse.RawDescriptionHelpFormatter, description="""Query SCM configuration of packages. By default this command will print one line for each SCM in the given package. The output format may be overridded by '-f'. By default the following formats are used: * git="git {package} {dir} {url} {branch}" * svn="svn {package} {dir} {url} {revision}" * cvs="cvs {package} {dir} {cvsroot} {module}" * url="url {package} {dir}/{fileName} {url}" """) parser.add_argument('packages', nargs='+', help="(Sub-)packages to query") parser.add_argument('-D', default=[], action='append', dest="defines", help="Override default environment variable") parser.add_argument('-c', dest="configFile", default=[], action='append', help="Use config File") parser.add_argument('-f', default=[], action='append', dest="formats", help="Output format for scm (syntax: scm=format). Can be specified multiple times.") parser.add_argument('--default', default="", help='Default for missing attributes (default: "")') parser.add_argument('-r', '--recursive', default=False, action='store_true', help="Recursively display dependencies") group = parser.add_mutually_exclusive_group() group.add_argument('--sandbox', action='store_true', default=False, help="Enable sandboxing") group.add_argument('--no-sandbox', action='store_false', dest='sandbox', help="Disable sandboxing") formats = { 'git' : "git {package} {dir} {url} {branch}", 'svn' : "svn {package} {dir} {url} {revision}", 'cvs' : "cvs {package} {dir} {cvsroot} {module}", 'url' : "url {package} {dir}/{fileName} {url}", } args = parser.parse_args(argv) defines = processDefines(args.defines) recipes = RecipeSet() recipes.setConfigFiles(args.configFile) recipes.parse(defines) packages = recipes.generatePackages(lambda s,m: "unused", args.sandbox) # update formats for fmt in args.formats: f = fmt.split("=") if len(f) != 2: parser.error("Malformed format: "+fmt) formats[f[0]] = f[1] def showPackage(package, recurse, done, donePackages): if package._getId() in donePackages: return donePackages.add(package._getId()) # show recipes only once for each checkout variant key = (package.getRecipe().getName(), package.getCheckoutStep().getVariantId()) if key not in done: for scm in package.getCheckoutStep().getScmList(): p = { k:v for (k,v) in scm.getProperties(False).items() if v is not None } p['package'] = "/".join(package.getStack()) fmt = formats.get(p['scm'], "{scm} {dir}") print(fmt.format_map(Default(args.default, p))) done.add(key) # recurse package tree if requested if recurse: for ps in package.getDirectDepSteps(): showPackage(ps.getPackage(), recurse, done, donePackages) done = set() donePackages = set() for p in args.packages: for package in packages.queryPackagePath(p): showPackage(package, args.recursive, done, donePackages) def doQueryRecipe(argv, bobRoot): parser = argparse.ArgumentParser(prog="bob query-recipe", description="Query recipe and class files of package.") parser.add_argument('package', help="(Sub-)package to query") parser.add_argument('-D', default=[], action='append', dest="defines", help="Override default environment variable") parser.add_argument('-c', dest="configFile", default=[], action='append', help="Use config File") group = parser.add_mutually_exclusive_group() group.add_argument('--sandbox', action='store_true', default=False, help="Enable sandboxing") group.add_argument('--no-sandbox', action='store_false', dest='sandbox', help="Disable sandboxing") args = parser.parse_args(argv) defines = processDefines(args.defines) recipes = RecipeSet() recipes.setConfigFiles(args.configFile) recipes.parse(defines) package = recipes.generatePackages(lambda s,m: "unused", args.sandbox).walkPackagePath(args.package) for fn in package.getRecipe().getSources(): print(fn) def doInit(argv, bobRoot): parser = argparse.ArgumentParser(prog="bob init", formatter_class=argparse.RawDescriptionHelpFormatter, description="""Initialize out-of-source build tree. Create a Bob build tree in the current directory or at the given BUILD directory. The recipes, classes, plugins and all other files are taken from the project root directory at PROJECT. """) parser.add_argument('project', metavar="PROJECT", help="Project root directory") parser.add_argument('build', nargs='?', metavar="BUILD", default=".", help="Build directory (default: .)") args = parser.parse_args(argv) recipesDir = os.path.join(args.project, "recipes") if not os.path.isdir(recipesDir): raise ParseError("No recipes directory found in " + recipesDir) try: os.makedirs(args.build, exist_ok=True) if os.path.samefile(args.project, args.build): print("The project directory does not need to be initialized.", file=sys.stderr) return except OSError as e: raise ParseError("Error creating build directory: " + str(e)) projectLink = os.path.join(args.build, ".bob-project") if os.path.exists(projectLink): raise ParseError("Build tree already initialized!") try: with open(projectLink, "w") as f: f.write(os.path.abspath(args.project)) except OSError as e: raise ParseError("Cannot create project link: " + str(e))
PypiClean
/ContactMechanics-1.1.1.tar.gz/ContactMechanics-1.1.1/LICENSE.md
### MIT license Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
PypiClean
/DecisionTree-3.4.3.tar.gz/DecisionTree-3.4.3/Examples/construct_dt_and_classify_one_sample_case3.py
## construct_dt_and_classify_one_sample_case3.py ## This script does the same thing as the script ## ## construct_dt_and_classify_one_sample_case2.py ## ## except that it uses just two of the columns of the csv file for DT construction ## and classification. The two features used are in columns indexed 3 and 5 of the ## csv file. ## Remember that column indexing is zero-based in the csv file. ## The training file `stage3cancer.csv' was taken from the RPART module by Terry ## Therneau and Elizabeth Atkinson. This module is a part of the R based ## statistical package for classification and regression by recursive partitioning ## of data. import DecisionTree import sys training_datafile = "stage3cancer.csv" dt = DecisionTree.DecisionTree( training_datafile = training_datafile, csv_class_column_index = 2, csv_columns_for_features = [3,5], entropy_threshold = 0.01, max_depth_desired = 4, symbolic_to_numeric_cardinality_threshold = 10, csv_cleanup_needed = 1, ) dt.get_training_data() dt.calculate_first_order_probabilities() dt.calculate_class_priors() # UNCOMMENT THE FOLLOWING LINE if you would like to see the training # data that was read from the disk file: #dt.show_training_data() root_node = dt.construct_decision_tree_classifier() # UNCOMMENT THE FOLLOWING LINE if you would like to see the decision # tree displayed in your terminal window: print("\n\nThe Decision Tree:\n") root_node.display_decision_tree(" ") test_sample = ['g2 = 20', 'age = 80.0'] # The rest of the script is for displaying the classification results: classification = dt.classify(root_node, test_sample) solution_path = classification['solution_path'] del classification['solution_path'] which_classes = list( classification.keys() ) which_classes = sorted(which_classes, key=lambda x: classification[x], reverse=True) print("\nClassification:\n") print(" " + str.ljust("class name", 30) + "probability") print(" ---------- -----------") for which_class in which_classes: if which_class is not 'solution_path': print(" " + str.ljust(which_class, 30) + str(classification[which_class])) print("\nSolution path in the decision tree: " + str(solution_path)) print("\nNumber of nodes created: " + str(root_node.how_many_nodes()))
PypiClean
/Euphorie-15.0.2.tar.gz/Euphorie-15.0.2/src/euphorie/client/resources/oira/script/chunks/12391.8a087770c620986d769d.min.js
"use strict";(self.webpackChunk_patternslib_patternslib=self.webpackChunk_patternslib_patternslib||[]).push([[12391],{64505:function(n,e,t){var o=t(87537),r=t.n(o),s=t(23645),a=t.n(s)()(r());a.push([n.id,".hljs-comment,.hljs-quote{color:#6c6b5a}.hljs-variable,.hljs-template-variable,.hljs-attribute,.hljs-tag,.hljs-name,.hljs-regexp,.hljs-link,.hljs-name,.hljs-selector-id,.hljs-selector-class{color:#ba6236}.hljs-number,.hljs-meta,.hljs-built_in,.hljs-builtin-name,.hljs-literal,.hljs-type,.hljs-params{color:#ae7313}.hljs-string,.hljs-symbol,.hljs-bullet{color:#7d9726}.hljs-title,.hljs-section{color:#36a166}.hljs-keyword,.hljs-selector-tag{color:#5f9182}.hljs-deletion,.hljs-addition{color:#22221b;display:inline-block;width:100%}.hljs-deletion{background-color:#ba6236}.hljs-addition{background-color:#7d9726}.hljs{display:block;overflow-x:auto;background:#f4f3ec;color:#5f5e4e;padding:.5em}.hljs-emphasis{font-style:italic}.hljs-strong{font-weight:bold}","",{version:3,sources:["webpack://./node_modules/highlight.js/styles/atelier-estuary-light.css"],names:[],mappings:"AAKA,0BAEE,aAAA,CAIF,sJAUE,aAAA,CAIF,gGAOE,aAAA,CAIF,uCAGE,aAAA,CAIF,0BAEE,aAAA,CAIF,iCAEE,aAAA,CAGF,8BAEE,aAAA,CACA,oBAAA,CACA,UAAA,CAGF,eACE,wBAAA,CAGF,eACE,wBAAA,CAGF,MACE,aAAA,CACA,eAAA,CACA,kBAAA,CACA,aAAA,CACA,YAAA,CAGF,eACE,iBAAA,CAGF,aACE,gBAAA",sourcesContent:["/* Base16 Atelier Estuary Light - Theme */\n/* by Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/estuary) */\n/* Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */\n\n/* Atelier-Estuary Comment */\n.hljs-comment,\n.hljs-quote {\n color: #6c6b5a;\n}\n\n/* Atelier-Estuary Red */\n.hljs-variable,\n.hljs-template-variable,\n.hljs-attribute,\n.hljs-tag,\n.hljs-name,\n.hljs-regexp,\n.hljs-link,\n.hljs-name,\n.hljs-selector-id,\n.hljs-selector-class {\n color: #ba6236;\n}\n\n/* Atelier-Estuary Orange */\n.hljs-number,\n.hljs-meta,\n.hljs-built_in,\n.hljs-builtin-name,\n.hljs-literal,\n.hljs-type,\n.hljs-params {\n color: #ae7313;\n}\n\n/* Atelier-Estuary Green */\n.hljs-string,\n.hljs-symbol,\n.hljs-bullet {\n color: #7d9726;\n}\n\n/* Atelier-Estuary Blue */\n.hljs-title,\n.hljs-section {\n color: #36a166;\n}\n\n/* Atelier-Estuary Purple */\n.hljs-keyword,\n.hljs-selector-tag {\n color: #5f9182;\n}\n\n.hljs-deletion,\n.hljs-addition {\n color: #22221b;\n display: inline-block;\n width: 100%;\n}\n\n.hljs-deletion {\n background-color: #ba6236;\n}\n\n.hljs-addition {\n background-color: #7d9726;\n}\n\n.hljs {\n display: block;\n overflow-x: auto;\n background: #f4f3ec;\n color: #5f5e4e;\n padding: 0.5em;\n}\n\n.hljs-emphasis {\n font-style: italic;\n}\n\n.hljs-strong {\n font-weight: bold;\n}\n"],sourceRoot:""}]),e.Z=a},23645:function(n){n.exports=function(n){var e=[];return e.toString=function(){return this.map((function(e){var t="",o=void 0!==e[5];return e[4]&&(t+="@supports (".concat(e[4],") {")),e[2]&&(t+="@media ".concat(e[2]," {")),o&&(t+="@layer".concat(e[5].length>0?" ".concat(e[5]):""," {")),t+=n(e),o&&(t+="}"),e[2]&&(t+="}"),e[4]&&(t+="}"),t})).join("")},e.i=function(n,t,o,r,s){"string"==typeof n&&(n=[[null,n,void 0]]);var a={};if(o)for(var l=0;l<this.length;l++){var i=this[l][0];null!=i&&(a[i]=!0)}for(var c=0;c<n.length;c++){var u=[].concat(n[c]);o&&a[u[0]]||(void 0!==s&&(void 0===u[5]||(u[1]="@layer".concat(u[5].length>0?" ".concat(u[5]):""," {").concat(u[1],"}")),u[5]=s),t&&(u[2]?(u[1]="@media ".concat(u[2]," {").concat(u[1],"}"),u[2]=t):u[2]=t),r&&(u[4]?(u[1]="@supports (".concat(u[4],") {").concat(u[1],"}"),u[4]=r):u[4]="".concat(r)),e.push(u))}},e}},87537:function(n){n.exports=function(n){var e=n[1],t=n[3];if(!t)return e;if("function"==typeof btoa){var o=btoa(unescape(encodeURIComponent(JSON.stringify(t)))),r="sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(o),s="/*# ".concat(r," */");return[e].concat([s]).join("\n")}return[e].join("\n")}},12391:function(n,e,t){t.r(e);var o=t(93379),r=t.n(o),s=t(7795),a=t.n(s),l=t(3565),i=t.n(l),c=t(19216),u=t.n(c),h=t(44589),A=t.n(h),d=t(64505),p={};p.styleTagTransform=A(),p.setAttributes=i(),p.insert=function(n){var e=document.head.querySelectorAll("*")[0];e?document.head.insertBefore(n,e):document.head.append(n)},p.domAPI=a(),p.insertStyleElement=u();r()(d.Z,p);e.default=d.Z&&d.Z.locals?d.Z.locals:void 0},93379:function(n){var e=[];function t(n){for(var t=-1,o=0;o<e.length;o++)if(e[o].identifier===n){t=o;break}return t}function o(n,o){for(var s={},a=[],l=0;l<n.length;l++){var i=n[l],c=o.base?i[0]+o.base:i[0],u=s[c]||0,h="".concat(c," ").concat(u);s[c]=u+1;var A=t(h),d={css:i[1],media:i[2],sourceMap:i[3],supports:i[4],layer:i[5]};if(-1!==A)e[A].references++,e[A].updater(d);else{var p=r(d,o);o.byIndex=l,e.splice(l,0,{identifier:h,updater:p,references:1})}a.push(h)}return a}function r(n,e){var t=e.domAPI(e);t.update(n);return function(e){if(e){if(e.css===n.css&&e.media===n.media&&e.sourceMap===n.sourceMap&&e.supports===n.supports&&e.layer===n.layer)return;t.update(n=e)}else t.remove()}}n.exports=function(n,r){var s=o(n=n||[],r=r||{});return function(n){n=n||[];for(var a=0;a<s.length;a++){var l=t(s[a]);e[l].references--}for(var i=o(n,r),c=0;c<s.length;c++){var u=t(s[c]);0===e[u].references&&(e[u].updater(),e.splice(u,1))}s=i}}},19216:function(n){n.exports=function(n){var e=document.createElement("style");return n.setAttributes(e,n.attributes),n.insert(e,n.options),e}},3565:function(n,e,t){n.exports=function(n){var e=t.nc;e&&n.setAttribute("nonce",e)}},7795:function(n){n.exports=function(n){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var e=n.insertStyleElement(n);return{update:function(t){!function(n,e,t){var o="";t.supports&&(o+="@supports (".concat(t.supports,") {")),t.media&&(o+="@media ".concat(t.media," {"));var r=void 0!==t.layer;r&&(o+="@layer".concat(t.layer.length>0?" ".concat(t.layer):""," {")),o+=t.css,r&&(o+="}"),t.media&&(o+="}"),t.supports&&(o+="}");var s=t.sourceMap;s&&"undefined"!=typeof btoa&&(o+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(s))))," */")),e.styleTagTransform(o,n,e.options)}(e,n,t)},remove:function(){!function(n){if(null===n.parentNode)return!1;n.parentNode.removeChild(n)}(e)}}}},44589:function(n){n.exports=function(n,e){if(e.styleSheet)e.styleSheet.cssText=n;else{for(;e.firstChild;)e.removeChild(e.firstChild);e.appendChild(document.createTextNode(n))}}}}]); //# sourceMappingURL=12391.8a087770c620986d769d.min.js.map
PypiClean
/AyiinXd-0.0.8-cp311-cp311-macosx_10_9_universal2.whl/fipper/node_modules/semver/ranges/subset.js
const Range = require('../classes/range.js') const Comparator = require('../classes/comparator.js') const { ANY } = Comparator const satisfies = require('../functions/satisfies.js') const compare = require('../functions/compare.js') // Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: // - Every simple range `r1, r2, ...` is a null set, OR // - Every simple range `r1, r2, ...` which is not a null set is a subset of // some `R1, R2, ...` // // Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: // - If c is only the ANY comparator // - If C is only the ANY comparator, return true // - Else if in prerelease mode, return false // - else replace c with `[>=0.0.0]` // - If C is only the ANY comparator // - if in prerelease mode, return true // - else replace C with `[>=0.0.0]` // - Let EQ be the set of = comparators in c // - If EQ is more than one, return true (null set) // - Let GT be the highest > or >= comparator in c // - Let LT be the lowest < or <= comparator in c // - If GT and LT, and GT.semver > LT.semver, return true (null set) // - If any C is a = range, and GT or LT are set, return false // - If EQ // - If GT, and EQ does not satisfy GT, return true (null set) // - If LT, and EQ does not satisfy LT, return true (null set) // - If EQ satisfies every C, return true // - Else return false // - If GT // - If GT.semver is lower than any > or >= comp in C, return false // - If GT is >=, and GT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the GT.semver tuple, return false // - If LT // - If LT.semver is greater than any < or <= comp in C, return false // - If LT is <=, and LT.semver does not satisfy every C, return false // - If GT.semver has a prerelease, and not in prerelease mode // - If no C has a prerelease and the LT.semver tuple, return false // - Else return true const subset = (sub, dom, options = {}) => { if (sub === dom) { return true } sub = new Range(sub, options) dom = new Range(dom, options) let sawNonNull = false OUTER: for (const simpleSub of sub.set) { for (const simpleDom of dom.set) { const isSub = simpleSubset(simpleSub, simpleDom, options) sawNonNull = sawNonNull || isSub !== null if (isSub) { continue OUTER } } // the null set is a subset of everything, but null simple ranges in // a complex range should be ignored. so if we saw a non-null range, // then we know this isn't a subset, but if EVERY simple range was null, // then it is a subset. if (sawNonNull) { return false } } return true } const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] const minimumVersion = [new Comparator('>=0.0.0')] const simpleSubset = (sub, dom, options) => { if (sub === dom) { return true } if (sub.length === 1 && sub[0].semver === ANY) { if (dom.length === 1 && dom[0].semver === ANY) { return true } else if (options.includePrerelease) { sub = minimumVersionWithPreRelease } else { sub = minimumVersion } } if (dom.length === 1 && dom[0].semver === ANY) { if (options.includePrerelease) { return true } else { dom = minimumVersion } } const eqSet = new Set() let gt, lt for (const c of sub) { if (c.operator === '>' || c.operator === '>=') { gt = higherGT(gt, c, options) } else if (c.operator === '<' || c.operator === '<=') { lt = lowerLT(lt, c, options) } else { eqSet.add(c.semver) } } if (eqSet.size > 1) { return null } let gtltComp if (gt && lt) { gtltComp = compare(gt.semver, lt.semver, options) if (gtltComp > 0) { return null } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { return null } } // will iterate one or zero times for (const eq of eqSet) { if (gt && !satisfies(eq, String(gt), options)) { return null } if (lt && !satisfies(eq, String(lt), options)) { return null } for (const c of dom) { if (!satisfies(eq, String(c), options)) { return false } } return true } let higher, lower let hasDomLT, hasDomGT // if the subset has a prerelease, we need a comparator in the superset // with the same tuple and a prerelease, or it's not a subset let needDomLTPre = lt && !options.includePrerelease && lt.semver.prerelease.length ? lt.semver : false let needDomGTPre = gt && !options.includePrerelease && gt.semver.prerelease.length ? gt.semver : false // exception: <1.2.3-0 is the same as <1.2.3 if (needDomLTPre && needDomLTPre.prerelease.length === 1 && lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { needDomLTPre = false } for (const c of dom) { hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' if (gt) { if (needDomGTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomGTPre.major && c.semver.minor === needDomGTPre.minor && c.semver.patch === needDomGTPre.patch) { needDomGTPre = false } } if (c.operator === '>' || c.operator === '>=') { higher = higherGT(gt, c, options) if (higher === c && higher !== gt) { return false } } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { return false } } if (lt) { if (needDomLTPre) { if (c.semver.prerelease && c.semver.prerelease.length && c.semver.major === needDomLTPre.major && c.semver.minor === needDomLTPre.minor && c.semver.patch === needDomLTPre.patch) { needDomLTPre = false } } if (c.operator === '<' || c.operator === '<=') { lower = lowerLT(lt, c, options) if (lower === c && lower !== lt) { return false } } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { return false } } if (!c.operator && (lt || gt) && gtltComp !== 0) { return false } } // if there was a < or >, and nothing in the dom, then must be false // UNLESS it was limited by another range in the other direction. // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 if (gt && hasDomLT && !lt && gtltComp !== 0) { return false } if (lt && hasDomGT && !gt && gtltComp !== 0) { return false } // we needed a prerelease range in a specific tuple, but didn't get one // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, // because it includes prereleases in the 1.2.3 tuple if (needDomGTPre || needDomLTPre) { return false } return true } // >=1.2.3 is lower than >1.2.3 const higherGT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp > 0 ? a : comp < 0 ? b : b.operator === '>' && a.operator === '>=' ? b : a } // <=1.2.3 is higher than <1.2.3 const lowerLT = (a, b, options) => { if (!a) { return b } const comp = compare(a.semver, b.semver, options) return comp < 0 ? a : comp > 0 ? b : b.operator === '<' && a.operator === '<=' ? b : a } module.exports = subset
PypiClean
/MetaCSV-0.1.1.tar.gz/MetaCSV-0.1.1/metacsv/io/to_xarray.py
import pandas as pd import numpy as np from collections import OrderedDict from .._compat import string_types from .yaml_tools import ordered_dump xr = None def _import_xarray(): global xr if xr is None: import xarray as xr def _check_series_unique(series): def check_unique(group): try: name = group.name if isinstance(group.name, string_types) else ','.join(group.name) except TypeError: name = group.name msg = "Data not uniquely indexed for base coords: ({})".format(name) if len(group.drop_duplicates()) != 1: raise ValueError(msg) if len(series.index.names) > 1: series.groupby(level=series.index.names).apply(check_unique) else: series.groupby(by=series.index).apply(check_unique) def _append_coords_to_dataset(ds, container, base_only, attrs=None): global xr if xr is None: _import_xarray() if container.coords == None: container.add_coords() for coord in container.base_coords: ds.coords[str(coord)] = container.index.get_level_values( coord).unique() ds.coords[str(coord)].attrs = container.variables.get(coord, {}) for coord in container.coords: if coord in container.base_coords: continue data = base_only[coord] if len(data.index.names) > len(container.coords._base_dependencies[coord]): data.reset_index([c for c in data.index.names if c not in container.coords._base_dependencies[ coord]], inplace=True, drop=True) ds.coords[str(coord)] = metacsv_series_to_dataarray( data, attrs=container.variables.get(coord, {})) def metacsv_series_to_dataarray(series, attrs=None): global xr if xr is None: _import_xarray() if attrs is None: attrs = series.attrs if series.base_coords != None: reset = [c for c in series.index.names if c not in series.base_coords] if len(reset) > 0: series = series.reset_index(reset, drop=True) _check_series_unique(series) series = series.iloc[np.unique(series.index.values, return_index=True)[1]] series.index.names = list(map(str, series.index.names)) da = xr.DataArray.from_series(series) da.attrs = attrs return da def metacsv_series_to_dataset(series, name='data', attrs=None): global xr if xr is None: _import_xarray() ds = xr.Dataset() if attrs is None: attrs = series.attrs reset = [c for c in series.coords if c not in series.base_coords] if len(reset) > 0: base_only = series.reset_index(reset, drop=False) else: base_only = series _check_series_unique(base_only) _append_coords_to_dataset(ds, series, base_only, attrs) if len(reset) > 0: data = series.reset_index(reset, drop=True) else: data = series ds[name] = xr.DataArray.from_series(data) ds[name].attrs = series.variables.get(name, {}) ds.attrs = series.attrs return ds def metacsv_dataframe_to_dataset(dataframe, name='data', attrs=None): global xr if xr is None: _import_xarray() ds = xr.Dataset() if attrs is None: attrs = dataframe.attrs reset = [c for c in dataframe.coords if c not in dataframe.base_coords] if len(reset) > 0: base_only = dataframe.reset_index(reset, drop=False, inplace=False) else: base_only = dataframe _check_series_unique(base_only) _append_coords_to_dataset(ds, dataframe, base_only, attrs) if len(reset) > 0: data = dataframe.reset_index(reset, drop=True) else: data = dataframe for col in dataframe.columns: ds[col] = xr.DataArray.from_series(data[col]) ds[col].attrs = dataframe.variables.get(col, {}) ds.attrs = dataframe.attrs return ds def metacsv_dataframe_to_dataarray(dataframe, names=None, attrs=None): global xr if xr is None: _import_xarray() dataframe = dataframe.copy() if attrs is None: attrs = dataframe.attrs coords = dataframe.coords.copy() dataframe.index.names = [ str(ind) if not pd.isnull(ind) else 'ind_{}'.format(i) for i, ind in enumerate(dataframe.index.names)] if dataframe.coords == None: coords.update({c: None for c in dataframe.index.names}) dataframe.columns.names = [ str(c) if not pd.isnull(c) else 'coldim_{}'.format(i) for i, c in enumerate(dataframe.columns.names)] colnames = dataframe.columns.names series = dataframe._constructor_sliced(dataframe.stack(colnames)) coords.update({c: None for c in colnames}) series.coords.update(coords) return metacsv_series_to_dataarray(series, attrs=attrs)
PypiClean
/Netfoll_TL-2.0.1-py3-none-any.whl/netfoll_tl/tl/functions/upload.py
from ...tl.tlobject import TLObject from ...tl.tlobject import TLRequest from typing import Optional, List, Union, TYPE_CHECKING import os import struct from datetime import datetime if TYPE_CHECKING: from ...tl.types import TypeInputFileLocation, TypeInputWebFileLocation class GetCdnFileRequest(TLRequest): CONSTRUCTOR_ID = 0x395f69da SUBCLASS_OF_ID = 0xf5ccf928 def __init__(self, file_token: bytes, offset: int, limit: int): """ :returns upload.CdnFile: Instance of either CdnFileReuploadNeeded, CdnFile. """ self.file_token = file_token self.offset = offset self.limit = limit def to_dict(self): return { '_': 'GetCdnFileRequest', 'file_token': self.file_token, 'offset': self.offset, 'limit': self.limit } def _bytes(self): return b''.join(( b'\xdai_9', self.serialize_bytes(self.file_token), struct.pack('<q', self.offset), struct.pack('<i', self.limit), )) @classmethod def from_reader(cls, reader): _file_token = reader.tgread_bytes() _offset = reader.read_long() _limit = reader.read_int() return cls(file_token=_file_token, offset=_offset, limit=_limit) class GetCdnFileHashesRequest(TLRequest): CONSTRUCTOR_ID = 0x91dc3f31 SUBCLASS_OF_ID = 0xa5940726 def __init__(self, file_token: bytes, offset: int): """ :returns Vector<FileHash>: This type has no constructors. """ self.file_token = file_token self.offset = offset def to_dict(self): return { '_': 'GetCdnFileHashesRequest', 'file_token': self.file_token, 'offset': self.offset } def _bytes(self): return b''.join(( b'1?\xdc\x91', self.serialize_bytes(self.file_token), struct.pack('<q', self.offset), )) @classmethod def from_reader(cls, reader): _file_token = reader.tgread_bytes() _offset = reader.read_long() return cls(file_token=_file_token, offset=_offset) class GetFileRequest(TLRequest): CONSTRUCTOR_ID = 0xbe5335be SUBCLASS_OF_ID = 0x6c9bd728 def __init__(self, location: 'TypeInputFileLocation', offset: int, limit: int, precise: Optional[bool]=None, cdn_supported: Optional[bool]=None): """ :returns upload.File: Instance of either File, FileCdnRedirect. """ self.location = location self.offset = offset self.limit = limit self.precise = precise self.cdn_supported = cdn_supported def to_dict(self): return { '_': 'GetFileRequest', 'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location, 'offset': self.offset, 'limit': self.limit, 'precise': self.precise, 'cdn_supported': self.cdn_supported } def _bytes(self): return b''.join(( b'\xbe5S\xbe', struct.pack('<I', (0 if self.precise is None or self.precise is False else 1) | (0 if self.cdn_supported is None or self.cdn_supported is False else 2)), self.location._bytes(), struct.pack('<q', self.offset), struct.pack('<i', self.limit), )) @classmethod def from_reader(cls, reader): flags = reader.read_int() _precise = bool(flags & 1) _cdn_supported = bool(flags & 2) _location = reader.tgread_object() _offset = reader.read_long() _limit = reader.read_int() return cls(location=_location, offset=_offset, limit=_limit, precise=_precise, cdn_supported=_cdn_supported) class GetFileHashesRequest(TLRequest): CONSTRUCTOR_ID = 0x9156982a SUBCLASS_OF_ID = 0xa5940726 def __init__(self, location: 'TypeInputFileLocation', offset: int): """ :returns Vector<FileHash>: This type has no constructors. """ self.location = location self.offset = offset def to_dict(self): return { '_': 'GetFileHashesRequest', 'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location, 'offset': self.offset } def _bytes(self): return b''.join(( b'*\x98V\x91', self.location._bytes(), struct.pack('<q', self.offset), )) @classmethod def from_reader(cls, reader): _location = reader.tgread_object() _offset = reader.read_long() return cls(location=_location, offset=_offset) class GetWebFileRequest(TLRequest): CONSTRUCTOR_ID = 0x24e6818d SUBCLASS_OF_ID = 0x68f17f51 def __init__(self, location: 'TypeInputWebFileLocation', offset: int, limit: int): """ :returns upload.WebFile: Instance of WebFile. """ self.location = location self.offset = offset self.limit = limit def to_dict(self): return { '_': 'GetWebFileRequest', 'location': self.location.to_dict() if isinstance(self.location, TLObject) else self.location, 'offset': self.offset, 'limit': self.limit } def _bytes(self): return b''.join(( b'\x8d\x81\xe6$', self.location._bytes(), struct.pack('<i', self.offset), struct.pack('<i', self.limit), )) @classmethod def from_reader(cls, reader): _location = reader.tgread_object() _offset = reader.read_int() _limit = reader.read_int() return cls(location=_location, offset=_offset, limit=_limit) class ReuploadCdnFileRequest(TLRequest): CONSTRUCTOR_ID = 0x9b2754a8 SUBCLASS_OF_ID = 0xa5940726 def __init__(self, file_token: bytes, request_token: bytes): """ :returns Vector<FileHash>: This type has no constructors. """ self.file_token = file_token self.request_token = request_token def to_dict(self): return { '_': 'ReuploadCdnFileRequest', 'file_token': self.file_token, 'request_token': self.request_token } def _bytes(self): return b''.join(( b"\xa8T'\x9b", self.serialize_bytes(self.file_token), self.serialize_bytes(self.request_token), )) @classmethod def from_reader(cls, reader): _file_token = reader.tgread_bytes() _request_token = reader.tgread_bytes() return cls(file_token=_file_token, request_token=_request_token) class SaveBigFilePartRequest(TLRequest): CONSTRUCTOR_ID = 0xde7b673d SUBCLASS_OF_ID = 0xf5b399ac # noinspection PyShadowingBuiltins def __init__(self, file_id: int, file_part: int, file_total_parts: int, bytes: bytes): """ :returns Bool: This type has no constructors. """ self.file_id = file_id self.file_part = file_part self.file_total_parts = file_total_parts self.bytes = bytes def to_dict(self): return { '_': 'SaveBigFilePartRequest', 'file_id': self.file_id, 'file_part': self.file_part, 'file_total_parts': self.file_total_parts, 'bytes': self.bytes } def _bytes(self): return b''.join(( b'=g{\xde', struct.pack('<q', self.file_id), struct.pack('<i', self.file_part), struct.pack('<i', self.file_total_parts), self.serialize_bytes(self.bytes), )) @classmethod def from_reader(cls, reader): _file_id = reader.read_long() _file_part = reader.read_int() _file_total_parts = reader.read_int() _bytes = reader.tgread_bytes() return cls(file_id=_file_id, file_part=_file_part, file_total_parts=_file_total_parts, bytes=_bytes) class SaveFilePartRequest(TLRequest): CONSTRUCTOR_ID = 0xb304a621 SUBCLASS_OF_ID = 0xf5b399ac # noinspection PyShadowingBuiltins def __init__(self, file_id: int, file_part: int, bytes: bytes): """ :returns Bool: This type has no constructors. """ self.file_id = file_id self.file_part = file_part self.bytes = bytes def to_dict(self): return { '_': 'SaveFilePartRequest', 'file_id': self.file_id, 'file_part': self.file_part, 'bytes': self.bytes } def _bytes(self): return b''.join(( b'!\xa6\x04\xb3', struct.pack('<q', self.file_id), struct.pack('<i', self.file_part), self.serialize_bytes(self.bytes), )) @classmethod def from_reader(cls, reader): _file_id = reader.read_long() _file_part = reader.read_int() _bytes = reader.tgread_bytes() return cls(file_id=_file_id, file_part=_file_part, bytes=_bytes)
PypiClean
/FFGo-1.12.7-py3-none-any.whl/ffgo/gui/gps_tool.py
import locale import tkinter as tk from tkinter import ttk from tkinter.messagebox import showwarning from ..constants import PROGNAME from .. import common_transl from . import widgets from ..geo import geodesy from ..misc import normalizeHeading from .tooltip import ToolTip, TreeviewToolTip def setupTranslationHelper(config): global pgettext, ngettext, npgettext from .. import misc translationHelper = misc.TranslationHelper(config) pgettext = translationHelper.pgettext ngettext = translationHelper.ngettext npgettext = translationHelper.npgettext def setupEarthMagneticFieldProvider(provider): global magField magField = provider class GPSTool: """GPS Tool dialog.""" geodCalc = geodesy.GeodCalc() def __init__(self, master, config, app): for attr in ("master", "config", "app"): setattr(self, attr, locals()[attr]) setupTranslationHelper(config) # These are used to break observer loops with widget A being modified, # causing an update of widget B, itself causing an update of widget # A... self.dontUpdateFlightDuration = self.dontUpdateGroundSpeed = False self.top = tk.Toplevel(self.master) self.top.transient(self.master) # Uncomment this to disallow interacting with other windows # self.top.grab_set() self.top.title(_('GPS Tool')) # Currently, hiding is a better choice than destroying, because memory # occupation doesn't increase when the dialog is shown again after # being hidden. self.top.protocol("WM_DELETE_WINDOW", self.hide) self.top.bind('<Escape>', self.hide) panedWindow = ttk.PanedWindow(self.top, orient="vertical") panedWindow.grid(row=0, column=0, sticky="nsew") self.top.grid_rowconfigure(0, weight=100) self.top.grid_columnconfigure(0, weight=100) # Padding: all or (left, top, right, bottom) # # Padding outside the LabelFrame widgets outerFramesPadding = "12p" # Half of the vertical separation between two “adjacent” LabelFrame # widgets outerFramesHalfSep = "0p" # Padding inside the LabelFrame widgets labelFramesPadding = "15p" # ********************************************************************* # * The airports selection frame * # ********************************************************************* # Frame providing padding around the “Airport A” and “Airport B” # LabelFrame widgets airportsOuterFrame = ttk.Frame( panedWindow, padding=(outerFramesPadding, outerFramesPadding, outerFramesPadding, outerFramesHalfSep)) panedWindow.add(airportsOuterFrame, weight=100) # Airport A self.icaoVarA = tk.StringVar() airportChooserA, searchEntryA, searchClearButtonA, airportSearchTreeA \ = self.airportChooserLabelFrame( container=airportsOuterFrame, row=0, column=0, columnWeight=100, labelFramesPadding=labelFramesPadding, frameTitle=_("Airport A"), icaoVar=self.icaoVarA) spacer = ttk.Frame(airportsOuterFrame) spacer.grid(row=0, column=1, sticky="nsew") airportsOuterFrame.grid_columnconfigure(1, minsize="12p", weight=10) # Airport B self.icaoVarB = tk.StringVar() airportChooserB, searchEntryB, searchClearButtonB, airportSearchTreeB \ = self.airportChooserLabelFrame( container=airportsOuterFrame, row=0, column=2, columnWeight=100, labelFramesPadding=labelFramesPadding, frameTitle=_("Airport B"), icaoVar=self.icaoVarB) # Frame providing padding around the “Calculations” LabelFrame calcOuterFrame = ttk.Frame( panedWindow, padding=(outerFramesPadding, outerFramesHalfSep, outerFramesPadding, outerFramesPadding)) panedWindow.add(calcOuterFrame, weight=100) calcFrame = ttk.LabelFrame(calcOuterFrame, text=_("Calculations"), padding=labelFramesPadding) calcFrame.grid(row=0, column=0, sticky="nsew") calcOuterFrame.grid_rowconfigure(0, weight=100) calcOuterFrame.grid_columnconfigure(0, weight=100) # ********************************************************************* # * Left frame of Calculations, containing parameters (units...) * # ********************************************************************* calcLeftFrame = ttk.Frame(calcFrame) calcLeftFrame.grid(row=0, column=0, sticky="nsw") calcFrame.grid_rowconfigure(0, weight=100) calcFrame.grid_columnconfigure(0, weight=100, pad="30p") # Length unit (nautical miles or kilometers) leftSubframe1 = ttk.Frame(calcLeftFrame) leftSubframe1.grid(row=0, column=0, sticky="nsw") lengthUnitLabel = ttk.Label(leftSubframe1, text=_("Distance in")) lengthUnitLabel.grid(row=0, column=0, sticky="w") leftSubframe1.grid_columnconfigure(0, weight=100) self.lengthUnit = tk.StringVar() self.lengthUnit.set("nautical mile") nautMilesButton = ttk.Radiobutton( leftSubframe1, variable=self.lengthUnit, text=_("nautical miles"), value="nautical mile", padding=("10p", 0, "10p", 0)) nautMilesButton.grid(row=0, column=1, sticky="w") leftSubframe1.grid_rowconfigure(0, pad="5p") kilometersButton = ttk.Radiobutton( leftSubframe1, variable=self.lengthUnit, text=_("kilometers"), value="kilometer", padding=("10p", 0, "10p", 0)) kilometersButton.grid(row=1, column=1, sticky="w") leftSpacerHeight = "20p" leftSpacer = ttk.Frame(calcLeftFrame) leftSpacer.grid(row=1, column=0, sticky="nsew") calcLeftFrame.grid_rowconfigure( 1, minsize=leftSpacerHeight, weight=100) # Magnetic or true bearings leftSubframe2 = ttk.Frame(calcLeftFrame) leftSubframe2.grid(row=2, column=0, sticky="nsw") bearingsTypeLabel = ttk.Label(leftSubframe2, text=_("Bearings")) bearingsTypeLabel.grid(row=0, column=0, sticky="w") leftSubframe2.grid_columnconfigure(0, weight=100) self.bearingsType = tk.StringVar() magBearingsButton = ttk.Radiobutton( leftSubframe2, variable=self.bearingsType, text=pgettext("Bearings", "magnetic"), value="magnetic", padding=("10p", 0, "10p", 0)) magBearingsButton.grid(row=0, column=1, sticky="w") leftSubframe2.grid_rowconfigure(0, pad="5p") trueBearingsButton = ttk.Radiobutton( leftSubframe2, variable=self.bearingsType, text=pgettext("Bearings", "true"), value="true", padding=("10p", 0, "10p", 0)) trueBearingsButton.grid(row=1, column=1, sticky="w") if magField is not None: self.bearingsType.set("magnetic") else: self.bearingsType.set("true") magBearingsButton.state(["disabled"]) ToolTip(bearingsTypeLabel, common_transl.magneticFieldTooltipText, autowrap=True) leftSpacer = ttk.Frame(calcLeftFrame) leftSpacer.grid(row=3, column=0, sticky="nsew") calcLeftFrame.grid_rowconfigure( 3, minsize=leftSpacerHeight, weight=100) # Speed unit (knots or kilometers per hour) leftSubframe3 = ttk.Frame(calcLeftFrame) leftSubframe3.grid(row=4, column=0, sticky="nsw") speedUnitLabel = ttk.Label(leftSubframe3, text=_("Speed in")) speedUnitLabel.grid(row=0, column=0, sticky="w") leftSubframe3.grid_columnconfigure(0, weight=100) self.speedUnit = tk.StringVar() self.speedUnit.set("knot") knotsButton = ttk.Radiobutton( leftSubframe3, variable=self.speedUnit, text=_("knots"), value="knot", padding=("10p", 0, "10p", 0)) knotsButton.grid(row=0, column=1, sticky="w") leftSubframe3.grid_rowconfigure(0, pad="5p") kmhButton = ttk.Radiobutton( leftSubframe3, variable=self.speedUnit, text=_("km/h"), value="km/h", padding=("10p", 0, "10p", 0)) kmhButton.grid(row=1, column=1, sticky="w") spacer = ttk.Frame(calcLeftFrame) spacer.grid(row=5, column=0, sticky="nsew") calcLeftFrame.grid_rowconfigure( 5, minsize=leftSpacerHeight, weight=100) # Calculation method (Vincenty or Karney) leftSubframe4 = ttk.Frame(calcLeftFrame) leftSubframe4.grid(row=6, column=0, sticky="nsw") calcMethodLabel = ttk.Label(leftSubframe4, text=_("Calculation method")) calcMethodLabel.grid(row=0, column=0, sticky="w") self.calcMethodVar = tk.StringVar() karneyMethodRadioButton = ttk.Radiobutton( leftSubframe4, variable=self.calcMethodVar, text=_("Karney"), value="karneyInverse", padding=("10p", 0, "10p", 0)) karneyMethodRadioButton.grid(row=0, column=1, sticky="w") vincentyMethodRadioButton = ttk.Radiobutton( leftSubframe4, variable=self.calcMethodVar, text=_("Vincenty et al."), value="vincentyInverseWithFallback", padding=("10p", 0, "10p", 0)) vincentyMethodRadioButton.grid(row=1, column=1, sticky="w") if self.geodCalc.karneyMethodAvailable(): self.calcMethodVar.set("karneyInverse") else: self.calcMethodVar.set("vincentyInverseWithFallback") karneyMethodRadioButton.state(["disabled"]) # Tooltip for the calculation method ToolTip(calcMethodLabel, common_transl.geodCalcMethodTooltipText(self.geodCalc), autowrap=True) # ********************************************************************* # * Right frame of Calculations, containing the results * # ********************************************************************* calcRightFrame = ttk.Frame(calcFrame) calcRightFrame.grid(row=0, column=1, sticky="nw") calcFrame.grid_rowconfigure(0, weight=100) calcFrame.grid_columnconfigure(1, weight=200) # Distance between the two airports distanceFrame = ttk.Frame(calcRightFrame) distanceFrame.grid(row=0, column=0, sticky="new") calcRightFrame.grid_rowconfigure(0, weight=0) calcRightFrame.grid_columnconfigure(0, weight=100) distanceLabel = ttk.Label(distanceFrame, text=_("Distance between A and B: ")) distanceLabel.grid(row=0, column=0, sticky="w") distanceFrame.grid_rowconfigure(0, weight=100) self.distanceVar = tk.StringVar() distanceValueLabel = ttk.Label(distanceFrame, textvariable=self.distanceVar) distanceValueLabel.grid(row=0, column=1, sticky="w") self.distanceUnitLabelVar = tk.StringVar() distanceUnitLabel = ttk.Label(distanceFrame, textvariable=self.distanceUnitLabelVar) distanceUnitLabel.grid(row=0, column=2, sticky="w") rightSpacerHeight = "20p" spacer = ttk.Frame(calcRightFrame) spacer.grid(row=1, column=0, sticky="nsew") calcRightFrame.grid_rowconfigure( 1, minsize=rightSpacerHeight, weight=100) # Bearings bearingsFrame = ttk.Frame(calcRightFrame) bearingsFrame.grid(row=2, column=0, sticky="ew") calcRightFrame.grid_rowconfigure(2, weight=0) bearingsABLabel = ttk.Label(bearingsFrame, text=_("Bearings from A to B:")) bearingsABLabel.grid(row=0, column=0, sticky="w") bearingsFrame.grid_rowconfigure(0, weight=100) bearingsFrame.grid_columnconfigure(0, pad="8p") bearingsABinitLabel = ttk.Label( bearingsFrame, text=pgettext( "bearings for a path between two points", "init: ")) bearingsABinitLabel.grid(row=0, column=1, sticky="w") self.bearingABinitVar = tk.StringVar() bearingsABinitValueLabel = ttk.Label( bearingsFrame, textvariable=self.bearingABinitVar) bearingsABinitValueLabel.grid(row=0, column=2, sticky="w") bearingsFrame.grid_columnconfigure(2, pad="10p") spacer = ttk.Frame(bearingsFrame) spacer.grid(row=0, column=3, sticky="nsew") calcRightFrame.grid_columnconfigure(3, minsize="10p", weight=100) bearingsABfinalLabel = ttk.Label( bearingsFrame, text=pgettext( "bearings for a path between two points", "final: ")) bearingsABfinalLabel.grid(row=0, column=4, sticky="w") self.bearingABfinalVar = tk.StringVar() bearingsABfinalValueLabel = ttk.Label( bearingsFrame, textvariable=self.bearingABfinalVar) bearingsABfinalValueLabel.grid(row=0, column=5, sticky="w") bearingsBALabel = ttk.Label(bearingsFrame, text=_("Bearings from B to A: ")) bearingsBALabel.grid(row=1, column=0, sticky="w") bearingsFrame.grid_rowconfigure(1, weight=100) bearingsBAinitLabel = ttk.Label( bearingsFrame, text=pgettext( "bearings for a path between two points", "init: ")) bearingsBAinitLabel.grid(row=1, column=1, sticky="w") self.bearingBAinitVar = tk.StringVar() bearingsBAinitValueLabel = ttk.Label( bearingsFrame, textvariable=self.bearingBAinitVar) bearingsBAinitValueLabel.grid(row=1, column=2, sticky="w") # Spacer present in row 0 column 3, no need to insert another one here bearingsBAfinalLabel = ttk.Label( bearingsFrame, text=pgettext( "bearings for a path between two points", "final: ")) bearingsBAfinalLabel.grid(row=1, column=4, sticky="w") self.bearingBAfinalVar = tk.StringVar() bearingsBAfinalValueLabel = ttk.Label( bearingsFrame, textvariable=self.bearingBAfinalVar) bearingsBAfinalValueLabel.grid(row=1, column=5, sticky="w") spacer = ttk.Frame(calcRightFrame) spacer.grid(row=3, column=0, sticky="nsew") calcRightFrame.grid_rowconfigure( 3, minsize=rightSpacerHeight, weight=100) # Flight duration in relation to ground speed groundSpeedVsFlightTimeFrame = ttk.Frame(calcRightFrame) groundSpeedVsFlightTimeFrame.grid(row=4, column=0, sticky="ew") calcRightFrame.grid_rowconfigure(4, weight=0) groundSpeedLabel = ttk.Label(groundSpeedVsFlightTimeFrame, text=_("Ground speed: ")) groundSpeedLabel.grid(row=0, column=0, sticky="w") groundSpeedVsFlightTimeFrame.grid_rowconfigure(0, weight=100) self.groundSpeed = tk.StringVar() self.groundSpeed.set("475") # typical airliner speed (in knots) self.groundSpeedEntry = ttk.Entry( groundSpeedVsFlightTimeFrame, width=5, textvariable=self.groundSpeed) self.groundSpeedEntry.grid(row=0, column=1) groundSpeedVsFlightTimeFrame.grid_columnconfigure(1, minsize="20p", pad="5p") self.speedUnitLabelVar = tk.StringVar() speedUnitLabel = ttk.Label(groundSpeedVsFlightTimeFrame, textvariable=self.speedUnitLabelVar) speedUnitLabel.grid(row=0, column=2, sticky="w") groundSpeedVsFlightTimeFrame.grid_columnconfigure(2, pad="20p") # Double arrow between ground speed and flight duration linkLabel = ttk.Label(groundSpeedVsFlightTimeFrame, text="↔") linkLabel.grid(row=0, column=3, sticky="ew") groundSpeedVsFlightTimeFrame.grid_columnconfigure(3, pad="20p") self.flightDuration = tk.StringVar() # minutes self.flightDurationEntry = ttk.Entry( groundSpeedVsFlightTimeFrame, width=6, textvariable=self.flightDuration) self.flightDurationEntry.grid(row=0, column=4) groundSpeedVsFlightTimeFrame.grid_columnconfigure(4, pad="5p") # Time unit + human-readable form for the flight duration (such as # “1 day, 12 hours and 5 minutes”) self.flightDurationPostfixVar = tk.StringVar() flightDurationPostfixLabel = ttk.Label( groundSpeedVsFlightTimeFrame, textvariable=self.flightDurationPostfixVar) flightDurationPostfixLabel.grid(row=0, column=5, sticky="w") # Use a minimum column size in order to avoid frequent layout changes # when the flight duration is modified. groundSpeedVsFlightTimeFrame.grid_columnconfigure( 5, minsize=tk.font.Font().measure("0"*60)) ToolTip(flightDurationPostfixLabel, _("Decomposition using Julian years\n" "(1 Julian year = {days} days)").format( days=locale.format("%.02f", 365.25, grouping=True))) # This causes the initialization of the various fields of the dialog # because of the TreeviewSelect event generated by the initial airport # selection from airportChooserLabelFrame(). self.icaoVarA.trace("w", self.updateResults) self.icaoVarB.trace("w", self.updateResults) self.calcMethodVar.trace("w", self.updateResults) self.bearingsType.trace("w", self.updateDisplayedResults) self.lengthUnit.trace("w", self.updateDisplayedResults) self.speedUnit.trace("w", self.onSpeedUnitChanged) self.groundSpeed.trace("w", self.updateDisplayedFlightTime) self.flightDuration.trace("w", self.updateDisplayedGroundSpeed) self.flightDuration.trace("w", self.updateFlightDurationPostfix) self.updateDisplayedSpeedUnit() # Initially focus the search field for airport A searchEntryA.focus_set() def airportChooserLabelFrame(self, *, container, row, column, columnWeight, labelFramesPadding, frameTitle, icaoVar): labelFrame = ttk.LabelFrame(container, text=frameTitle, padding=labelFramesPadding) labelFrame.grid(row=row, column=column, sticky="nsew") container.grid_rowconfigure(row, weight=100) container.grid_columnconfigure(column, weight=100) leftSubframe = ttk.Frame(labelFrame, padding=(0, 0, "30p", 0)) leftSubframe.grid(row=0, column=0, sticky="ew") labelFrame.grid_rowconfigure(0, weight=100) labelFrame.grid_columnconfigure(0, weight=100) searchLabel = ttk.Label(leftSubframe, text=_("Search: ")) searchLabel.grid(row=0, column=0, sticky="w") # The link to a StringVar is done in the AirportChooser class searchEntry = ttk.Entry(leftSubframe) searchEntry.grid(row=0, column=1, sticky="ew") leftSubframe.grid_columnconfigure(1, weight=100) spacer = ttk.Frame(leftSubframe) spacer.grid(row=1, column=0, sticky="nsew") leftSubframe.grid_rowconfigure(1, minsize="18p", weight=100) # The button binding is done in the AirportChooser class searchClearButton = ttk.Button(leftSubframe, text=_('Clear')) searchClearButton.grid(row=2, column=1, sticky="w") # The TreeviewSelect event binding is done in the AirportChooser class airportSearchTree = widgets.MyTreeview( labelFrame, columns=["icao", "name"], show="headings", selectmode="browse", height=10) airportSearchTree.grid(row=0, column=1, sticky="nsew") labelFrame.grid_columnconfigure(1, weight=500) def airportSearchTreeTooltipFunc(region, itemID, column, self=self): if region == "cell": icao = airportSearchTree.set(itemID, "icao") found, airport = self.app.readAirportData(icao) return airport.tooltipText() if found else None else: return None airportChooserTooltip = TreeviewToolTip(airportSearchTree, airportSearchTreeTooltipFunc) airportScrollbar = ttk.Scrollbar( labelFrame, orient='vertical', command=airportSearchTree.yview, takefocus=0) airportScrollbar.grid(row=0, column=2, sticky="ns") def onAirportListScrolled(*args, airportScrollbar=airportScrollbar, airportChooserTooltip=airportChooserTooltip): airportScrollbar.set(*args) # Once the Treeview is scrolled, the tooltip is likely not to match # the airport under the mouse pointer anymore. airportChooserTooltip.hide() airportSearchTree.config(yscrollcommand=onAirportListScrolled) airportSearchColumnsList = [ widgets.Column("icao", _("ICAO"), 0, "w", False, "width", widthText="M"*4), widgets.Column("name", _("Name"), 1, "w", True, "width", widthText="M"*20)] airportSearchColumns = { col.name: col for col in airportSearchColumnsList } airportSearchData = [] for icao in self.config.sortedIcao(): airport = self.config.airports[icao] airportSearchData.append((icao, airport.name)) airportChooser = widgets.AirportChooser( self.master, self.config, icaoVar, # output variable of the chooser airportSearchData, airportSearchColumns, "icao", # Initially, sort by ICAO searchEntry, searchClearButton, airportSearchTree, # Delay before propagating the effect of nav keys (arrows...). 0, # The calculation is fast enough here that now delay is needed. treeUpdatedCallback=lambda t=airportChooserTooltip: t.hide()) # Initial airport selection curIcao = self.config.airport.get() try: # This will set icaoVar via the TreeviewSelect event handler. airportSearchTree.FFGoGotoItemWithValue("icao", curIcao) except widgets.NoSuchItem: icaoVar.set('') return (airportChooser, searchEntry, searchClearButton, airportSearchTree) # Accept any arguments to allow safe use as a Tkinter variable observer def updateResults(self, *args): # By default, assume the calculations couldn't be carried out to make # sure not to display wrong results in case we return without setting # these instance attributes. self.distance = self.bearingABinit = self.bearingABfinal = None icaoA = self.icaoVarA.get() icaoB = self.icaoVarB.get() if icaoA and icaoB: # we have two defined airports, go ahead distCalcFunc = getattr(self.geodCalc, self.calcMethodVar.get()) aptA = self.config.airports[icaoA] aptB = self.config.airports[icaoB] if magField is not None: self.magDeclA, self.magDeclB = magField.batchDecl( ((aptA.lat, aptA.lon), (aptB.lat, aptB.lon))) try: g = distCalcFunc(aptA.lat, aptA.lon, aptB.lat, aptB.lon) except geodesy.VincentyInverseError: message = _('Unable to perform this calculation') detail = _( "Could not compute the distance and bearings between " "{icaoA} ({nameA}) and {icaoB} ({nameB}).\n\n" "Vincenty's algorithm for the geodetic inverse problem " "is known not to handle all possible cases (most notably, " "it can't handle the case of two antipodal or nearly " "antipodal points). Use Karney's calculation method if " "you want to see the results for these two airports.") \ .format(icaoA=icaoA, icaoB=icaoB, nameA=aptA.name, nameB=aptB.name) showwarning(_('{prg}').format(prg=PROGNAME), message, detail=detail, parent=self.top) else: # The calculation went fine; set the relevant attributes. self.distance = g["s12"] # in meters self.bearingABinit = g["azi1"] # true bearing self.bearingABfinal = g["azi2"] # ditto self.updateDisplayedResults() # Accept any arguments to allow safe use as a Tkinter variable observer def updateDisplayedResults(self, *args): self.updateDisplayedDistance() self.updateDisplayedBearings() self.updateDisplayedFlightTime() def updateDisplayedDistance(self): unit = self.lengthUnit.get() if unit == "nautical mile": if self.distance is not None: dist = self.distance / 1852 unitPostfix = pgettext("length unit", " nm") else: assert unit == "kilometer", unit if self.distance is not None: dist = self.distance / 1000 unitPostfix = pgettext("length unit", " km") if self.distance is None: self.distanceVar.set("---") else: self.distanceVar.set(str(round(dist))) self.distanceUnitLabelVar.set(unitPostfix) def updateDisplayedBearings(self): bearingsType = self.bearingsType.get() assert bearingsType in ("magnetic", "true"), bearingsType magBearings = (bearingsType == "magnetic") azi1 = self.bearingABinit azi2 = self.bearingABfinal if azi1 is None or self.distance == 0: initBearingAB = finalBearingBA = "---" else: if magBearings: initBearingAB = normalizeHeading(azi1 - self.magDeclA) finalBearingBA = normalizeHeading(azi1 + 180.0 - self.magDeclA) else: initBearingAB = normalizeHeading(azi1) finalBearingBA = normalizeHeading(azi1 + 180.0) if azi2 is None or self.distance == 0: finalBearingAB = initBearingBA = "---" else: if magBearings: finalBearingAB = normalizeHeading(azi2 - self.magDeclB) initBearingBA = normalizeHeading(azi2 + 180.0 - self.magDeclB) else: finalBearingAB = normalizeHeading(azi2) initBearingBA = normalizeHeading(azi2 + 180.0) self.bearingABinitVar.set(str(initBearingAB)) self.bearingABfinalVar.set(str(finalBearingAB)) self.bearingBAinitVar.set(str(initBearingBA)) self.bearingBAfinalVar.set(str(finalBearingBA)) # Accept any arguments to allow safe use as a Tkinter variable observer def updateDisplayedGroundSpeed(self, *args): if self.dontUpdateGroundSpeed: self.dontUpdateGroundSpeed = False return # Every code path below sets self.groundSpeed. This must not in turn # cause an update to the flight duration... self.dontUpdateFlightDuration = True if self.distance is None: self.groundSpeed.set("") return durationStr = self.flightDuration.get() try: durationMin = float(durationStr) if durationMin < 0: raise ValueError except ValueError: self.groundSpeed.set("") return unit = self.speedUnit.get() assert unit in ("knot", "km/h") try: if unit == "knot": gs = 60*self.distance / (durationMin*1852) else: gs = 60*self.distance / (durationMin*1000) except ZeroDivisionError: self.groundSpeed.set("") else: self.groundSpeed.set(str(round(gs))) def _setInvalidFlightDuration(self): self.flightDuration.set("") # Accept any arguments to allow safe use as a Tkinter variable observer def updateDisplayedFlightTime(self, *args): if self.dontUpdateFlightDuration: self.dontUpdateFlightDuration = False return # Every code path below sets self.flightDuration. This must not in turn # cause an update to the ground speed... self.dontUpdateGroundSpeed = True if self.distance is None: self._setInvalidFlightDuration() return groundSpeedStr = self.groundSpeed.get() try: groundSpeed = float(groundSpeedStr) if groundSpeed < 0: raise ValueError except ValueError: self._setInvalidFlightDuration() return unit = self.speedUnit.get() assert unit in ("knot", "km/h") try: if unit == "knot": durationMin = 60*self.distance / (groundSpeed*1852) else: durationMin = 60*self.distance / (groundSpeed*1000) except ZeroDivisionError: self._setInvalidFlightDuration() return roundedMin = round(durationMin) self.flightDuration.set(str(roundedMin)) # Accept any arguments to allow safe use as a Tkinter variable observer def updateFlightDurationPostfix(self, *args): """ Update the converted value of flight time in days, hours and minutes.""" baseUnitStr = pgettext("unit of time", "min") durationStr = self.flightDuration.get() try: durationMin = float(durationStr) if durationMin < 0: raise ValueError except ValueError: self.flightDurationPostfixVar.set(baseUnitStr) return roundedMin = round(durationMin) l = [baseUnitStr] if roundedMin >= 60: # Print a user-friendly representation of the flight duration if it # is at least one minute. l.append(" (" + self.decomposeMinutes(roundedMin) + ")") self.flightDurationPostfixVar.set(''.join(l)) def decomposeMinutes(self, nMin): """Decompose an integral number of minutes.""" # 1 Julian year = 365.25 days. This one is easier to handle separately # because of the non-integral number. 525960 = 365.25*24*60. years, remainingMin = divmod(nMin, 525960) hours, minutes = divmod(remainingMin, 60) days, hours = divmod(hours, 24) l = [] if years: l.append(_("{nYears} {years}").format( nYears=locale.format("%d", years, grouping=True), years=ngettext("year", "years", years))) if days: l.append(_("{nDays} {days}").format( nDays=locale.format("%d", days, grouping=True), days=ngettext("day", "days", days))) if hours: l.append(_("{nHours} {hours}").format( nHours=locale.format("%d", hours, grouping=True), hours=ngettext("hour", "hours", hours))) if minutes: l.append(_("{nMinutes} {minutes}").format( nMinutes=locale.format("%d", minutes, grouping=True), minutes=ngettext("minute", "minutes", minutes))) if len(l) >= 2: res = ", ".join(l[:-1]) + pgettext("duration expression", " and ") + l[-1] elif l: # len(l) == 1, actually res = l[0] else: # 0 minutes in total # Use the same expression as above for uniformity and to avoid # creating useless work for translations res = _("{nMinutes} {minutes}").format( nMinutes=locale.format("%d", 0, grouping=True), minutes=ngettext("minute", "minutes", minutes)) return res # Accept any arguments to allow safe use as a Tkinter variable observer def onSpeedUnitChanged(self, *args): self.updateDisplayedSpeedUnit() groundSpeedStr = self.groundSpeed.get() try: groundSpeed = float(groundSpeedStr) except ValueError: return unit = self.speedUnit.get() assert unit in ("knot", "km/h") if unit == "knot": gs = groundSpeed / 1.852 else: gs = 1.852*groundSpeed self.dontUpdateFlightDuration = True self.groundSpeed.set(str(round(gs))) def updateDisplayedSpeedUnit(self): unit = self.speedUnit.get() assert unit in ("knot", "km/h") if unit == "knot": unitPostfix = pgettext("speed unit", " kn") else: unitPostfix = pgettext("speed unit", " km/h") self.speedUnitLabelVar.set(unitPostfix) def hide(self, event=None): """Hide the GPS Tool dialog.""" self.top.withdraw() def show(self, event=None): """Unhide a hidden GPS Tool dialog.""" self.top.deiconify() def destroy(self, event=None): """Destroy the GPS Tool dialog.""" self.top.destroy() # Normally, this should allow Python's garbage collector to free some # memory, however it doesn't work so well. Presumably, the Tk widgets # stay in memory even when they are not referenced anymore... self.app.setGPSToolToNone()
PypiClean
/1000pip%20Climber%20System%20download-2022.tar.gz/1000pip Climber System download-2022/README.md
<h1></h1> <p> <div class="separator" style="clear: both;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: block; padding: 1em 0px; text-align: center;" target="_blank"></a><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></div><div class="separator" style="clear: both;"><br /><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Would you like to achieve your dream of being a successful Forex trader?&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">Take the shortcut to success with the state of the art Forex algorithm from 1000pip Climber. This trading system is rated 5 star on Investing.com and has verififed performance history from MyFXBook, so you can be confident that you are using the best algorithm available.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" target="_blank">&gt;&gt;&gt;Click here to learn more</a></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This unique Forex system continuously analyses the FX market, looking for potentially high probability price movements. Once identified the software will notify you visually, audibly, and via email.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">ALL key parameters are provided; entry price, take profit and stop loss. The Forex system is easy to set up and is designed to be followed 100% mechanically – just try the Forex system and see the results. This Forex system really is the simplest way to follow the FX market.&nbsp;</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;">This is a rare opportunity to use a professional Forex trading algorithm that has produced highly accurate and consistent results. Join our group of loyal members and see how you can revolutionize your trading.</p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><br /></p><p style="border: 0px; caret-color: rgb(85, 85, 85); color: #555555; font-family: Lato; font-size: 20px; font-stretch: inherit; line-height: 24px; margin: 0px 0px 15px; padding: 0px; vertical-align: baseline;"><a href="https://156544mlxov28levev7grc9v9g.hop.clickbank.net/?tid=py" rel="nofollow" style="display: inline; font-family: -webkit-standard; padding: 1em 0px;" target="_blank"><img border="0" data-original-height="66" data-original-width="342" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTJ6OH0OJANSM_yJIoRArK0LR0CRaOEWTSm3mxxP23WdYgh3mQxKobSFzZrDFzIqCaNEnzzoXzexZ1XKUJF7eXiyCoKlBw1aQ3BOM5_92szbWpIjMKbFIasd51DpFoYG7UWvAn4rqfDqZe_nR8Ct0_ubH2WPREFJC_cJviYwd5Kpp3CtTabVq34YqWJA/s16000/button_download-now.png" /></a></p></div> # 1000pip Climber System download ```bash pip3 1000pip Climber System download
PypiClean
/Nuitka_fixed-1.1.2-cp310-cp310-win_amd64.whl/nuitka/code_generation/ListCodes.py
from .CodeHelpers import ( assignConstantNoneResult, decideConversionCheckNeeded, generateChildExpressionsCode, generateExpressionCode, withCleanupFinally, withObjectCodeTemporaryAssignment, ) from .ErrorCodes import getErrorExitBoolCode, getErrorExitCode from .PythonAPICodes import generateCAPIObjectCode def generateListCreationCode(to_name, expression, emit, context): elements = expression.subnode_elements assert elements with withObjectCodeTemporaryAssignment( to_name, "list_result", expression, emit, context ) as result_name: element_name = context.allocateTempName("list_element") def generateElementCode(element): generateExpressionCode( to_name=element_name, expression=element, emit=emit, context=context ) # Use helper that makes sure we provide a reference. if context.needsCleanup(element_name): context.removeCleanupTempName(element_name) helper_code = "PyList_SET_ITEM" else: helper_code = "PyList_SET_ITEM0" return helper_code helper_code = generateElementCode(elements[0]) emit("%s = PyList_New(%d);" % (result_name, len(elements))) needs_exception_exit = any( element.mayRaiseException(BaseException) for element in elements[1:] ) with withCleanupFinally( "list_build", result_name, needs_exception_exit, emit, context ) as guarded_emit: emit = guarded_emit.emit for count, element in enumerate(elements): if count > 0: helper_code = generateElementCode(element) emit( "%s(%s, %d, %s);" % (helper_code, result_name, count, element_name) ) def generateListOperationAppendCode(statement, emit, context): list_arg_name = context.allocateTempName("append_list") generateExpressionCode( to_name=list_arg_name, expression=statement.subnode_list_arg, emit=emit, context=context, ) value_arg_name = context.allocateTempName("append_value") generateExpressionCode( to_name=value_arg_name, expression=statement.subnode_value, emit=emit, context=context, ) context.setCurrentSourceCodeReference(statement.getSourceReference()) res_name = context.getBoolResName() emit("assert(PyList_Check(%s));" % list_arg_name) if context.needsCleanup(value_arg_name): emit("%s = LIST_APPEND1(%s, %s);" % (res_name, list_arg_name, value_arg_name)) context.removeCleanupTempName(value_arg_name) else: emit("%s = LIST_APPEND0(%s, %s);" % (res_name, list_arg_name, value_arg_name)) # TODO: Only really MemoryError, which we often ignore. getErrorExitBoolCode( condition="%s == false" % res_name, release_names=(list_arg_name, value_arg_name), emit=emit, context=context, ) def generateListOperationExtendCode(to_name, expression, emit, context): list_arg_name, value_arg_name = generateChildExpressionsCode( expression=expression, emit=emit, context=context ) emit("assert(PyList_Check(%s));" % list_arg_name) # These give different error messages. is_unpack = expression.isExpressionListOperationExtendForUnpack() res_name = context.getBoolResName() emit( "%s = %s(%s, %s);" % ( res_name, "LIST_EXTEND_FOR_UNPACK" if is_unpack else "LIST_EXTEND", list_arg_name, value_arg_name, ) ) getErrorExitBoolCode( condition="%s == false" % res_name, release_names=(list_arg_name, value_arg_name), emit=emit, context=context, ) assignConstantNoneResult(to_name, emit, context) def generateListOperationPopCode(to_name, expression, emit, context): (list_arg_name,) = generateChildExpressionsCode( expression=expression, emit=emit, context=context ) emit("assert(PyList_Check(%s));" % list_arg_name) with withObjectCodeTemporaryAssignment( to_name, "list_pop_result", expression, emit, context ) as result_name: # TODO: Have a dedicated helper instead, this could be more efficient. emit( '%s = PyObject_CallMethod(%s, (char *)"pop", NULL);' % (result_name, list_arg_name) ) getErrorExitCode( check_name=result_name, release_name=list_arg_name, emit=emit, context=context, ) context.addCleanupTempName(result_name) def generateBuiltinListCode(to_name, expression, emit, context): generateCAPIObjectCode( to_name=to_name, capi="MAKE_LIST", arg_desc=(("list_arg", expression.subnode_value),), may_raise=expression.mayRaiseException(BaseException), conversion_check=decideConversionCheckNeeded(to_name, expression), source_ref=expression.getCompatibleSourceReference(), emit=emit, context=context, )
PypiClean
/Flask_AppBuilder-4.3.6-py3-none-any.whl/flask_appbuilder/security/sqla/apis/user/api.py
from datetime import datetime from flask import g, request from flask_appbuilder import ModelRestApi from flask_appbuilder.api import expose, safe from flask_appbuilder.const import API_RESULT_RES_KEY from flask_appbuilder.models.sqla.interface import SQLAInterface from flask_appbuilder.security.decorators import permission_name, protect from flask_appbuilder.security.sqla.apis.user.schema import ( UserPostSchema, UserPutSchema, ) from flask_appbuilder.security.sqla.models import Role, User from marshmallow import ValidationError from sqlalchemy.exc import IntegrityError from werkzeug.security import generate_password_hash class UserApi(ModelRestApi): resource_name = "security/users" openapi_spec_tag = "Security Users" class_permission_name = "User" datamodel = SQLAInterface(User) allow_browser_login = True list_columns = [ "id", "roles.id", "roles.name", "first_name", "last_name", "username", "active", "email", "last_login", "login_count", "fail_login_count", "created_on", "changed_on", "created_by.id", "changed_by.id", ] show_columns = list_columns add_columns = [ "roles", "first_name", "last_name", "username", "active", "email", "password", ] edit_columns = add_columns search_columns = [ "username", "first_name", "last_name", "active", "email", "created_by", "changed_by", "roles", ] add_model_schema = UserPostSchema() edit_model_schema = UserPutSchema() def pre_update(self, item): item.changed_on = datetime.now() item.changed_by_fk = g.user.id if item.password: item.password = generate_password_hash(item.password) def pre_add(self, item): item.password = generate_password_hash(item.password) @expose("/", methods=["POST"]) @protect() @safe @permission_name("post") def post(self): """Create new user --- post: requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' responses: 201: description: Item changed content: application/json: schema: type: object properties: result: $ref: '#/components/schemas/{{self.__class__.__name__}}.post' 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ try: item = self.add_model_schema.load(request.json) model = User() roles = [] for key, value in item.items(): if key != "roles": setattr(model, key, value) else: for role_id in item[key]: role = ( self.datamodel.session.query(Role) .filter(Role.id == role_id) .one_or_none() ) if role: role.user_id = model.id role.role_id = role_id roles.append(role) if "roles" in item.keys(): model.roles = roles self.pre_add(model) self.datamodel.add(model, raise_exception=True) return self.response(201, id=model.id) except ValidationError as error: return self.response_400(message=error.messages) except IntegrityError as e: return self.response_422(message=str(e.orig)) @expose("/<pk>", methods=["PUT"]) @protect() @safe @permission_name("put") def put(self, pk): """Edit user --- put: parameters: - in: path schema: type: integer name: pk requestBody: description: Model schema required: true content: application/json: schema: $ref: '#/components/schemas/{{self.__class__.__name__}}.put' responses: 200: description: Item changed content: application/json: schema: type: object properties: result: $ref: '#/components/schemas/{{self.__class__.__name__}}.put' 400: $ref: '#/components/responses/400' 401: $ref: '#/components/responses/401' 404: $ref: '#/components/responses/404' 422: $ref: '#/components/responses/422' 500: $ref: '#/components/responses/500' """ try: item = self.edit_model_schema.load(request.json) model = self.datamodel.get(pk, self._base_filters) roles = [] for key, value in item.items(): if key != "roles": setattr(model, key, value) else: for role_id in item[key]: role = ( self.datamodel.session.query(Role) .filter(Role.id == role_id) .one_or_none() ) if role: role.user_id = model.id role.role_id = role_id roles.append(role) if "roles" in item.keys(): model.roles = roles self.pre_update(model) self.datamodel.edit(model, raise_exception=True) return self.response( 200, **{API_RESULT_RES_KEY: self.edit_model_schema.dump(item, many=False)}, ) except ValidationError as e: return self.response_400(message=e.messages) except IntegrityError as e: return self.response_422(message=str(e.orig))
PypiClean
/Hyperion-0.9.10.tar.gz/Hyperion-0.9.10/docs/important/important.rst
Important Notes =============== Gridding -------- As a user, you are responsible for ensuring that the grid on which the radiative transfer is carried out is adequate to resolve density and temperature gradients. In the case of the :class:`~hyperion.model.AnalyticalYSOModel` class, Hyperion tries to optimize the gridding of the inner disk to ensure that it is properly resolved, but you still need to ensure that the *number* of cells you specificy is adequate. Number of photons ----------------- Similarly to the `Gridding`_, you are responsible for choosing an adequate number of photons to carry out the radiative transfer. You can read the :doc:`../setup/photon_numbers` page for advice, and this page will be expanded in future, but the best way to ensure that you have enough photons is to check yourself that the results (temperature, images, SEDs) have converged if you increase the number of photons. Dust and/or Gas? ---------------- While Hyperion is a dust continuum radiative transfer code, you should take care when specifying densities, accretion rates, etc. as to whether to include the contribution from gas. The guidelines are as follows: * The core Fortran code does not make any assumptions regarding gas - it simply computes optical depths from the densities and opacities provided. Therefore, dust opacities and densities have to be consistent as to whether they are per unit dust mass, or per unit dust+gas mass, and what gas-to-dust ratio they assume. For example, if the dust opacities are provided per unit dust mass, then the densities specified in the model should be dust densities. If the dust opacities are provided per unit dust+gas mass, then the densities specified in the model should be dust+gas densities. For the dust models provided in :doc:`../dust/dust`, each dust model explicitly states whether it includes gas in the opacities or not. When setting up your own dust models, you should be aware of whether they are given per unit dust or dust+gas mass and what gas-to-dust ratio was assumed. * For the :class:`~hyperion.densities.UlrichEnvelope` density structure, the infall rate provided is directly related to the density, so that if the dust opacities are per unit dust mass, the infall rate should be the infall rate of dust. * For the :class:`~hyperion.densities.AlphaDisk` density structure, the accretion rate provided does not relate to the density in the model, but it used to add a source of luminosity. Therefore, it should include the total mass of **dust+gas** regardless of how the opacities are expressed. However, the mass or density of the disk should be given depending on the units of the opacity, as described above.
PypiClean
/DecoratorTools-1.8.zip/DecoratorTools-1.8/README.txt
Class, Function, and Assignment Decorators, Metaclasses, and Related Tools ========================================================================== Want to use decorators, but still need to support Python 2.3? Wish you could have class decorators, decorate arbitrary assignments, or match decorated function signatures to their original functions? Want to get metaclass features without creating metaclasses? How about synchronized methods? "DecoratorTools" gets you all of this and more. Some quick examples:: # Method decorator example from peak.util.decorators import decorate class Demo1(object): decorate(classmethod) # equivalent to @classmethod def example(cls): print "hello from", cls # Class decorator example from peak.util.decorators import decorate_class def my_class_decorator(): def decorator(cls): print "decorating", cls return cls decorate_class(decorator) class Demo2: my_class_decorator() # "decorating <class Demo2>" will be printed when execution gets here Installing DecoratorTools (using ``"easy_install DecoratorTools"`` or ``"setup.py install"``) gives you access to the ``peak.util.decorators`` module. The tools in this module have been bundled for years inside of PEAK, PyProtocols, RuleDispatch, and the zope.interface package, so they have been widely used and tested. (Unit tests are also included, of course.) This standalone version is backward-compatible with the bundled versions, so you can mix and match decorators from this package with those provided by zope.interface, TurboGears, etc. For complete documentation, see the `DecoratorTools manual`_. Changes since version 1.7: * The ``@template_function`` decorator now supports using a return value instead of a docstring, in order to work with the "-OO" option to Python; it's highly recommended that you update your template functions to use a return value instead of a docstring. (The error message has also been improved for the missing docstring case.) * Fixed metaclass collisions in ``classy`` subclasses that mix in abstract classes (e.g. ``collections.Sequence``) in Python 2.6+. Changes since version 1.6: * Added ``synchronized`` decorator to support locking objects during method execution. Changes since version 1.5: * Added ``classy`` base class that allows you to do the most often-needed metaclass behviors *without* needing an actual metaclass. Changes since version 1.4: * Added ``enclosing_frame()`` function, so that complex decorators that call DecoratorTools functions while being called *by* DecoratorTools functions, will work correctly. Changes since version 1.3: * Added support for debugging generated code, including the code generated by ``rewrap()`` and ``template_function``. Changes since version 1.2: * Added ``rewrap()`` function and ``template_function`` decorator to support signature matching for decorated functions. (These features are similar to the ones provided by Michele Simionato's "decorator" package, but do not require Python 2.4 and don't change the standard idioms for creating decorator functions.) * ``decorate_class()`` will no longer apply duplicate class decorator callbacks unless the ``allow_duplicates`` argument is true. Changes since version 1.1: * Fixed a problem where instances of different struct types could equal each other Changes since version 1.0: * The ``struct()`` decorator makes it easy to create tuple-like data structure types, by decorating a constructor function. .. _DecoratorTools Manual: http://peak.telecommunity.com/DevCenter/DecoratorTools#toc .. _toc: .. contents:: **Table of Contents** You may access any of the following APIs by importing them from ``peak.util.decorators``: Simple Decorators ----------------- decorate(\*decorators) Apply `decorators` to the subsequent function definition or assignment statement, thereby allowing you to conviently use standard decorators with Python 2.3 and up (i.e., no ``@`` syntax required), as shown in the following table of examples:: Python 2.4+ DecoratorTools ------------ -------------- @classmethod decorate(classmethod) def blah(cls): def blah(cls): pass pass @foo @bar(baz) decorate(foo, bar(baz)) def spam(bing): def spam(bing): """whee""" """whee""" decorate_class(decorator [, depth=2, frame=None]) Set up `decorator` to be passed the containing class after its creation. This function is designed to be called by a decorator factory function executed in a class suite. It is not used directly; instead you simply give your users a "magic function" to call in the body of the appropriate class. Your "magic function" (i.e. a decorator factory function) then calls ``decorate_class`` to register the decorator to be called when the class is created. Multiple decorators may be used within a single class, although they must all appear *after* the ``__metaclass__`` declaration, if there is one. The registered decorator will be given one argument: the newly created containing class. The return value of the decorator will be used in place of the original class, so the decorator should return the input class if it does not wish to replace it. Example:: >>> from peak.util.decorators import decorate_class >>> def demo_class_decorator(): ... def decorator(cls): ... print "decorating", cls ... return cls ... decorate_class(decorator) >>> class Demo: ... demo_class_decorator() decorating __builtin__.Demo In the above example, ``demo_class_decorator()`` is the decorator factory function, and its inner function ``decorator`` is what gets called to actually decorate the class. Notice that the factory function has to be called within the class body, even if it doesn't take any arguments. If you are just creating simple class decorators, you don't need to worry about the `depth` or `frame` arguments here. However, if you are creating routines that are intended to be used within other class or method decorators, you will need to pay attention to these arguments to ensure that ``decorate_class()`` can find the frame where the class is being defined. In general, the simplest way to do this is for the function that's called in the class body to get its caller's frame with ``sys._getframe(1)``, and then pass that frame down to whatever code will be calling ``decorate_class()``. Alternately, you can specify the `depth` that ``decorate_class()`` should call ``sys._getframe()`` with, but this can be a bit trickier to compute correctly. Note, by the way that ``decorate_class()`` ignores duplicate callbacks:: >>> def hello(cls): ... print "decorating", cls ... return cls >>> def do_hello(): ... decorate_class(hello) >>> class Demo: ... do_hello() ... do_hello() decorating __builtin__.Demo Unless the ``allow_duplicates`` argument is set to a true value:: >>> def do_hello(): ... decorate_class(hello, allow_duplicates=True) >>> class Demo: ... do_hello() ... do_hello() decorating __builtin__.Demo decorating __builtin__.Demo The ``synchronized`` Decorator ------------------------------ When writing multithreaded programs, it's often useful to define certain operations as being protected by a lock on an object. The ``synchronized`` decorator lets you do this by decorating object methods, e.g.:: >>> from peak.util.decorators import synchronized >>> class TryingToBeThreadSafe(object): ... synchronized() # could be just ``@synchronized`` for 2.4+ ... def method1(self, arg): ... print "in method 1" ... self.method2() ... print "back in method 1" ... return arg ... ... synchronized() # could be just ``@synchronized`` for 2.4+ ... def method2(self): ... print "in method 2" ... return 42 >>> TryingToBeThreadSafe().method1(99) in method 1 in method 2 back in method 1 99 What you can't tell from this example is that a ``__lock__`` attribute is being acquired and released around each of those calls. Let's take a closer look:: >>> class DemoLock: ... def __init__(self, name): ... self.name = name ... def acquire(self): ... print "acquiring", self.name ... def release(self): ... print "releasing", self.name >>> ts = TryingToBeThreadSafe() >>> ts.__lock__ = DemoLock("lock 1") >>> ts.method2() acquiring lock 1 in method 2 releasing lock 1 42 >>> ts.method1(27) acquiring lock 1 in method 1 acquiring lock 1 in method 2 releasing lock 1 back in method 1 releasing lock 1 27 As you can see, if an object already has a ``__lock__`` attribute, its ``acquire()`` and ``release()`` methods are called around the execution of the wrapped method. (Note that this means the lock must be re-entrant: that is, you must use a ``threading.RLock`` or something similar to it, if you explicitly create your own ``__lock__`` attribute.) If the object has no ``__lock__``, the decorator creates a ``threading.RLock`` and tries to add it to the object's ``__dict__``:: >>> del ts.__lock__ >>> ts.method1(27) in method 1 in method 2 back in method 1 27 >>> ts.__lock__ <_RLock(None, 0)> (This means, by the way, that if you want to use synchronized methods on an object with no ``__dict__``, you must explicitly include a ``__lock__`` slot and initialize it yourself when the object is created.) The ``struct()`` Decorator -------------------------- The ``struct()`` decorator creates a tuple subclass with the same name and docstring as the decorated function. The class will have read-only properties with the same names as the function's arguments, and the ``repr()`` of its instances will look like a call to the original function:: >>> from peak.util.decorators import struct >>> def X(a,b,c): ... """Demo type""" ... return a,b,c >>> X = struct()(X) # can't use decorators above functions in doctests >>> v = X(1,2,3) >>> v X(1, 2, 3) >>> v.a 1 >>> v.b 2 >>> v.c 3 >>> help(X) # doctest: +NORMALIZE_WHITESPACE Help on class X: <BLANKLINE> class X(__builtin__.tuple) | Demo type | | Method resolution order: | X | __builtin__.tuple | __builtin__.object | | Methods defined here: | | __repr__(self) | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(cls, *args, **kw) | | ---------------------------------------------------------------------- | ...s defined here: | | a... | | b... | | c... | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __args__ = ['a', 'b', 'c']... | | __star__ = None | | ... The function should return a tuple of values in the same order as its argument names, as it will be used by the class' constructor. The function can perform validation, add defaults, and/or do type conversions on the values. If the function takes a ``*``, argument, it should flatten this argument into the result tuple, e.g.:: >>> def pair(first, *rest): ... return (first,) + rest >>> pair = struct()(pair) >>> p = pair(1,2,3,4) >>> p pair(1, 2, 3, 4) >>> p.first 1 >>> p.rest (2, 3, 4) Internally, ``struct`` types are actually tuples:: >>> print tuple.__repr__(X(1,2,3)) (<class 'X'>, 1, 2, 3) The internal representation contains the struct's type object, so that structs of different types will not compare equal to each other:: >>> def Y(a,b,c): ... return a,b,c >>> Y = struct()(Y) >>> X(1,2,3) == X(1,2,3) True >>> Y(1,2,3) == Y(1,2,3) True >>> X(1,2,3) == Y(1,2,3) False Note, however, that this means that if you want to unpack them or otherwise access members directly, you must include the type entry, or use a slice:: >>> a, b, c = X(1,2,3) # wrong Traceback (most recent call last): ... ValueError: too many values to unpack >>> t, a, b, c = X(1,2,3) # right >>> a, b, c = X(1,2,3)[1:] # ok, if perhaps a bit unintuitive The ``struct()`` decorator takes optional mixin classes (as positional arguments), and dictionary entries (as keyword arguments). The mixin classes will be placed before ``tuple`` in the resulting class' bases, and the dictionary entries will be placed in the class' dictionary. These entries take precedence over any default entries (e.g. methods, properties, docstring, etc.) that are created by the ``struct()`` decorator:: >>> class Mixin(object): ... __slots__ = [] ... def foo(self): print "bar" >>> def demo(a, b): ... return a, b >>> demo = struct(Mixin, reversed=property(lambda self: self[:0:-1]))(demo) >>> demo(1,2).foo() bar >>> demo(3,4).reversed (4, 3) >>> demo.__mro__ (<class 'demo'>, <class ...Mixin...>, <type 'tuple'>, <type 'object'>) Note that using mixin classes will result in your new class' instances having a ``__dict__`` attribute, unless they are new-style classes that set ``__slots__`` to an empty list. And if they have any slots other than ``__weakref__`` or ``__dict__``, this will cause a type error due to layout conflicts. In general, it's best to use mixins only for adding methods, not data. Finally, note that if your function returns a non-tuple result, it will be returned from the class' constructor. This is sometimes useful:: >>> def And(a, b): ... if a is None: return b ... return a, b >>> And = struct()(And) >>> And(1,2) And(1, 2) >>> And(None, 27) 27 Signature Matching ------------------ One of the drawbacks to using function decorators is that using ``help()`` or other documentation tools on a decorated function usually produces unhelpful results:: >>> def before_and_after(message): ... def decorator(func): ... def decorated(*args, **kw): ... print "before", message ... try: ... return func(*args, **kw) ... finally: ... print "after", message ... return decorated ... return decorator >>> def foo(bar, baz): ... """Here's some doc""" >>> foo(1,2) >>> help(foo) # doctest: -NORMALIZE_WHITESPACE Help on function foo: ... foo(bar, baz) Here's some doc ... >>> decorated_foo = before_and_after("hello")(foo) >>> decorated_foo(1,2) before hello after hello >>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE Help on function decorated: ... decorated(*args, **kw) ... So DecoratorTools provides you with two tools to improve this situation. First, the ``rewrap()`` function provides a simple way to match the signature, module, and other characteristics of the original function:: >>> from peak.util.decorators import rewrap >>> def before_and_after(message): ... def decorator(func): ... def before_and_after(*args, **kw): ... print "before", message ... try: ... return func(*args, **kw) ... finally: ... print "after", message ... return rewrap(func, before_and_after) ... return decorator >>> decorated_foo = before_and_after("hello")(foo) >>> decorated_foo(1,2) before hello after hello >>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE Help on function foo: ... foo(bar, baz) Here's some doc ... The ``rewrap()`` function returns you a new function object with the same attributes (including ``__doc__``, ``__dict__``, ``__name__``, ``__module__``, etc.) as the original function, but which calls the decorated function. If you want the same signature but don't want the overhead of another calling level at runtime, you can use the ``@template_function`` decorator instead. The downside to this approach, however, is that it is more complex to use. So, this approach is only recommended for more performance-intensive decorators, that you've already debugged using the ``rewrap()`` approach. But if you need to use it, the appropriate usage looks something like this:: >>> from peak.util.decorators import template_function >>> def before_and_after2(message): ... def decorator(func): ... [template_function()] # could also be @template_function in 2.4 ... def before_and_after2(__func, __message): ... return ''' ... print "before", __message ... try: ... return __func($args) ... finally: ... print "after", __message ... ''' ... return before_and_after2(func, message) ... return decorator >>> decorated_foo = before_and_after2("hello")(foo) >>> decorated_foo(1,2) before hello after hello >>> help(decorated_foo) # doctest: -NORMALIZE_WHITESPACE Help on function foo: ... foo(bar, baz) Here's some doc ... As you can see, the process is somewhat more complex. Any values you wish the generated function to be able to access (aside from builtins) must be declared as arguments to the decorating function, and all arguments must be named so as not to conflict with the names of any of the decorated function's arguments. The function template must return a static string that will be compiled into a new function by DecoratorTools. The returned string must either fit on one line, or begin with a newline and have its contents indented by at least two spaces. The string ``$args`` may be used one or more times in the returned string, whenever calling the original function. The first argument of the decorating function must always be the original function. Note, however, that function template is only called *once*, in order to get this string, and it's called with dummy arguments. So the function must not attempt to actually *use* any of its arguments, and must **always return a static string**. Any attempt to insert the supplied arguments into the template will result in an error:: >>> def broken_decorator(func): ... [template_function()] ... def broken_template(__func, __message): ... # This doesn't work; don't do this: ... return ''' ... print "before %(__message)s" ... try: ... return __func($args) ... finally: ... print "after %(__message)s" ... ''' % locals() ... return broken_template(func, "test") >>> broken_decorator(foo) Traceback (most recent call last): ... RuntimeError: template functions must return a static string! Debugging Generated Code ------------------------ Both ``rewrap()`` and ``template_function`` are implemented using code generation and runtime compile/exec operations. Normally, such things are frowned on in Python because Python's debugging tools don't work on generated code. In particular, tracebacks and pdb don't show the source code of functions compiled from strings... or do they? Let's see:: >>> def raiser(x, y="blah"): ... raise TypeError(y) >>> def call_and_print_error(func, *args, **kw): ... # This function is necessary because we want to test the error ... # output, but doctest ignores a lot of exception detail, and ... # won't show the non-errror output unless we do it this way ... # ... try: ... func(*args, **kw) ... except: ... import sys, traceback ... print ''.join(traceback.format_exception(*sys.exc_info())) >>> call_and_print_error(before_and_after("error")(raiser), 99) before error after error Traceback (most recent call last): File "<doctest README.txt[...]>", line ..., in call_and_print_error func(*args, **kw) File "<peak.util.decorators.rewrap wrapping raiser at 0x...>", line 3, in raiser def raiser(x, y): return __decorated(x, y) File ..., line ..., in before_and_after return func(*args, **kw) File "<doctest README.txt[...]>", line 2, in raiser raise TypeError(y) TypeError: blah >>> call_and_print_error(before_and_after2("error")(raiser), 99) before error after error Traceback (most recent call last): File "<doctest README.txt[...]>", line ..., in call_and_print_error func(*args, **kw) File "<before_and_after2 wrapping raiser at 0x...>", line 6, in raiser return __func(x, y) File "<doctest README.txt[...]>", line 2, in raiser raise TypeError(y) TypeError: blah As you can see, both decorators' tracebacks include lines from the pseudo-files "<peak.util.decorators.rewrap wrapping raiser at 0x...>" and "<before_and_after2 wrapping raiser at 0x...>" (the hex id's of the corresponding objects are omitted here). This is because DecoratorTools adds information to the Python ``linecache`` module, and tracebacks and pdb both use the ``linecache`` module to get source lines. Any tools that use ``linecache``, either directly or indirectly, will therefore be able to display this information for generated code. If you'd like to be able to use this feature for your own code generation or non-file-based code (e.g. Python source loaded from a database, etc.), you can use the ``cache_source()`` function:: >>> from peak.util.decorators import cache_source >>> from linecache import getline >>> demo_source = "line 1\nline 2\nline 3" >>> cache_source("<dummy filename 1>", demo_source) >>> getline("<dummy filename 1>", 3) 'line 3' The function requires a dummy filename, which must be globally unique. An easy way to ensure uniqueness is to include the ``id()`` of an object that will exist at least as long as the source code being cached. Also, if you have such an object, and it is weak-referenceable, you can supply it as a third argument to ``cache_source()``, and when that object is garbage collected the source will be removed from the ``linecache`` cache. If you're generating a function from the source, the function object itself is ideal for this purpose (and it's what ``rewrap()`` and ``template_function`` do):: >>> def a_function(): pass # just an object to "own" the source >>> cache_source("<dummy filename 2>", demo_source, a_function) >>> getline("<dummy filename 2>", 1) 'line 1\n' >>> del a_function # GC should now clean up the cache >>> getline("<dummy filename 2>", 1) '' Advanced Decorators ------------------- The ``decorate_assignment()`` function can be used to create standalone "magic" decorators that work in Python 2.3 and up, and which can also be used to decorate arbitrary assignments as well as function/method definitions. For example, if you wanted to create an ``info(**kwargs)`` decorator that could be used either with or without an ``@``, you could do something like:: from peak.util.decorators import decorate_assignment def info(**kw): def callback(frame, name, func, old_locals): func.__dict__.update(kw) return func return decorate_assignment(callback) info(foo="bar") # will set dummy.foo="bar"; @info() would also work def dummy(blah): pass As you can see, this ``info()`` decorator can be used without an ``@`` sign for backward compatibility with Python 2.3. It can also be used *with* an ``@`` sign, for forward compatibility with Python 2.4 and up. Here's a more detailed reference for the ``decorate_assignment()`` API: decorate_assignment(callback [, depth=2, frame=None]) Call `callback(frame, name, value, old_locals)` on next assign in `frame`. If a `frame` isn't supplied, a frame is obtained using ``sys._getframe(depth)``. `depth` defaults to 2 so that the correct frame is found when ``decorate_assignment()`` is called from a decorator factory that was called in the target usage context. When `callback` is invoked, `old_locals` contains the frame's local variables as they were *before* the assignment, thus allowing the callback to access the previous value of the assigned variable, if any. The callback's return value will become the new value of the variable. `name` will contain the name of the variable being created or modified, and `value` will be the thing being decorated. `frame` is the Python frame in which the assignment occurred. This function also returns a decorator function for forward-compatibility with Python 2.4 ``@`` syntax. Note, however, that if the returned decorator is used with Python 2.4 ``@`` syntax, the callback `name` argument may be ``None`` or incorrect, if the `value` is not the original function (e.g. when multiple decorators are used). "Meta-less" Classes ------------------- Sometimes, you want to create a base class in a library or program that will use the data defined in subclasses in some way, or that needs to customize the way instances are created (*without* overriding ``__new__``). Since Python 2.2, the standard way to accomplish these things is by creating a custom metaclass and overriding ``__new__``, ``__init__``, or ``__call__``. Unfortunately, however, metaclasses don't play well with others. If two frameworks define independent metaclasses, and a library or application mixes classes from those frameworks, the user will have to create a *third* metaclass to sort out the differences. For this reason, it's best to minimize the number of distinct metaclasses in use. ``peak.util.decorators`` therefore provides a kind of "one-size-fits-all" metaclass, so that most of the common use cases for metaclasses can be handled with just one metaclass. In PEAK and elsewhere, metaclasses are most commonly used to perform some sort of operations during class creation (metaclass ``__new__`` and ``__init__``), or instance creation (metaclass ``__call__``, wrapping the class-level ``__new__`` and ``__init__``). Therefore, the ``classy`` base class allows subclasses to implement one or more of the three classmethods ``__class_new__``, ``__class_init__``, and ``__class_call__``. The "one-size-fits-all" metaclass delegates these operations to the class, so that you don't need a custom metaclass for every class with these behaviors. Thus, as long as all your custom metaclasses derive from ``classy.__class__``, you can avoid any metaclass conflicts during multiple inheritance. Here's an example of ``classy`` in use:: >>> from peak.util.decorators import classy, decorate >>> class Demo(classy): ... """Look, ma! No metaclass!""" ... ... def __class_new__(meta, name, bases, cdict, supr): ... cls = supr()(meta, name, bases, cdict, supr) ... print "My metaclass is", meta ... print "And I am", cls ... return cls ... ... def __class_init__(cls, name, bases, cdict, supr): ... supr()(cls, name, bases, cdict, supr) ... print "Initializing", cls ... ... decorate(classmethod) # could be just @classmethod for 2.4+ ... def __class_call__(cls, *args, **kw): ... print "before creating instance" ... ob = super(Demo, cls).__class_call__(*args, **kw) ... print "after creating instance" ... return ob ... ... def __new__(cls, *args, **kw): ... print "new called with", args, kw ... return super(Demo, cls).__new__(cls) ... ... def __init__(self, *args, **kw): ... print "init called with", args, kw My metaclass is <class 'peak.util.decorators.classy_class'> And I am <class 'Demo'> Initializing <class 'Demo'> >>> d = Demo(1,2,a="b") before creating instance new called with (1, 2) {'a': 'b'} init called with (1, 2) {'a': 'b'} after creating instance Note that because ``__class_new__`` and ``__class_init__`` are called *before* the name ``Demo`` has been bound to the class under creation, ``super()`` cannot be used in these methods. So, they use a special calling convention, where the last argument (``supr``) is the ``next()`` method of an iterator that yields base class methods in mro order. In other words, calling ``supr()(..., supr)`` invokes the previous definition of the method. You MUST call this exactly *once* in your methods -- no more, no less. ``__class_call__`` is different, because it is called after the class already exists. Thus, it can be a normal ``classmethod`` and use ``super()`` in the standard way. Finally, note that any given ``classy`` subclass does NOT need to define all three methods; you can mix and match methods as needed. Just be sure to always use the ``supr`` argument (or ``super()`` in the case of ``__class_call__``). Utility/Introspection Functions ------------------------------- ``peak.util.decorators`` also exposes these additional utility and introspection functions that it uses internally: frameinfo(frame) Return a ``(kind, module, locals, globals)`` tuple for a frame The `kind` returned is a string, with one of the following values: * ``"exec"`` * ``"module"`` * ``"class"`` * ``"function call"`` * ``"unknown"`` The `module` returned is the Python module object whose globals are in effect for the frame, or ``None`` if the globals don't include a value for ``__name__``. metaclass_is_decorator(mc) Return truth if the given metaclass is a class decorator metaclass inserted into a class by ``decorate_class()``, or by another class decorator implementation that follows the same protocol (such as the one in ``zope.interface``). metaclass_for_bases(bases, explicit_mc=None) Given a sequence of 1 or more base classes and an optional explicit ``__metaclass__``, return the metaclass that should be used. This routine basically emulates what Python does to determine the metaclass when creating a class, except that it does *not* take a module-level ``__metaclass__`` into account, only the arguments as given. If there are no base classes, you should just directly use the module-level ``__metaclass__`` or ``types.ClassType`` if there is none. enclosing_frame(frame=None, level=3) Given a frame and/or stack level, skip upward past any DecoratorTools code frames. This function is used by ``decorate_class()`` and ``decorate_assignment()`` to ensure that any decorators calling them that were themselves invoked using ``decorate()``, won't end up looking at DecoratorTools code instead of the target. If you have a function that needs to be callable via ``decorate()`` and which inspects stack frames, you may need to use this function to access the right frame. Mailing List ------------ Please direct questions regarding this package to the PEAK mailing list; see http://www.eby-sarna.com/mailman/listinfo/PEAK/ for details.
PypiClean
/Fregger-0.10.7.tar.gz/Fregger-0.10.7/fregger/static/lang/tr.js
'use strict'; /* jshint quotmark: double */ window.SwaggerTranslator.learn({ "Warning: Deprecated":"Uyarı: Deprecated", "Implementation Notes":"Gerçekleştirim Notları", "Response Class":"Dönen Sınıf", "Status":"Statü", "Parameters":"Parametreler", "Parameter":"Parametre", "Value":"Değer", "Description":"Açıklama", "Parameter Type":"Parametre Tipi", "Data Type":"Veri Tipi", "Response Messages":"Dönüş Mesajı", "HTTP Status Code":"HTTP Statü Kodu", "Reason":"Gerekçe", "Response Model":"Dönüş Modeli", "Request URL":"İstek URL", "Response Body":"Dönüş İçeriği", "Response Code":"Dönüş Kodu", "Response Headers":"Dönüş Üst Bilgileri", "Hide Response":"Dönüşü Gizle", "Headers":"Üst Bilgiler", "Try it out!":"Dene!", "Show/Hide":"Göster/Gizle", "List Operations":"Operasyonları Listele", "Expand Operations":"Operasyonları Aç", "Raw":"Ham", "can't parse JSON. Raw result":"JSON çözümlenemiyor. Ham sonuç", "Model Schema":"Model Şema", "Model":"Model", "apply":"uygula", "Username":"Kullanıcı Adı", "Password":"Parola", "Terms of service":"Servis şartları", "Created by":"Oluşturan", "See more at":"Daha fazlası için", "Contact the developer":"Geliştirici ile İletişime Geçin", "api version":"api versiyon", "Response Content Type":"Dönüş İçerik Tipi", "fetching resource":"kaynak getiriliyor", "fetching resource list":"kaynak listesi getiriliyor", "Explore":"Keşfet", "Show Swagger Petstore Example Apis":"Swagger Petstore Örnek Api'yi Gör", "Can't read from server. It may not have the appropriate access-control-origin settings.":"Sunucudan okuma yapılamıyor. Sunucu access-control-origin ayarlarınızı kontrol edin.", "Please specify the protocol for":"Lütfen istenen adres için protokol belirtiniz", "Can't read swagger JSON from":"Swagger JSON bu kaynaktan okunamıyor", "Finished Loading Resource Information. Rendering Swagger UI":"Kaynak baglantısı tamamlandı. Swagger UI gösterime hazırlanıyor", "Unable to read api":"api okunamadı", "from path":"yoldan", "server returned":"sunucuya dönüldü" });
PypiClean
/MetPyQC-0.1.1-py3-none-any.whl/metpyqc/temporal.py
import pandas as pd import numpy as np def step_all(x, step_val_susp, step_val_wrong, flag_val_susp, flag_val_wrong): r""" Check the difference between consecutive observations. Parameters ---------- x : pd.DataFrame Dataframe to be tested (time, stations) step_val_susp : float step limit for suspect values. step_val_wrong : float step limit for wrong values. flag_val_susp: int integer representing flag values to be associated to suspect values. flag_val_wrong: int integer representing flag values to be associated to wrong values. Returns ------- flag : pd.DataFrame Dataframe with flags identifying values which fail the test. res : pd.DataFrame Dataframe with quantitative residuals from prescribed limits: positive values indicates suspect or wrong values. Warning ------- This function must be used with dataframes with homogeneous temporal resolution on the temporal index. Missing dates have to be filled with np.nan values. """ flag = pd.DataFrame(0, index=x.index, columns=x.columns, ) res = pd.DataFrame(0, index=x.index, columns=x.columns, ) prev = x.shift(-1) post = x.shift(+1) diff_prev = abs(x - prev) diff_post = abs(post - x) mask_step_wrong = ((diff_prev > step_val_wrong) | (diff_post > step_val_wrong)) mask_step_susp = (((diff_prev > step_val_susp) | (diff_post > step_val_susp)) & (~mask_step_wrong)) res_prev = diff_prev - step_val_susp res_post = diff_post - step_val_susp mask_res = (res_prev >= res_post) res[mask_res] = res_prev[mask_res] res[~mask_res] = res_post[~mask_res] flag[mask_step_susp] += flag_val_susp flag[mask_step_wrong] += flag_val_wrong return flag, res def step_seas(x, step_vals_susp, step_vals_wrong, flag_val_susp, flag_val_wrong): r""" Check the difference between consecutive observations by considering different limits for each season. Parameters ---------- x : pd.DataFrame Dataframe to be tested (time, stations) step_vals_susp : array_like, shape(4,) Array of step limits for suspect values for each season in this order: DJF (December, January, February),MAM (March, April, May), JJA (June, July, August), SON (September, October, November). step_vals_wrong : array_like, shape(4,) Array of step limits for wrong values for each season in this order: DJF (December, January, February),MAM (March, April, May), JJA (June, July, August), SON (September, October, November). flag_val_susp: int integer representing flag values to be associated to suspect values. flag_val_wrong: int integer representing flag values to be associated to wrong values. Returns ------- flag : pd.DataFrame Dataframe with flags identifying values which fail the test. res : pd.DataFrame Dataframe with quantitative residuals from prescribed limits: positive values indicates suspect or wrong values. Warning ------- This function must be used with dataframes with homogeneous temporal resolution on the temporal index. Missing dates have to be filled with np.nan values. """ flag = pd.DataFrame(0, index=x.index, columns=x.columns, ) res = pd.DataFrame(0, index=x.index, columns=x.columns, ) mask_djf = ((x.index.month == 12) | (x.index.month == 1) | (x.index.month == 2)) mask_mam = ((x.index.month == 3) | (x.index.month == 4) | (x.index.month == 5)) mask_jja = ((x.index.month == 6) | (x.index.month == 7) | (x.index.month == 8)) mask_son = ((x.index.month == 9) | (x.index.month == 10) | (x.index.month == 11)) mask_seas = [mask_djf, mask_mam, mask_jja, mask_son] for i in range(len(step_vals_susp)): x_seas = x.copy() x_seas[~mask_seas[i]] = np.nan flag_seas, res_seas = step_all(x_seas, step_vals_susp[i], step_vals_wrong[i], flag_val_susp, flag_val_wrong) flag[mask_seas[i]] = flag_seas res[mask_seas[i]] = res_seas return flag, res def persistence_noc(x, n, flag_val): r""" Not Observed Change (NOC) Persistence test to check minimum variability of a certain variable with respect to the previous n time steps. Parameters ---------- x : pd.DataFrame Dataframe to be tested (time, stations) n : int Number of previous time steps to be considered in the test. The value must be bigger than 1. flag_val: int integer representing flag values to be associated to suspect values. Returns ------- flag : pd.DataFrame Dataframe with flags identifying values which fail the test. res : pd.DataFrame Dataframe with quantitative residuals representing the maximum absolute difference between the selected observation and the preceding ones. As this value tends to zero, the selected observation indicates temporal persistence. Warning ------- This function must be used with dataframes with homogeneous temporal resolution on the temporal index. Missing dates have to be filled with np.nan values. """ flag = pd.DataFrame(0, index=x.index, columns=x.columns, ) prev1 = x.shift(+1) diff1 = abs(x - prev1) res = diff1.copy() mask_pers = (diff1 == 0) for i in range(2, n+1): prev_i = x.shift(+i) diff_i = abs(x - prev_i) mask_pers = (mask_pers & (diff_i == 0)) res = np.maximum(res, diff_i) flag[mask_pers] += flag_val return flag, res def persistence_var(x, window, perc_min, method, var_val_min, flag_val): r""" Minimum Variability Persistence test to check minimum allowed variability of a certain variable with respect to a certain time window. Parameters ---------- x : pd.DataFrame Dataframe to be tested (time, stations) window : int Number of hours over which evaluate temporal variability perc_min : int Minimum percentage of valid observations (not missing) in order to calculate temporal variability method : {'STD', 'MAX_MIN', 'IQR'} Method for calculating the temporal variability within the desired time window: standard deviation (STD), difference between absolute maximum and minimum values (MAX_MIN), interquartile range (IQR). var_val_min : float Minimum allowed variability for the selected variable within the defined time window flag_val: int integer representing flag values to be associated to suspect values. Returns ------- flag : pd.DataFrame Dataframe with flags identifying values which fail the test. res : pd.DataFrame Dataframe with quantitative residuals representing the difference between the actual variability and the minimum allowed variability. Positive values indicates suspect observations. Raises ------ Exception If the selected method is neither 'STD', 'MAX_MIN' nor 'IQR'. """ flag = pd.DataFrame(0, index=x.index, columns=x.columns, ) var_count = x.resample('{}H'.format(window)).count() var_perc = (var_count / window) * 100 mask_perc = (var_perc <= perc_min) if method == 'STD': std = x.resample('{}H'.format(window)).std() std_nan = std.copy() std_nan[mask_perc] = np.nan std_res = std_nan.resample('H').pad() mask_nan = np.isnan(x) mask_pers_std = ((std_res < var_val_min) & (~mask_nan)) flag[mask_pers_std] += flag_val res = var_val_min - std_res elif method == 'MAX_MIN': r = x.resample('{}H'.format(window)).max() - x.resample('{}H'.format(window)).min() r_nan = r.copy() r_nan[mask_perc] = np.nan r_res = r_nan.resample('H').pad() mask_nan = np.isnan(x) mask_pers_maxmin = ((r_res < var_val_min) & (~mask_nan)) flag[mask_pers_maxmin] += flag_val res = var_val_min - r_res elif method == 'IQR': r = x.resample('{}H'.format(window)).quantile(0.75) - x.resample('{}H'.format(window)).quantile(0.25) r_nan = r.copy() r_nan[mask_perc] = np.nan r_res = r_nan.resample('H').pad() mask_nan = np.isnan(x) mask_pers_iqr = ((r_res < var_val_min) & (~mask_nan)) flag[mask_pers_iqr] += flag_val res = var_val_min - r_res else: raise Exception('Selected method not found. Available methods are:' ' STD, MAX_MIN and IQR.') return flag, res def isolated(x, n, flag_val): r""" Check if an observation of rainfall (or other discrete variables) is isolated with respect to the adjacent measures (in time). Parameters ---------- x : pd.DataFrame Dataframe to be tested (time, stations) n : int Number of previous and following time steps to be considered in the test. The value must be bigger than 1. flag_val: int integer representing flag values to be associated to suspect values. Returns ------- flag : pd.DataFrame Dataframe with flags identifying values which fail the test. res : pd.DataFrame Dataframe with quantitative residuals representing the difference between the selected observation and the sum of the adjacent ones. As this value increases, the selected observation is more isolated with respect to neighbors. Warning ------- This function must be used with dataframes with homogeneous temporal resolution on the temporal index. Missing dates have to be filled with np.nan values. """ flag = pd.DataFrame(0, index=x.index, columns=x.columns, ) prev1 = x.shift(+1) post1 = x.shift(-1) sum = prev1+post1 mask_isol = ((x != 0) & (sum == 0)) for i in range(2, n+1): prev_i = x.shift(+i) post_i = x.shift(-i) sum_i = prev_i + post_i mask_isol = (mask_isol & (sum_i == 0)) sum = sum + sum_i res = x - sum flag[mask_isol] += flag_val return flag, res
PypiClean
/OASYS1-SHADOWFOUR-0.0.4.tar.gz/OASYS1-SHADOWFOUR-0.0.4/orangecontrib/shadow4/widgets/sources/ow_wiggler.py
import sys import time # from syned.storage_ring.magnetic_structures.wiggler import Wiggler # # from orangecontrib.shadow4.widgets.gui.ow_light_source import OWLightSource # # from orangecontrib.syned.widgets.gui.ow_light_source import OWLightSource # # from orangecontrib.shadow4.widgets.gui.ow_generic_element import GenericElement # from orangecontrib.shadow4.widgets.gui.ow_automatic_element import AutomaticElement from orangecontrib.shadow4.widgets.gui.ow_electron_beam import OWElectronBeam from orangecontrib.shadow4.widgets.gui.plots import plot_data1D from oasys.widgets import gui as oasysgui from orangewidget import gui as orangegui from orangewidget.settings import Setting # from syned.storage_ring.electron_beam import ElectronBeam from shadow4.syned.magnetic_structure_1D_field import MagneticStructure1DField from syned.storage_ring.magnetic_structures.wiggler import Wiggler from shadow4.sources.wiggler.source_wiggler import SourceWiggler from shadow4.compatibility.beam3 import Beam3 from srxraylib.sources.srfunc import wiggler_spectrum # for the moment, use ShadowOui beam... from orangecontrib.shadow.util.shadow_objects import ShadowBeam class OWWiggler(OWElectronBeam): name = "Wiggler Light Source" description = "Wiggler Light Source" icon = "icons/wiggler.png" priority = 3 # inputs = [("Trigger", TriggerOut, "sendNewBeam")] outputs = [{"name":"Beam", "type":ShadowBeam, "doc":"Shadow Beam", "id":"beam"}] magnetic_field_source = Setting(0) number_of_periods = Setting(1) k_value = Setting(10.0) id_period = Setting(0.010) file_with_b_vs_y = Setting("/Users/srio/Oasys/BM_multi7.b") file_with_harmonics = Setting("tmp.h") shift_x_flag = Setting(4) shift_x_value =Setting(0.0) shift_betax_flag = Setting(4) shift_betax_value = Setting(0.0) e_min = Setting(0.1) e_max = Setting(0.1) n_rays = Setting(100) plot_wiggler_graph = 1 workspace_units_to_cm = 1.0 shadowoui_neam = None def __init__(self): super().__init__() tab_wiggler = oasysgui.createTabPage(self.tabs_control_area, "Wiggler Setting") # wiggler parameters box left_box_3 = oasysgui.widgetBox(tab_wiggler, "Wiggler Parameters", addSpace=False, orientation="vertical", height=200) orangegui.comboBox(left_box_3, self, "magnetic_field_source", label="Type", items=["conventional/sinusoidal", "B from file (y [m], Bz [T])", "B from harmonics"], callback=self.set_visibility, labelWidth=220, orientation="horizontal") oasysgui.lineEdit(left_box_3, self, "number_of_periods", "Number of Periods", labelWidth=260, tooltip="Number of Periods", valueType=int, orientation="horizontal") self.conventional_sinusoidal_box = oasysgui.widgetBox(left_box_3, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.conventional_sinusoidal_box, self, "k_value", "K value", labelWidth=260, tooltip="K value", valueType=float, orientation="horizontal") oasysgui.lineEdit(self.conventional_sinusoidal_box, self, "id_period", "ID period [m]", labelWidth=260, tooltip="ID period [m]", valueType=float, orientation="horizontal") self.b_from_file_box = oasysgui.widgetBox(left_box_3, "", addSpace=False, orientation="vertical") file_box = oasysgui.widgetBox(self.b_from_file_box, "", addSpace=True, orientation="horizontal", height=25) self.le_file_with_b_vs_y = oasysgui.lineEdit(file_box, self, "file_with_b_vs_y", "File/Url with B vs Y", labelWidth=150, tooltip="File/Url with B vs Y", valueType=str, orientation="horizontal") orangegui.button(file_box, self, "...", callback=self.selectFileWithBvsY) self.b_from_harmonics_box = oasysgui.widgetBox(left_box_3, "", addSpace=False, orientation="vertical") oasysgui.lineEdit(self.b_from_harmonics_box, self, "id_period", "ID period [m]", labelWidth=260, tooltip="ID period [m]", valueType=float, orientation="horizontal") file_box = oasysgui.widgetBox(self.b_from_harmonics_box, "", addSpace=True, orientation="horizontal", height=25) self.le_file_with_harmonics = oasysgui.lineEdit(file_box, self, "file_with_harmonics", "File/Url with harmonics", labelWidth=150, tooltip="File/Url with harmonics", valueType=str, orientation="horizontal") orangegui.button(file_box, self, "...", callback=self.selectFileWithHarmonics) # Electron Box left_box_10 = oasysgui.widgetBox(tab_wiggler, "Electron Initial Condition", addSpace=False, orientation="vertical", height=200) orangegui.comboBox(left_box_10, self, "shift_betax_flag", label="Shift Transversal Velocity", items=["No shift", "Half excursion", "Minimum", "Maximum", "Value at zero", "User value"], callback=self.set_ShiftBetaXFlag, labelWidth=260, orientation="horizontal") self.shift_betax_value_box = oasysgui.widgetBox(left_box_10, "", addSpace=False, orientation="vertical", height=25) self.shift_betax_value_box_hidden = oasysgui.widgetBox(left_box_10, "", addSpace=False, orientation="vertical", height=25) oasysgui.lineEdit(self.shift_betax_value_box, self, "shift_betax_value", "Value", labelWidth=260, valueType=float, orientation="horizontal") orangegui.comboBox(left_box_10, self, "shift_x_flag", label="Shift Transversal Coordinate", items=["No shift", "Half excursion", "Minimum", "Maximum", "Value at zero", "User value"], callback=self.set_ShiftXFlag, labelWidth=260, orientation="horizontal") self.shift_x_value_box = oasysgui.widgetBox(left_box_10, "", addSpace=False, orientation="vertical", height=25) self.shift_x_value_box_hidden = oasysgui.widgetBox(left_box_10, "", addSpace=False, orientation="vertical", height=25) oasysgui.lineEdit(self.shift_x_value_box, self, "shift_x_value", "Value [m]", labelWidth=260, valueType=float, orientation="horizontal") self.set_ShiftXFlag() self.set_ShiftBetaXFlag() # Calculation Box left_box_11 = oasysgui.widgetBox(tab_wiggler, "Sampling rays", addSpace=False, orientation="vertical", height=200) oasysgui.lineEdit(left_box_11, self, "e_min", "Min photon energy [eV]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(left_box_11, self, "e_max", "Max photon energy [eV]", labelWidth=260, valueType=float, orientation="horizontal") oasysgui.lineEdit(left_box_11, self, "n_rays", "Number of rays", labelWidth=260, valueType=int, orientation="horizontal") self.set_ShiftXFlag() self.set_ShiftBetaXFlag() # wiggler plots self.add_specific_wiggler_plots() self.set_visibility() orangegui.rubber(self.controlArea) def add_specific_wiggler_plots(self): wiggler_plot_tab = oasysgui.widgetBox(self.main_tabs, addToLayout=0, margin=4) self.main_tabs.insertTab(1, wiggler_plot_tab, "Wiggler Plots") view_box = oasysgui.widgetBox(wiggler_plot_tab, "Plotting Style", addSpace=False, orientation="horizontal") view_box_1 = oasysgui.widgetBox(view_box, "", addSpace=False, orientation="vertical", width=350) self.wiggler_view_type_combo = orangegui.comboBox(view_box_1, self, "plot_wiggler_graph", label="Plot Graphs?", labelWidth=220, items=["No", "Yes"], callback=self.plot_widget_all, sendSelectedValue=False, orientation="horizontal") self.wiggler_tab = [] self.wiggler_tabs = oasysgui.tabWidget(wiggler_plot_tab) current_tab = self.wiggler_tabs.currentIndex() size = len(self.wiggler_tab) indexes = range(0, size) for index in indexes: self.wiggler_tabs.removeTab(size-1-index) self.wiggler_tab = [ orangegui.createTabPage(self.wiggler_tabs, "Magnetic Field"), orangegui.createTabPage(self.wiggler_tabs, "Electron Curvature"), orangegui.createTabPage(self.wiggler_tabs, "Electron Velocity"), orangegui.createTabPage(self.wiggler_tabs, "Electron Trajectory"), orangegui.createTabPage(self.wiggler_tabs, "Wiggler Spectrum"), orangegui.createTabPage(self.wiggler_tabs, "Wiggler Spectral power") ] for tab in self.wiggler_tab: tab.setFixedHeight(self.IMAGE_HEIGHT) tab.setFixedWidth(self.IMAGE_WIDTH) self.wiggler_plot_canvas = [None, None, None, None, None, None] self.wiggler_tabs.setCurrentIndex(current_tab) def set_PlotGraphs(self): pass def set_visibility(self): self.conventional_sinusoidal_box.setVisible(self.magnetic_field_source == 0) self.b_from_file_box.setVisible(self.magnetic_field_source == 1) self.b_from_harmonics_box.setVisible(self.magnetic_field_source == 2) def selectFileWithBvsY(self): self.le_file_with_b_vs_y.setText(oasysgui.selectFileFromDialog(self, self.file_with_b_vs_y, "Open File With B vs Y")) def selectFileWithHarmonics(self): self.le_file_with_harmonics.setText(oasysgui.selectFileFromDialog(self, self.file_with_harmonics, "Open File With Harmonics")) def set_ShiftXFlag(self): self.shift_x_value_box.setVisible(self.shift_x_flag==5) self.shift_x_value_box_hidden.setVisible(self.shift_x_flag!=5) def set_ShiftBetaXFlag(self): self.shift_betax_value_box.setVisible(self.shift_betax_flag==5) self.shift_betax_value_box_hidden.setVisible(self.shift_betax_flag!=5) # def get_magnetic_structure(self): # return Wiggler(K_horizontal=self.K_horizontal, # K_vertical=self.K_vertical, # period_length=self.period_length, # number_of_periods=self.number_of_periods) # # def check_magnetic_structure_instance(self, magnetic_structure): # if not isinstance(magnetic_structure, Wiggler): # raise ValueError("Magnetic Structure is not a Wiggler") # # def populate_magnetic_structure(self, magnetic_structure): # if not isinstance(magnetic_structure, Wiggler): # raise ValueError("Magnetic Structure is not a Wiggler") # # self.K_horizontal = magnetic_structure._K_horizontal # self.K_vertical = magnetic_structure._K_vertical # self.period_length = magnetic_structure._period_length # self.number_of_periods = magnetic_structure._number_of_periods def run_shadow4(self): nTrajPoints = 501 # # syned # syned_electron_beam = self.get_syned_electron_beam() print(syned_electron_beam.info()) # B from file if self.magnetic_field_source == 0: syned_wiggler = Wiggler( K_vertical=self.k_value, K_horizontal=0.0, period_length=self.id_period, number_of_periods=self.number_of_periods ) elif self.magnetic_field_source == 1: syned_wiggler = MagneticStructure1DField.initialize_from_file(self.file_with_b_vs_y) elif self.magnetic_field_source == 2: raise Exception(NotImplemented) print(syned_wiggler.info()) sw = SourceWiggler() sourcewiggler = SourceWiggler(name="test", syned_electron_beam=syned_electron_beam, syned_wiggler=syned_wiggler, flag_emittance=True, emin=self.e_min, emax=self.e_max, ng_e=100, ng_j=nTrajPoints) if self.e_min == self.e_max: sourcewiggler.set_energy_monochromatic(self.e_min) # sourcewiggler.set_electron_initial_conditions_by_label(velocity_label="value_at_zero", # position_label="value_at_zero",) sourcewiggler.set_electron_initial_conditions( shift_x_flag=self.shift_x_flag, shift_x_value=self.shift_x_value, shift_betax_flag=self.shift_betax_flag, shift_betax_value=self.shift_betax_value) # sourcewiggler.calculate_radiation() print(sourcewiggler.info()) t00 = time.time() print(">>>> starting calculation...") rays = sourcewiggler.calculate_rays(NRAYS=self.n_rays) t11 = time.time() - t00 print(">>>> time for %d rays: %f s, %f min, " % (self.n_rays, t11, t11 / 60)) print(">>> Results of calculate_radiation") print(">>> trajectory.shape: ",sourcewiggler._result_trajectory.shape) print(">>> cdf: ", sourcewiggler._result_cdf.keys()) calculate_spectrum = True if calculate_spectrum: e, f, w = wiggler_spectrum(sourcewiggler._result_trajectory, enerMin=self.e_min, enerMax=self.e_max, nPoints=500, electronCurrent=self.ring_current, outFile="", elliptical=False) # from srxraylib.plot.gol import plot # plot(e, f, xlog=False, ylog=False, show=False, # xtitle="Photon energy [eV]", ytitle="Flux [Photons/s/0.1%bw]", title="Flux") # plot(e, w, xlog=False, ylog=False, show=True, # xtitle="Photon energy [eV]", ytitle="Spectral Power [E/eV]", title="Spectral Power") beam = Beam3.initialize_from_array(rays) # # wiggler plots # self.plot_widget_all(sourcewiggler,e,f,w) self.shadowoui_beam = ShadowBeam(oe_number = 0, beam = beam, number_of_rays = 0) self.plot_shadow_all() self.send("Beam", self.shadowoui_beam) def set_PlotQuality(self): self.plot_shadow_all() def plot_shadow_all(self): if self.view_type == 2: for slot_index in range(6): current_item = self.tab[slot_index].layout().itemAt(0) self.tab[slot_index].layout().removeItem(current_item) tmp = oasysgui.QLabel() # TODO: is there a better way to clean this?????????????????????? self.tab[slot_index].layout().addWidget(tmp) elif self.view_type == 1: raise Exception(NotImplemented) else: self.plot_xy(self.shadowoui_beam, 10, 1, 3, 0, "(X,Z)", "X", "Z", xum="um", yum="um", is_footprint=False) self.plot_xy(self.shadowoui_beam, 10, 4, 6, 1, "(X',Z')", "X'", "Z'", xum="urad", yum="urad", is_footprint=False) self.plot_xy(self.shadowoui_beam, 10, 1, 4, 2, "(X,X')", "X", "X'", xum="um", yum="urad", is_footprint=False) self.plot_xy(self.shadowoui_beam, 10, 3, 6, 3, "(Z,Z')", "Z", "Z'", xum="um", yum="urad", is_footprint=False) self.plot_histo(self.shadowoui_beam,10,11,4,"Photon energy","Photon energy [eV]","Intensity [a.u.]",xum="eV") def plot_widget_all(self,sourcewiggler=None,e=None,f=None,w=None): print(">>>>>>>>>>> ",sourcewiggler) import numpy if self.plot_wiggler_graph == 0: for wiggler_plot_slot_index in range(6): current_item = self.wiggler_tab[wiggler_plot_slot_index].layout().itemAt(0) self.wiggler_tab[wiggler_plot_slot_index].layout().removeItem(current_item) plot_widget_id = oasysgui.QLabel() # TODO: is there a better way to clean this?????????????????????? self.wiggler_tab[wiggler_plot_slot_index].layout().addWidget(plot_widget_id) else: if sourcewiggler is None: return self.plot_widget_item(sourcewiggler._result_trajectory[1, :],sourcewiggler._result_trajectory[7, :],0, title="Magnetic Field",xtitle="y [m]",ytitle="B [T]") self.plot_widget_item(sourcewiggler._result_trajectory[1, :],sourcewiggler._result_trajectory[6, :],1, title="Electron curvature",xtitle="y [m]",ytitle="cirvature [m^-1]") self.plot_widget_item(sourcewiggler._result_trajectory[1, :],sourcewiggler._result_trajectory[3, :],2, title="Electron velocity",xtitle="y [m]",ytitle="BetaX") self.plot_widget_item(sourcewiggler._result_trajectory[1, :],sourcewiggler._result_trajectory[0, :],3, title="Electron trajectory",xtitle="y [m]",ytitle="x [m]") self.plot_widget_item(e,f,4, title="Wiggler spectrum (current = %5.1f)"%self.ring_current, xtitle="Photon energy [eV]",ytitle=r"Photons/s/0.1%bw") self.plot_widget_item(e,w,5, title="Wiggler spectrum (current = %5.1f)"%self.ring_current, xtitle="Photon energy [eV]",ytitle="Spectral power [W/eV]") def plot_widget_item(self,x,y,wiggler_plot_slot_index,title="",xtitle="",ytitle=""): self.wiggler_tab[wiggler_plot_slot_index].layout().removeItem(self.wiggler_tab[wiggler_plot_slot_index].layout().itemAt(0)) plot_widget_id = plot_data1D(x.copy(),y.copy(),title=title,xtitle=xtitle,ytitle=ytitle,symbol='.') self.wiggler_tab[wiggler_plot_slot_index].layout().addWidget(plot_widget_id) if __name__ == "__main__": from PyQt5.QtWidgets import QApplication a = QApplication(sys.argv) ow = OWWiggler() ow.show() a.exec_() #ow.saveSettings()
PypiClean
/ConSSL-0.0.1-py3-none-any.whl/CSSL/datamodules/vocdetection_datamodule.py
from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from pytorch_lightning import LightningDataModule from torch.utils.data import DataLoader from CSSL.utils import _TORCHVISION_AVAILABLE from CSSL.utils.warnings import warn_missing_pkg if _TORCHVISION_AVAILABLE: from torchvision import transforms as transform_lib from torchvision.datasets import VOCDetection else: # pragma: no cover warn_missing_pkg('torchvision') class Compose(object): """ Like `torchvision.transforms.compose` but works for (image, target) """ def __init__(self, transforms: List[Callable], image_transforms: Optional[Callable] = None) -> None: self.transforms = transforms self.image_transforms = image_transforms def __call__(self, image: Any, target: Any) -> Tuple[torch.Tensor, torch.Tensor]: for t in self.transforms: image, target = t(image, target) if self.image_transforms: image = self.image_transforms(image) return image, target def _collate_fn(batch: List[torch.Tensor]) -> tuple: return tuple(zip(*batch)) CLASSES = ( "__background__ ", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor", ) def _prepare_voc_instance(image: Any, target: Dict[str, Any]): """ Prepares VOC dataset into appropriate target for fasterrcnn https://github.com/pytorch/vision/issues/1097#issuecomment-508917489 """ anno = target["annotation"] boxes = [] classes = [] area = [] iscrowd = [] objects = anno["object"] if not isinstance(objects, list): objects = [objects] for obj in objects: bbox = obj["bndbox"] bbox = [int(bbox[n]) - 1 for n in ["xmin", "ymin", "xmax", "ymax"]] boxes.append(bbox) classes.append(CLASSES.index(obj["name"])) iscrowd.append(int(obj["difficult"])) area.append((bbox[2] - bbox[0]) * (bbox[3] - bbox[1])) boxes = torch.as_tensor(boxes, dtype=torch.float32) classes = torch.as_tensor(classes) area = torch.as_tensor(area) iscrowd = torch.as_tensor(iscrowd) image_id = anno["filename"][5:-4] image_id = torch.as_tensor([int(image_id)]) target = {} target["boxes"] = boxes target["labels"] = classes target["image_id"] = image_id # for conversion to coco api target["area"] = area target["iscrowd"] = iscrowd return image, target class VOCDetectionDataModule(LightningDataModule): """ TODO(teddykoker) docstring """ name = "vocdetection" def __init__( self, data_dir: str, year: str = "2012", num_workers: int = 16, normalize: bool = False, shuffle: bool = False, pin_memory: bool = False, drop_last: bool = False, *args: Any, **kwargs: Any, ) -> None: if not _TORCHVISION_AVAILABLE: # pragma: no cover raise ModuleNotFoundError( 'You want to use VOC dataset loaded from `torchvision` which is not installed yet.' ) super().__init__(*args, **kwargs) self.year = year self.data_dir = data_dir self.num_workers = num_workers self.normalize = normalize self.shuffle = shuffle self.pin_memory = pin_memory self.drop_last = drop_last @property def num_classes(self) -> int: """ Return: 21 """ return 21 def prepare_data(self) -> None: """ Saves VOCDetection files to data_dir """ VOCDetection(self.data_dir, year=self.year, image_set="train", download=True) VOCDetection(self.data_dir, year=self.year, image_set="val", download=True) def train_dataloader( self, batch_size: int = 1, image_transforms: Union[List[Callable], Callable] = None ) -> DataLoader: """ VOCDetection train set uses the `train` subset Args: batch_size: size of batch transforms: custom transforms """ transforms = [_prepare_voc_instance] image_transforms = image_transforms or self.train_transforms or self._default_transforms() transforms = Compose(transforms, image_transforms) dataset = VOCDetection(self.data_dir, year=self.year, image_set="train", transforms=transforms) loader = DataLoader( dataset, batch_size=batch_size, shuffle=self.shuffle, num_workers=self.num_workers, drop_last=self.drop_last, pin_memory=self.pin_memory, collate_fn=_collate_fn, ) return loader def val_dataloader(self, batch_size: int = 1, image_transforms: Optional[List[Callable]] = None) -> DataLoader: """ VOCDetection val set uses the `val` subset Args: batch_size: size of batch transforms: custom transforms """ transforms = [_prepare_voc_instance] image_transforms = image_transforms or self.train_transforms or self._default_transforms() transforms = Compose(transforms, image_transforms) dataset = VOCDetection(self.data_dir, year=self.year, image_set="val", transforms=transforms) loader = DataLoader( dataset, batch_size=batch_size, shuffle=False, num_workers=self.num_workers, drop_last=self.drop_last, pin_memory=self.pin_memory, collate_fn=_collate_fn, ) return loader def _default_transforms(self) -> Callable: if self.normalize: voc_transforms = transform_lib.Compose([ transform_lib.ToTensor(), transform_lib.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) else: voc_transforms = transform_lib.Compose([transform_lib.ToTensor()]) return voc_transforms
PypiClean
/Eskapade_Spark-1.0.0-py3-none-any.whl/eskapadespark/links/sparkhister.py
import numpy as np from eskapade import process_manager, StatusCode, DataStore, Link class SparkHister(Link): """Defines the content of link SparkHister.""" # TODO: Fix class docstring. def __init__(self, name='HiveHister'): """Initialize link instance. Store the configuration of link SparkHister. :param str name: name of link :param str read_key: key of data to read from data store :param str store_key: key of data to store in data store :param list columns: columns of the Spark dataframe to make a histogram from :param dict bins: the bin edges of the histogram :param bool convert_for_mongo: if True the data structure of the result is converted so it can be stored in mongo """ Link.__init__(self, name) self.read_key = None self.columns = None self.store_key = None self.bins = {} self.convert_for_mongo = False self.save_as_csv_style = False self.save_as_json_style = True def initialize(self): """Initialize the link.""" return StatusCode.Success def execute(self): """Execute the link.""" ds = process_manager.service(DataStore) spark_df = ds[self.read_key] result = {} for c in self.columns: pos = spark_df.columns.index(c) self.logger.debug("Processing column: {col}.", col=c) result[c] = spark_df.map(lambda r: r[pos]).histogram(self.bins.get(c, 25)) # --- NOTE: this depends on how the data will be read by the BI tool # - SQL/Tableau requires a row per histogram bin # - QlikSense supports a more JSON-like style by putting an entire histogram in single row if self.convert_for_mongo: r = [] for c in self.columns: hist = result[c] if self.save_as_csv_style: try: binedges = np.asarray(hist[0]) bincenters = 0.5 * (binedges[1:] + binedges[:-1]) binvalues = hist[1] except Exception: self.logger.error("Could not extract values from histogram data.") # --- row per bin for i in range(len(binvalues)): r.append({'column': c, 'bin': bincenters[i], 'value': binvalues[i]}) # --- alternatively row per histogram if self.save_as_json_style: r.append({'column': c, 'edges': hist[0], 'values': hist[1]}) result = r ds[self.store_key] = result return StatusCode.Success def finalize(self): """Finalize the link.""" return StatusCode.Success
PypiClean
/Canto-0.9.8.tar.gz/Canto-0.9.8/canto_next/config.py
#Canto - RSS reader backend # Copyright (C) 2016 Jack Miller <jack@codezen.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. from .locks import feed_lock, config_lock, tag_lock, watch_lock from .encoding import locale_enc from .transform import eval_transform from .feed import allfeeds, CantoFeed from .tag import alltags import traceback import logging import codecs import json import os import re log = logging.getLogger("CONFIG") default_config =\ { "defaults" : { "rate" : 10, "keep_time" : 86400, "keep_unread" : False, "global_transform" : "filter_read" }, "feeds" : [ { "name" : "Canto", "url" : "http://codezen.org/canto-ng/feed/" }, { "name" : "Slashdot", "url" : "http://rss.slashdot.org/slashdot/Slashdot" }, { "name" : "Reddit", "url": "http://reddit.com/.rss" } ] } def parse_locks(): config_lock.acquire_write() feed_lock.acquire_write() tag_lock.acquire_write() watch_lock.acquire_read() def parse_unlocks(): config_lock.release_write() feed_lock.release_write() tag_lock.release_write() watch_lock.release_read() class CantoConfig(): def init(self, filename, shelf): self.filename = filename self.shelf = shelf self.json = {} self.defaults_validators = [ ("rate", self.validate_int, False), ("keep_time", self.validate_int, False), ("keep_unread", self.validate_bool, False), ("global_transform", self.validate_set_transform, False), ] self.defaults_defaults = { "rate" : 10, "keep_time" : 86400, "keep_unread" : False, "global_transform" : "None", } self.feed_validators = [ ("name", self.validate_unique_feed_name, True), ("url", self.validate_unique_url, True), ("rate", self.validate_int, False), ("keep_time", self.validate_int, False), ("keep_unread", self.validate_bool, False), ("username", self.validate_string, False), ("password", self.validate_string, False), ] self.feed_defaults = {} self.tag_validators = [ ("transform", self.validate_set_transform, False), ("extra_tags", self.validate_string_list, False), ] self.tag_defaults = {} def reset(self): allfeeds.reset() alltags.reset() self.errors = {} self.final = {} # Accumulators for verifying uniqueness self.urls = [] self.feed_names = [] def parse(self, fromfile=True, changes={}): parse_locks() # Since we host client config too, check if # we should do a reparse. we_care = False for header in [ "feeds", "tags", "defaults" ]: if header in changes: if header == "tags": for tag in changes["tags"]: if list(changes["tags"][tag].keys()) != [ "collapsed" ]: we_care = True if we_care: break else: we_care = True break if fromfile or we_care: self.reset() if fromfile: self.read_config() if self.validate(): self.instantiate() if not fromfile: self.write() elif not fromfile: self.write() parse_unlocks() def read_config(self): if not os.path.exists(self.filename): log.info("No config found, writing default.") self.json = default_config.copy() self.write() c = codecs.open(self.filename, "rb", locale_enc) self.json = json.load(c) c.close() log.info("Read %s" % self.filename) log.debug("Parsed into: %s", self.json) def error(self, ident, val, error): if ident in self.errors: self.errors[ident].append((val, error)) else: self.errors[ident] = [(val, error)] def _validate_unique(self, ident, value, accumulator, desc): if not self.validate_string(ident, value): return False if value in accumulator: self.error(ident, value, "%s already used!" % (desc,)) return False accumulator.append(value) return (True, value) def validate_unique_url(self, ident, value): return self._validate_unique(ident, value, self.urls, "URL") def validate_unique_feed_name(self, ident, value): return self._validate_unique(ident, value, self.feed_names, "Feed name") def validate_bool(self, ident, value): if type(value) != bool: self.error(ident, value, "Not boolean!") return False return (True, value) def validate_int(self, ident, value): if type(value) != int: self.error(ident, value, "Not integer!") return False return (True, value) def validate_string(self, ident, value): if type(value) != str: self.error(ident, value, "Not unicode!") return False return (True, value) def validate_string_list(self, ident, value): if type(value) != list: self.error(ident, value, "Not list!") return False for idx, item in enumerate(value): item_ident = ident + ("[%d]" % idx) if not self.validate_string(item_ident, item): return False return (True, value) # Unfortunately, this must return the value, so that the JSON doesn't get # tainted with non-serializable values. def validate_set_transform(self, ident, value): try: r = eval_transform(value) except Exception as e: tb = traceback.format_exc() msg = "\n" + "".join(tb) self.error(ident, value, "Invalid transform" + msg) return (True, "None") return (True, value) def validate_dict(self, ident_prefix, d, validators): section_invalidated = False for rgx, validator, required in validators: r = re.compile(rgx) found = False for opt in list(d.keys()): match = r.match(opt) if not match: continue found = True ident = ident_prefix + ("[%s]" % opt) ret = validator(ident, d[opt]) if not ret: if required: self.error(ident, d[opt],\ "Set but invalid and required!") section_invalidated = True else: self.error(ident, d[opt], "Set but invalid!") del d[opt] else: # NOTE: we're ignoring the first tuple, it should # always be True. If it wasn't for the fact that (val,) # looks terrible that could also be returned from the # validators. d[opt] = ret[1] if not found and required: ident = ident_prefix + "[%s]" % rgx self.error(ident, None,\ "No matching value found on required option!") section_invalidated = True if section_invalidated: break return not section_invalidated # Validate validates only what exists in self.final, it does not make # substitutions for defaults. That's done on instantiation. def validate(self): # Because we have to ensure that all items in the JSON are # simple, we can do this cheap deepcopy intead of importing # copy or doing it ourselves. self.final = eval(repr(self.json), {}, {}) if "defaults" in self.final: good = self.validate_dict("[defaults]", self.final["defaults"], self.defaults_validators) if not good: del self.final["defaults"] if "tags" in self.final and not self.errors: for tag in list(self.final["tags"].keys()): good = self.validate_dict("[tags][" + tag + "]", self.final["tags"][tag], self.tag_validators) if not good: del self.final["tags"][tag] if "feeds" in self.final and not self.errors: for i, feed in enumerate(self.final["feeds"][:]): good = self.validate_dict("[feeds][%s]" % i, feed, self.feed_validators) if not good: self.final["feeds"].remove(feed) if self.errors: log.error("ERRORS:") for key in list(self.errors.keys()): log.error("%s:" % key) for value, error in self.errors[key]: log.error("\t%s -> %s" % (value, error)) return False log.info("Validated: %s" % self.final) return True # Create Tag and Feed objects based on final validated config def instantiate(self): if "defaults" in self.final: for k in self.defaults_defaults.keys(): if k not in self.final["defaults"]: self.final["defaults"][k] = self.defaults_defaults[k] else: self.final["defaults"] = self.defaults_defaults.copy() if "tags" in self.final: for tag in self.final["tags"]: defs = self.final["tags"][tag] if "transform" not in defs: defs["transform"] = "None" defs["transform"] = eval_transform(defs["transform"]) if "extra_tags" not in defs: defs["extra_tags"] = [] alltags.tag_transform(tag, defs["transform"]) alltags.set_extra_tags(tag, defs["extra_tags"]) # Feeds must be instantiated *after* tags, so tag settings like extra_tags # can rely on getting an add_tag for each item after all tag settings have # been handled. if "feeds" in self.final: for feed in self.final["feeds"]: # Mandatory arguments to CantoFeed for k in [ "rate", "keep_time", "keep_unread" ]: if k not in feed: feed[k] = self.final["defaults"][k] # Optional arguments in kwargs kws = {} for k in ["password", "username"]: if k in feed: kws[k] = feed[k] feed = CantoFeed(self.shelf, feed["name"],\ feed["url"], feed["rate"], feed["keep_time"], feed["keep_unread"], **kws) # Set global transform. self.global_transform = eval_transform(\ self.final["defaults"]["global_transform"]) # Delete settings from the JSON. Any key equal to "DELETE" will be removed, # keys that are lists will items removed if specified. def _delete(self, deletions, current): for key in list(deletions.keys()): # Nothing to do. if key not in current: continue # Delete surface fields. if deletions[key] == "DELETE": del current[key] # Delete potential fields in deeper dicts. elif type(deletions[key]) == dict: self._delete(deletions[key], current[key]) # If we've specified a list for and are operating on a list, # then eliminate those. elif type(deletions[key]) == list and\ type(current[key]) == list: log.debug("Deleting items from list lists:") log.debug("\\%s", deletions[key]) log.debug("\\%s", current[key]) for item in deletions[key]: if item in current[key]: current[key].remove(item) def delete(self, deletions): self._delete(deletions, self.json) def _merge(self, change, current): for key in list(change.keys()): # Move over missing keys if key not in current: current[key] = change[key] # Merge subsequent dicts, or overwrite if wrong types # (in a well-behaved merge that shouldn't happen) elif type(change[key]) == dict: if type(current[key]) != dict: log.warn("Type change! Old value of ['%s'] not dict." % (key,)) current[key] = change[key] else: self._merge(change[key], current[key]) # Merge lists (append change items not present in current and # potentially change their order based on the contents in change). elif type(change[key]) == list: if type(current[key]) != list: log.warn("Type change! Old value of ['%s'] not list." % (key, )) current[key] = change[key] else: log.debug("Merging lists:") log.debug("\\%s", change[key]) log.debug("\\%s", current[key]) # Any items not in change are prepended. This allows the # simple n-item append to work as expected, it allows the # sort case to work as expected, and gives consistent # behavior in the case of items unaccounted for in change. current[key] = [ i for i in current[key] if i not in change[key] ] +\ change[key] # Move over present else: current[key] = change[key] def merge(self, newconfigs): self._merge(newconfigs, self.json) def write(self): try: f = codecs.open(self.filename, "wb", locale_enc) json.dump(self.json, f, ensure_ascii=False, sort_keys=True, indent=4) finally: f.close() config = CantoConfig()
PypiClean
/Chula-0.13.3.tar.gz/Chula-0.13.3/chula/pager.py
class Pager(list): def __init__(self, offset, recordcount, limit=8, visiblepages=19): """ Create a new pager @param offset: 0 based representation of what to offset/skip by @type offset: Integer @param recordcount: 1 based representation of records available @type recordcount: Integer @param limit: 1 based representation of records to show per page @type limit: Integer @param visiblepages: 1 based representation of pages to show at a time @type visiblepages: Integer @return: List of dictionaries >>> from chula import pager >>> p = pager.Pager(0, 50) >>> p[0]['isselected'] True >>> p[0]['offset'] 0 >>> p = pager.Pager(30, 100, 5, 11) >>> p[0]['isselected'] False >>> p[0]['offset'] 5 """ super(Pager, self).__init__() if (visiblepages % 2) == 0: raise ValueError, 'visiblepages cannot be an even number' if recordcount < 1: return if offset < 0: raise ValueError, 'offset must be >= 0' elif offset >= recordcount: raise ValueError, 'offset must be < recordcount' currentpage = offset // limit # 0 based totalpages = ((recordcount - 1) // limit) + 1 # 1 based firstvisible = 0 # 0 based # If current page is more than half of total visiblepages, adjust # first page to avoid sliding too far to the right if currentpage > visiblepages // 2: firstvisible = currentpage - visiblepages // 2 # Initially set last page to first + visible lastvisible = firstvisible + visiblepages - 1 # If previous calculation made last page too high, calculate # first page by subtracting from the last if lastvisible > totalpages - 1: lastvisible = totalpages - 1 firstvisible = totalpages - visiblepages if totalpages <= visiblepages: firstvisible = 0 lastvisible = totalpages - 1 self.currentpage = currentpage for page in xrange(firstvisible, lastvisible + 1): self.append({'offset':page * limit, 'isselected':(page == currentpage), 'number':page * limit / limit + 1}) def render(self): return self
PypiClean
/Nuitka_winsvc-1.7.10-cp310-cp310-win_amd64.whl/nuitka/Variables.py
from abc import abstractmethod from nuitka.__past__ import getMetaClassBase, iterItems from nuitka.nodes.shapes.BuiltinTypeShapes import tshape_dict from nuitka.nodes.shapes.StandardShapes import tshape_unknown from nuitka.utils import Utils from nuitka.utils.InstanceCounters import ( counted_del, counted_init, isCountingInstances, ) complete = False class Variable(getMetaClassBase("Variable")): # We will need all of these attributes, since we track the global # state and cache some decisions as attributes. TODO: But in some # cases, part of the these might be moved to the outside. __slots__ = ( "variable_name", "owner", "version_number", "shared_users", "traces", "users", "writers", ) @counted_init def __init__(self, owner, variable_name): assert type(variable_name) is str, variable_name assert type(owner) not in (tuple, list), owner self.variable_name = variable_name self.owner = owner self.version_number = 0 self.shared_users = False self.traces = set() # Derived from all traces. self.users = None self.writers = None if isCountingInstances(): __del__ = counted_del() def finalize(self): del self.users del self.writers del self.traces del self.owner def __repr__(self): return "<%s '%s' of '%s'>" % ( self.__class__.__name__, self.variable_name, self.owner.getName(), ) @abstractmethod def getVariableType(self): pass def getDescription(self): return "variable '%s'" % self.variable_name def getName(self): return self.variable_name def getOwner(self): return self.owner def getEntryPoint(self): return self.owner.getEntryPoint() def getCodeName(self): var_name = self.variable_name var_name = var_name.replace(".", "$") var_name = Utils.encodeNonAscii(var_name) return var_name def allocateTargetNumber(self): self.version_number += 1 return self.version_number @staticmethod def isLocalVariable(): return False @staticmethod def isParameterVariable(): return False @staticmethod def isModuleVariable(): return False @staticmethod def isIncompleteModuleVariable(): return False @staticmethod def isTempVariable(): return False @staticmethod def isTempVariableBool(): return False @staticmethod def isLocalsDictVariable(): return False def addVariableUser(self, user): # Update the shared scopes flag. if user is not self.owner: self.shared_users = True # These are not really scopes, just shared uses. if ( user.isExpressionGeneratorObjectBody() or user.isExpressionCoroutineObjectBody() or user.isExpressionAsyncgenObjectBody() ): if self.owner is user.getParentVariableProvider(): return _variables_in_shared_scopes.add(self) def isSharedTechnically(self): if not self.shared_users: return False if not self.users: return False owner = self.owner.getEntryPoint() for user in self.users: user = user.getEntryPoint() while user is not owner and ( (user.isExpressionFunctionBody() and not user.needsCreation()) or user.isExpressionClassBodyBase() ): user = user.getParentVariableProvider() if user is not owner: return True return False def addTrace(self, variable_trace): self.traces.add(variable_trace) def removeTrace(self, variable_trace): self.traces.remove(variable_trace) def getTraces(self): """For debugging only""" return self.traces def updateUsageState(self): writers = set() users = set() for trace in self.traces: owner = trace.owner users.add(owner) if trace.isAssignTrace(): writers.add(owner) elif trace.isDeletedTrace() and owner is not self.owner: writers.add(owner) self.writers = writers self.users = users def hasAccessesOutsideOf(self, provider): if not self.owner.locals_scope.complete: return None elif self.users is None: return False elif provider in self.users: return len(self.users) > 1 else: return bool(self.users) def hasWritersOutsideOf(self, provider): if not self.owner.locals_scope.complete: return None elif self.writers is None: return False elif provider in self.writers: return len(self.writers) > 1 else: return bool(self.writers) def getMatchingAssignTrace(self, assign_node): for trace in self.traces: if trace.isAssignTrace() and trace.getAssignNode() is assign_node: return trace return None def getMatchingUnescapedAssignTrace(self, assign_node): found = None for trace in self.traces: if trace.isAssignTrace() and trace.getAssignNode() is assign_node: found = trace if trace.isEscapeTrace(): return None return found def getMatchingDelTrace(self, del_node): for trace in self.traces: if trace.isDeletedTrace() and trace.getDelNode() is del_node: return trace return None def getTypeShapes(self): result = set() for trace in self.traces: if trace.isAssignTrace(): result.add(trace.getAssignNode().getTypeShape()) elif trace.isUnknownTrace(): result.add(tshape_unknown) elif trace.isEscapeTrace(): result.add(tshape_unknown) elif trace.isInitTrace(): result.add(tshape_unknown) elif trace.isUnassignedTrace(): pass elif trace.isMergeTrace(): pass # TODO: Remove this and be not unknown. elif trace.isLoopTrace(): trace.getTypeShape().emitAlternatives(result.add) else: assert False, trace return result @staticmethod def onControlFlowEscape(trace_collection): """Mark the variable as escaped or unknown, or keep it depending on variable type.""" def removeKnowledge(self, trace_collection): """Remove knowledge for the variable marking as unknown or escaped.""" trace_collection.markActiveVariableAsEscaped(self) def removeAllKnowledge(self, trace_collection): """Remove all knowledge for the variable marking as unknown, or keep it depending on variable type.""" trace_collection.markActiveVariableAsUnknown(self) class LocalVariable(Variable): __slots__ = () def __init__(self, owner, variable_name): Variable.__init__(self, owner=owner, variable_name=variable_name) @staticmethod def isLocalVariable(): return True def initVariable(self, trace_collection): """Initialize variable in trace collection state.""" return trace_collection.initVariableUninitialized(self) if str is not bytes: def onControlFlowEscape(self, trace_collection): if self.hasWritersOutsideOf(trace_collection.owner) is not False: trace_collection.markClosureVariableAsUnknown(self) elif self.hasAccessesOutsideOf(trace_collection.owner) is not False: trace_collection.markActiveVariableAsEscaped(self) else: def onControlFlowEscape(self, trace_collection): if self.hasAccessesOutsideOf(trace_collection.owner) is not False: trace_collection.markActiveVariableAsEscaped(self) @staticmethod def getVariableType(): return "object" class ParameterVariable(LocalVariable): __slots__ = () def __init__(self, owner, parameter_name): LocalVariable.__init__(self, owner=owner, variable_name=parameter_name) def getDescription(self): return "parameter variable '%s'" % self.variable_name @staticmethod def isParameterVariable(): return True def initVariable(self, trace_collection): """Initialize variable in trace collection state.""" return trace_collection.initVariableInit(self) class ModuleVariable(Variable): __slots__ = () def __init__(self, module, variable_name): assert type(variable_name) is str, repr(variable_name) assert module.isCompiledPythonModule() Variable.__init__(self, owner=module, variable_name=variable_name) def __repr__(self): return "<ModuleVariable '%s' of '%s'>" % ( self.variable_name, self.owner.getFullName(), ) def getDescription(self): return "global variable '%s'" % self.variable_name @staticmethod def isModuleVariable(): return True def initVariable(self, trace_collection): """Initialize variable in trace collection state.""" return trace_collection.initVariableModule(self) def onControlFlowEscape(self, trace_collection): trace_collection.markActiveVariableAsUnknown(self) def removeKnowledge(self, trace_collection): """Remove knowledge for the variable marking as unknown or escaped.""" trace_collection.markActiveVariableAsUnknown(self) def isIncompleteModuleVariable(self): return not self.owner.locals_scope.complete def hasDefiniteWrites(self): if not self.owner.locals_scope.complete: return None else: return bool(self.writers) def getModule(self): return self.owner @staticmethod def getVariableType(): return "object" class TempVariable(Variable): __slots__ = () def __init__(self, owner, variable_name): Variable.__init__(self, owner=owner, variable_name=variable_name) def getDescription(self): return "temp variable '%s'" % self.variable_name @staticmethod def isTempVariable(): return True @staticmethod def getVariableType(): return "object" def initVariable(self, trace_collection): """Initialize variable in trace collection state.""" return trace_collection.initVariableUninitialized(self) @staticmethod def removeAllKnowledge(trace_collection): """Remove all knowledge for the variable marking as unknown, or keep it depending on variable type.""" # For temporary variables, the knowledge is not by name, so never gets # lost to outside star imports or exec/eval uses. class TempVariableBool(TempVariable): __slots__ = () def getDescription(self): return "temp bool variable '%s'" % self.variable_name @staticmethod def isTempVariableBool(): return True @staticmethod def getVariableType(): return "bool" class LocalsDictVariable(Variable): __slots__ = () def __init__(self, owner, variable_name): Variable.__init__(self, owner=owner, variable_name=variable_name) @staticmethod def isLocalsDictVariable(): return True @staticmethod def getVariableType(): return "object" def initVariable(self, trace_collection): """Initialize variable in trace collection state.""" if self.owner.getTypeShape() is tshape_dict: return trace_collection.initVariableUninitialized(self) else: return trace_collection.initVariableUnknown(self) def updateVariablesFromCollection(old_collection, new_collection, source_ref): # After removing/adding traces, we need to pre-compute the users state # information. touched_variables = set() loop_trace_removal = set() if old_collection is not None: for (variable, _version), variable_trace in iterItems( old_collection.getVariableTracesAll() ): variable.removeTrace(variable_trace) touched_variables.add(variable) if variable_trace.isLoopTrace(): loop_trace_removal.add(variable) if new_collection is not None: for (variable, _version), variable_trace in iterItems( new_collection.getVariableTracesAll() ): variable.addTrace(variable_trace) touched_variables.add(variable) if variable_trace.isLoopTrace(): if variable in loop_trace_removal: loop_trace_removal.remove(variable) # Release the memory, and prevent the "active" state from being ever # inspected, it's useless now. new_collection.variable_actives.clear() del new_collection.variable_actives for variable in touched_variables: variable.updateUsageState() if loop_trace_removal: if new_collection is not None: new_collection.signalChange( "var_usage", source_ref, lambda: "Loop variable '%s' usage ceased." % ",".join(variable.getName() for variable in loop_trace_removal), ) # To detect the Python2 shared variable deletion, that would be a syntax # error _variables_in_shared_scopes = set() def isSharedAmongScopes(variable): return variable in _variables_in_shared_scopes def releaseSharedScopeInformation(tree): # Singleton, pylint: disable=global-statement assert tree.isCompiledPythonModule() global _variables_in_shared_scopes _variables_in_shared_scopes = set( variable for variable in _variables_in_shared_scopes if variable.getOwner().getParentModule() is not tree )
PypiClean
/AWAKE_ANALYSIS_TOOLS-0.0.2-py3-none-any.whl/analyses/frame_analysis.py
import numpy as np import scipy.signal as sig from scipy.optimize import curve_fit from numpy.fft import fft ''' Class for analyzing images ''' class FrameAna(object): def __init__(self,frame=[],x_ax=[],y_ax=[],roi=[]): self.init_frame = frame self.init_xax = x_ax self.init_yax = y_ax self.frame = frame self.x_ax = x_ax self.y_ax = y_ax self.roi = roi self.bg_frame = np.array([]) self.bg_sub = False self.median_filter = False self.fit_gauss = False self.streak_width = 2.5 self.marker_lim = -3.5 self.nEmbed = 4096 self.frame_analyzed = False ''' Main image analysis method ''' def analyze_frame(self): # Find pixel sum of image before applying manipulations self.sum_all = self.frame.sum() # Cast image as float and apply median filter self.frame = self.frame.astype(float) # Subtract background image if self.bg_sub: if self.bg_frame.any(): if np.size(self.bg_frame) != np.size(self.frame): print('Warning: Background frame size does not match image frame size. Background not subtracted') else: self.frame = self.frame - self.bg_frame # Apply median filter if self.median_filter: self.frame = sig.medfilt2d(self.frame) # Extract ROI and relevant portions of axes self.x_ind = (self.x_ax >= self.roi[0]) & (self.x_ax <= self.roi[1]) self.y_ind = (self.y_ax >= self.roi[2]) & (self.y_ax <= self.roi[3]) #self.y_ind = np.flipud(self.y_ind) #print(self.y_ind.shape) self.frame = np.flipud(self.frame) self.frame = self.frame[np.ix_(self.y_ind,self.x_ind)] #print self.x_ax = self.x_ax[self.x_ind] #self.y_ind = np.flipud(self.y_ind) self.y_ax = self.y_ax[self.y_ind] #print(self.y_ax[0]) #print(self.y_ax[-1]) # Get frame min and max self.min = np.amin(self.frame) self.max = np.amax(self.frame) # Find pixel sum and projections of ROI'd image self.sum_proc = self.frame.sum() self.proj_x = self.frame.mean(0) self.proj_y = self.frame.mean(1) # Find centroid and RMS self.xBar,self.xRMS = self.profile_moments('x') self.yBar,self.yRMS = self.profile_moments('y') self.xMax = np.max(self.proj_x) self.xMin = np.min(self.proj_x) self.yMax = np.max(self.proj_y) self.yMin = np.min(self.proj_y) # Perform Gaussian fits if self.fit_gauss: self.gaussFit('x') self.gaussFit('y') self.frame_analyzed = True self.frame = np.flipud(self.frame) ''' Streak Analysis Method ''' def streak_ana(self): if not self.frame_analyzed: print('Must run analyze_frame first.') return # Extract axes centroid and image self.t_ax = np.linspace(self.y_ax[0],self.y_ax[-1],len(self.y_ax)) #self.t_ax = self.y_ax # Create lineout and bands for FFT if self.fit_gauss: xc = self.mean_x xs = self.sig_x else: xc = self.xBar xs = self.xRMS # xl is lower band, xh, is the upper band, and xc is the center line xl = xc - xs*self.streak_width xh = xc + xs*self.streak_width x_ind = (self.x_ax > xl) & (self.x_ax < xh) c_ind = np.argmin(min(abs(self.x_ax-xc))) # Orig profs oBand = self.frame[:,x_ind].mean(1) oLine = self.frame[:,c_ind] oOutb = self.frame[:,~x_ind].mean(1) # New interpolation band = np.interp(self.t_ax,self.y_ax,oBand) line = np.interp(self.t_ax,self.y_ax,oLine) outb = np.interp(self.t_ax,self.y_ax,oOutb) hann_band = np.hanning(len(band))*band hann_line = np.hanning(len(line))*line hann_outb = np.hanning(len(outb))*outb # Create FFT axis nsamp = len(self.t_ax) s_max = round(nsamp/2) dt = self.t_ax[1]-self.t_ax[0] #dt = np.mean(np.diff(self.t_ax)) f_max = 1/dt full_ax = np.linspace(0,f_max,nsamp) f_ax = 1000*full_ax[0:s_max] # Create FFT embed arb = self.nEmbed embed = np.zeros(arb) embed[(round(arb/2)-round(nsamp/2)):(round(arb/2)+round(nsamp/2))] = hann_band pad_ax = np.linspace(0,f_max,arb) f_pad = 1000*pad_ax[0:round(arb/2)] # FFT the data fb = fft(band) fl = fft(line) fo = fft(outb) hb = fft(hann_band) hl = fft(hann_line) ho = fft(hann_outb) he = fft(embed) # Get the absolute value of the FFT fftb = abs(fb[0:s_max]) fftl = abs(fl[0:s_max]) ffto = abs(fo[0:s_max]) hftb = abs(hb[0:s_max]) hftl = abs(hl[0:s_max]) hfto = abs(ho[0:s_max]) hfte = abs(he[0:round(arb/2)]) # Store the results self.inner_band = band self.center_line = line self.outer_band = outb self.hann_band = hann_band self.hann_line = hann_line self.hann_outb = hann_outb self.f_ax = f_ax self.band_fft = fftb self.line_fft = fftl self.outer_fft = ffto self.band_hft = hftb self.line_hft = hftl self.outer_hft = hfto self.embed_hft = hfte self.f_pad = f_pad self.band_ref = [xl, xc, xh] ''' Streak Analysis Method ''' def marker_ana(self): if not self.frame_analyzed: print('Must run analyze_frame first.') return new_frame = np.array(self.init_frame.astype(float)) self.m_ind = (self.init_xax < self.marker_lim) marker_area = new_frame[np.ix_(self.y_ind,self.m_ind)] mark_area = sig.medfilt2d(marker_area) self.m_ax = np.linspace(self.y_ax[0],self.y_ax[-1],len(self.y_ax)) self.proj_m = np.interp(self.m_ax,self.y_ax,mark_area.mean(1)) self.mark_ind = np.argmax(self.proj_m) self.mark_val = self.y_ax[self.mark_ind] self.gaussFit('m') ''' Generate COGs. Default Function ''' def profile_moments(self,axis): if axis == 'x': no_zero = self.proj_x - min(self.proj_x) cent = no_zero.dot(self.x_ax)/no_zero.sum() rms = np.sqrt(no_zero.dot((self.x_ax-cent)**2)/no_zero.sum()) elif axis == 'y': no_zero = self.proj_y - min(self.proj_y) cent = no_zero.dot(self.y_ax)/no_zero.sum() rms = np.sqrt(no_zero.dot((self.y_ax-cent)**2)/no_zero.sum()) return cent, rms ''' Define Gaussian Shape ''' def gaussian(self, x, amp, cen, wid, off): return amp * np.exp(-(x-cen)**2 /(2*wid**2)) + off ''' Fit Gaussian. Not called by default ''' def gaussFit(self,axis): if axis == 'x': guess = [self.xMax-self.xMin,self.xBar,self.xRMS,self.xMin] #print(guess) try: result,pcov = curve_fit(self.gaussian,self.x_ax,self.proj_x,guess) result[2] = abs(result[2]) fit = self.gaussian(self.x_ax, *result) except: print('Failed to fit in '+axis+'-direction') result = [0,0,0,0] fit = np.zeros(np.shape(self.x_ax)) self.amp_x = result[0] self.mean_x = result[1] self.sig_x = result[2] self.off_x = result[3] self.fit_x = fit elif axis == 'y': guess = [self.yMax-self.yMin,self.yBar,self.yRMS,self.yMin] #print(guess) try: result,pcov = curve_fit(self.gaussian,self.y_ax,self.proj_y,guess) result[2] = abs(result[2]) fit = self.gaussian(self.y_ax, *result) except: print('Failed to fit in '+axis+'-direction') result = [0,0,0,0] fit = np.zeros(np.shape(self.y_ax)) self.amp_y = result[0] self.mean_y = result[1] self.sig_y = result[2] self.off_y = result[3] self.fit_y = fit elif axis == 'm': guess = [np.max(self.proj_m)-np.min(self.proj_m),self.mark_val,10,np.min(self.proj_m)] #print(guess) try: result,pcov = curve_fit(self.gaussian,self.y_ax,self.proj_m,guess) result[2] = abs(result[2]) fit = self.gaussian(self.y_ax, *result) except: print('Failed to fit in '+axis+'-direction') result = [0,0,0,0] fit = np.zeros(np.shape(self.y_ax)) self.amp_m = result[0] self.mean_m = result[1] self.sig_m = result[2] self.off_m = result[3] self.fit_m = fit
PypiClean
/Choco-1.0.5.tar.gz/Choco-1.0.5/choco/runtime.py
from choco import errors, util, compat from choco.compat import compat_builtins import sys class Context(object): """Provides runtime namespace, output buffer, and various callstacks for templates. See :ref:`runtime_toplevel` for detail on the usage of :class:`.Context`. """ def __init__(self, buffer, **data): self._buffer_stack = [buffer] self._data = data self._kwargs = data.copy() self._with_template = None self._outputting_as_unicode = None self.namespaces = {} # "capture" function which proxies to the # generic "capture" function self._data['capture'] = compat.partial(capture, self) # "caller" stack used by def calls with content self.caller_stack = self._data['caller'] = CallerStack() def _set_with_template(self, t): self._with_template = t illegal_names = t.reserved_names.intersection(self._data) if illegal_names: raise errors.NameConflictError( "Reserved words passed to render(): %s" % ", ".join(illegal_names)) @property def lookup(self): """Return the :class:`.TemplateLookup` associated with this :class:`.Context`. """ return self._with_template.lookup @property def kwargs(self): """Return the dictionary of top level keyword arguments associated with this :class:`.Context`. This dictionary only includes the top-level arguments passed to :meth:`.Template.render`. It does not include names produced within the template execution such as local variable names or special names such as ``self``, ``next``, etc. The purpose of this dictionary is primarily for the case that a :class:`.Template` accepts arguments via its ``<%page>`` tag, which are normally expected to be passed via :meth:`.Template.render`, except the template is being called in an inheritance context, using the ``body()`` method. :attr:`.Context.kwargs` can then be used to propagate these arguments to the inheriting template:: ${next.body(**context.kwargs)} """ return self._kwargs.copy() def push_caller(self, caller): """Push a ``caller`` callable onto the callstack for this :class:`.Context`.""" self.caller_stack.append(caller) def pop_caller(self): """Pop a ``caller`` callable onto the callstack for this :class:`.Context`.""" del self.caller_stack[-1] def keys(self): """Return a list of all names established in this :class:`.Context`.""" return list(self._data.keys()) def __getitem__(self, key): if key in self._data: return self._data[key] else: return compat_builtins.__dict__[key] def _push_writer(self): """push a capturing buffer onto this Context and return the new writer function.""" buf = util.FastEncodingBuffer() self._buffer_stack.append(buf) return buf.write def _pop_buffer_and_writer(self): """pop the most recent capturing buffer from this Context and return the current writer after the pop. """ buf = self._buffer_stack.pop() return buf, self._buffer_stack[-1].write def _push_buffer(self): """push a capturing buffer onto this Context.""" self._push_writer() def _pop_buffer(self): """pop the most recent capturing buffer from this Context.""" return self._buffer_stack.pop() def get(self, key, default=None): """Return a value from this :class:`.Context`.""" return self._data.get(key, compat_builtins.__dict__.get(key, default)) def write(self, string): """Write a string to this :class:`.Context` object's underlying output buffer.""" self._buffer_stack[-1].write(string) def writer(self): """Return the current writer function.""" return self._buffer_stack[-1].write def _copy(self): c = Context.__new__(Context) c._buffer_stack = self._buffer_stack c._data = self._data.copy() c._kwargs = self._kwargs c._with_template = self._with_template c._outputting_as_unicode = self._outputting_as_unicode c.namespaces = self.namespaces c.caller_stack = self.caller_stack return c def _locals(self, d): """Create a new :class:`.Context` with a copy of this :class:`.Context`'s current state, updated with the given dictionary. The :attr:`.Context.kwargs` collection remains unaffected. """ if not d: return self c = self._copy() c._data.update(d) return c def _clean_inheritance_tokens(self): """create a new copy of this :class:`.Context`. with tokens related to inheritance state removed.""" c = self._copy() x = c._data x.pop('self', None) x.pop('parent', None) x.pop('next', None) return c class CallerStack(list): def __init__(self): self.nextcaller = None def __nonzero__(self): return self.__bool__() def __bool__(self): return len(self) and self._get_caller() and True or False def _get_caller(self): # this method can be removed once # codegen MAGIC_NUMBER moves past 7 return self[-1] def __getattr__(self, key): return getattr(self._get_caller(), key) def _push_frame(self): frame = self.nextcaller or None self.append(frame) self.nextcaller = None return frame def _pop_frame(self): self.nextcaller = self.pop() class Undefined(object): """Represents an undefined value in a template. All template modules have a constant value ``UNDEFINED`` present which is an instance of this object. """ def __str__(self): raise NameError("Undefined") def __nonzero__(self): return self.__bool__() def __bool__(self): return False UNDEFINED = Undefined() STOP_RENDERING = "" class LoopStack(object): """a stack for LoopContexts that implements the context manager protocol to automatically pop off the top of the stack on context exit """ def __init__(self): self.stack = [] def _enter(self, iterable): self._push(iterable) return self._top def _exit(self): self._pop() return self._top @property def _top(self): if self.stack: return self.stack[-1] else: return self def _pop(self): return self.stack.pop() def _push(self, iterable): new = LoopContext(iterable) if self.stack: new.parent = self.stack[-1] return self.stack.append(new) def __getattr__(self, key): raise errors.RuntimeException("No loop context is established") def __iter__(self): return iter(self._top) class LoopContext(object): """A magic loop variable. Automatically accessible in any ``% for`` block. See the section :ref:`loop_context` for usage notes. :attr:`parent` -> :class:`.LoopContext` or ``None`` The parent loop, if one exists. :attr:`index` -> `int` The 0-based iteration count. :attr:`reverse_index` -> `int` The number of iterations remaining. :attr:`first` -> `bool` ``True`` on the first iteration, ``False`` otherwise. :attr:`last` -> `bool` ``True`` on the last iteration, ``False`` otherwise. :attr:`even` -> `bool` ``True`` when ``index`` is even. :attr:`odd` -> `bool` ``True`` when ``index`` is odd. """ def __init__(self, iterable): self._iterable = iterable self.index = 0 self.parent = None def __iter__(self): for i in self._iterable: yield i self.index += 1 @util.memoized_instancemethod def __len__(self): return len(self._iterable) @property def reverse_index(self): return len(self) - self.index - 1 @property def first(self): return self.index == 0 @property def last(self): return self.index == len(self) - 1 @property def even(self): return not self.odd @property def odd(self): return bool(self.index % 2) def cycle(self, *values): """Cycle through values as the loop progresses. """ if not values: raise ValueError("You must provide values to cycle through") return values[self.index % len(values)] class _NSAttr(object): def __init__(self, parent): self.__parent = parent def __getattr__(self, key): ns = self.__parent while ns: if hasattr(ns.module, key): return getattr(ns.module, key) else: ns = ns.inherits raise AttributeError(key) class Namespace(object): """Provides access to collections of rendering methods, which can be local, from other templates, or from imported modules. To access a particular rendering method referenced by a :class:`.Namespace`, use plain attribute access: .. sourcecode:: choco ${some_namespace.foo(x, y, z)} :class:`.Namespace` also contains several built-in attributes described here. """ def __init__(self, name, context, callables=None, inherits=None, populate_self=True, calling_uri=None): self.name = name self.context = context self.inherits = inherits if callables is not None: self.callables = dict([(c.__name__, c) for c in callables]) callables = () module = None """The Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, i.e. the generated module for the template. """ template = None """The :class:`.Template` object referenced by this :class:`.Namespace`, if any. """ context = None """The :class:`.Context` object for this :class:`.Namespace`. Namespaces are often created with copies of contexts that contain slightly different data, particularly in inheritance scenarios. Using the :class:`.Context` off of a :class:`.Namespace` one can traverse an entire chain of templates that inherit from one-another. """ filename = None """The path of the filesystem file used for this :class:`.Namespace`'s module or template. If this is a pure module-based :class:`.Namespace`, this evaluates to ``module.__file__``. If a template-based namespace, it evaluates to the original template file location. """ uri = None """The URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. This is the equivalent of :attr:`.Template.uri`. """ _templateuri = None @util.memoized_property def attr(self): """Access module level attributes by name. This accessor allows templates to supply "scalar" attributes which are particularly handy in inheritance relationships. .. seealso:: :ref:`inheritance_attr` :ref:`namespace_attr_for_includes` """ return _NSAttr(self) def get_namespace(self, uri): """Return a :class:`.Namespace` corresponding to the given ``uri``. If the given ``uri`` is a relative URI (i.e. it does not contain a leading slash ``/``), the ``uri`` is adjusted to be relative to the ``uri`` of the namespace itself. This method is therefore mostly useful off of the built-in ``local`` namespace, described in :ref:`namespace_local`. In most cases, a template wouldn't need this function, and should instead use the ``<%namespace>`` tag to load namespaces. However, since all ``<%namespace>`` tags are evaluated before the body of a template ever runs, this method can be used to locate namespaces using expressions that were generated within the body code of the template, or to conditionally use a particular namespace. """ key = (self, uri) if key in self.context.namespaces: return self.context.namespaces[key] else: ns = TemplateNamespace(uri, self.context._copy(), templateuri=uri, calling_uri=self._templateuri) self.context.namespaces[key] = ns return ns def get_template(self, uri): """Return a :class:`.Template` from the given ``uri``. The ``uri`` resolution is relative to the ``uri`` of this :class:`.Namespace` object's :class:`.Template`. """ return _lookup_template(self.context, uri, self._templateuri) def get_cached(self, key, **kwargs): """Return a value from the :class:`.Cache` referenced by this :class:`.Namespace` object's :class:`.Template`. The advantage to this method versus direct access to the :class:`.Cache` is that the configuration parameters declared in ``<%page>`` take effect here, thereby calling up the same configured backend as that configured by ``<%page>``. """ return self.cache.get(key, **kwargs) @property def cache(self): """Return the :class:`.Cache` object referenced by this :class:`.Namespace` object's :class:`.Template`. """ return self.template.cache def include_file(self, uri, **kwargs): """Include a file at the given ``uri``.""" _include_file(self.context, uri, self._templateuri, **kwargs) def _populate(self, d, l): for ident in l: if ident == '*': for (k, v) in self._get_star(): d[k] = v else: d[ident] = getattr(self, ident) def _get_star(self): if self.callables: for key in self.callables: yield (key, self.callables[key]) def __getattr__(self, key): if key in self.callables: val = self.callables[key] elif self.inherits: val = getattr(self.inherits, key) else: raise AttributeError( "Namespace '%s' has no member '%s'" % (self.name, key)) setattr(self, key, val) return val class TemplateNamespace(Namespace): """A :class:`.Namespace` specific to a :class:`.Template` instance.""" def __init__(self, name, context, template=None, templateuri=None, callables=None, inherits=None, populate_self=True, calling_uri=None): self.name = name self.context = context self.inherits = inherits if callables is not None: self.callables = dict([(c.__name__, c) for c in callables]) if templateuri is not None: self.template = _lookup_template(context, templateuri, calling_uri) self._templateuri = self.template.module._template_uri elif template is not None: self.template = template self._templateuri = template.module._template_uri else: raise TypeError("'template' argument is required.") if populate_self: lclcallable, lclcontext = \ _populate_self_namespace(context, self.template, self_ns=self) @property def module(self): """The Python module referenced by this :class:`.Namespace`. If the namespace references a :class:`.Template`, then this module is the equivalent of ``template.module``, i.e. the generated module for the template. """ return self.template.module @property def filename(self): """The path of the filesystem file used for this :class:`.Namespace`'s module or template. """ return self.template.filename @property def uri(self): """The URI for this :class:`.Namespace`'s template. I.e. whatever was sent to :meth:`.TemplateLookup.get_template()`. This is the equivalent of :attr:`.Template.uri`. """ return self.template.uri def _get_star(self): if self.callables: for key in self.callables: yield (key, self.callables[key]) def get(key): callable_ = self.template._get_def_callable(key) return compat.partial(callable_, self.context) for k in self.template.module._exports: yield (k, get(k)) def __getattr__(self, key): if key in self.callables: val = self.callables[key] elif self.template.has_def(key): callable_ = self.template._get_def_callable(key) val = compat.partial(callable_, self.context) elif self.inherits: val = getattr(self.inherits, key) else: raise AttributeError( "Namespace '%s' has no member '%s'" % (self.name, key)) setattr(self, key, val) return val class ModuleNamespace(Namespace): """A :class:`.Namespace` specific to a Python module instance.""" def __init__(self, name, context, module, callables=None, inherits=None, populate_self=True, calling_uri=None): self.name = name self.context = context self.inherits = inherits if callables is not None: self.callables = dict([(c.__name__, c) for c in callables]) mod = __import__(module) for token in module.split('.')[1:]: mod = getattr(mod, token) self.module = mod @property def filename(self): """The path of the filesystem file used for this :class:`.Namespace`'s module or template. """ return self.module.__file__ def _get_star(self): if self.callables: for key in self.callables: yield (key, self.callables[key]) for key in dir(self.module): if key[0] != '_': callable_ = getattr(self.module, key) if compat.callable(callable_): yield key, compat.partial(callable_, self.context) def __getattr__(self, key): if key in self.callables: val = self.callables[key] elif hasattr(self.module, key): callable_ = getattr(self.module, key) val = compat.partial(callable_, self.context) elif self.inherits: val = getattr(self.inherits, key) else: raise AttributeError( "Namespace '%s' has no member '%s'" % (self.name, key)) setattr(self, key, val) return val def supports_caller(func): """Apply a caller_stack compatibility decorator to a plain Python function. See the example in :ref:`namespaces_python_modules`. """ def wrap_stackframe(context, *args, **kwargs): context.caller_stack._push_frame() try: return func(context, *args, **kwargs) finally: context.caller_stack._pop_frame() return wrap_stackframe def capture(context, callable_, *args, **kwargs): """Execute the given template def, capturing the output into a buffer. See the example in :ref:`namespaces_python_modules`. """ if not compat.callable(callable_): raise errors.RuntimeException( "capture() function expects a callable as " "its argument (i.e. capture(func, *args, **kwargs))" ) context._push_buffer() try: callable_(*args, **kwargs) finally: buf = context._pop_buffer() return buf.getvalue() def _decorate_toplevel(fn): def decorate_render(render_fn): def go(context, *args, **kw): def y(*args, **kw): return render_fn(context, *args, **kw) try: y.__name__ = render_fn.__name__[7:] except TypeError: # < Python 2.4 pass return fn(y)(context, *args, **kw) return go return decorate_render def _decorate_inline(context, fn): def decorate_render(render_fn): dec = fn(render_fn) def go(*args, **kw): return dec(context, *args, **kw) return go return decorate_render def _include_file(context, uri, calling_uri, **kwargs): """locate the template from the given uri and include it in the current output.""" template = _lookup_template(context, uri, calling_uri) (callable_, ctx) = _populate_self_namespace( context._clean_inheritance_tokens(), template) callable_(ctx, **_kwargs_for_include(callable_, context._data, **kwargs)) def _include_ui(context, ui, template_uri, *args, **kwargs): uicls = _lookup_uicls(context, ui) ui_module = uicls(context) ui_module._execute(*args, **kwargs) def _inherit_from(context, uri, calling_uri): """called by the _inherit method in template modules to set up the inheritance chain at the start of a template's execution.""" if uri is None: return None template = _lookup_template(context, uri, calling_uri) self_ns = context['self'] ih = self_ns while ih.inherits is not None: ih = ih.inherits lclcontext = context._locals({'next': ih}) ih.inherits = TemplateNamespace("self:%s" % template.uri, lclcontext, template=template, populate_self=False) context._data['parent'] = lclcontext._data['local'] = ih.inherits callable_ = getattr(template.module, '_choco_inherit', None) if callable_ is not None: ret = callable_(template, lclcontext) if ret: return ret gen_ns = getattr(template.module, '_choco_generate_namespaces', None) if gen_ns is not None: gen_ns(context) return (template.callable_, lclcontext) def _lookup_uicls(context, ui): lookup = context._with_template.lookup if lookup is None: raise errors.TemplateLookupException( "Template '%s' has no TemplateLookup associated" % context._with_template.uri) uicls = lookup.get_ui(ui) return uicls def _lookup_template(context, uri, relativeto): lookup = context._with_template.lookup if lookup is None: raise errors.TemplateLookupException( "Template '%s' has no TemplateLookup associated" % context._with_template.uri) uri = lookup.adjust_uri(uri, relativeto) try: return lookup.get_template(uri) except errors.TopLevelLookupException: raise errors.TemplateLookupException(str(compat.exception_as())) def _populate_self_namespace(context, template, self_ns=None): if self_ns is None: self_ns = TemplateNamespace('self:%s' % template.uri, context, template=template, populate_self=False) context._data['self'] = context._data['local'] = self_ns if hasattr(template.module, '_choco_inherit'): ret = template.module._choco_inherit(template, context) if ret: return ret return (template.callable_, context) def _render(template, callable_, args, data, as_unicode=False): """create a Context and return the string output of the given template and template callable.""" if as_unicode: buf = util.FastEncodingBuffer(as_unicode=True) elif template.bytestring_passthrough: buf = compat.StringIO() else: buf = util.FastEncodingBuffer( as_unicode=as_unicode, encoding=template.output_encoding, errors=template.encoding_errors) context = Context(buf, **data) context._outputting_as_unicode = as_unicode context._set_with_template(template) _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) return context._pop_buffer().getvalue() def _render_ui(template, callable_, pctx, args, data): context = Context(pctx._buffer_stack[-1], **data) context._outputting_as_unicode = pctx._outputting_as_unicode context._set_with_template(template) _render_context(template, callable_, context) def _kwargs_for_callable(callable_, data): argspec = compat.inspect_func_args(callable_) # for normal pages, **pageargs is usually present if argspec[2]: return data # for rendering defs from the top level, figure out the args namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None] kwargs = {} for arg in namedargs: if arg != 'context' and arg in data and arg not in kwargs: kwargs[arg] = data[arg] return kwargs def _kwargs_for_include(callable_, data, **kwargs): argspec = compat.inspect_func_args(callable_) namedargs = argspec[0] + [v for v in argspec[1:3] if v is not None] for arg in namedargs: if arg != 'context' and arg in data and arg not in kwargs: kwargs[arg] = data[arg] return kwargs def _render_context(tmpl, callable_, context, *args, **kwargs): import choco.template as template # create polymorphic 'self' namespace for this # template with possibly updated context if not isinstance(tmpl, template.DefTemplate): # if main render method, call from the base of the inheritance stack (inherit, lclcontext) = _populate_self_namespace(context, tmpl) _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) else: # otherwise, call the actual rendering method specified (inherit, lclcontext) = _populate_self_namespace(context, tmpl.parent) _exec_template(callable_, context, args=args, kwargs=kwargs) def _exec_template(callable_, context, args=None, kwargs=None): """execute a rendering callable given the callable, a Context, and optional explicit arguments the contextual Template will be located if it exists, and the error handling options specified on that Template will be interpreted here. """ template = context._with_template if template is not None and \ (template.format_errors or template.error_handler): try: callable_(context, *args, **kwargs) except Exception: _render_error(template, context, compat.exception_as()) except: e = sys.exc_info()[0] _render_error(template, context, e) else: callable_(context, *args, **kwargs) def _render_error(template, context, error): if template.error_handler: result = template.error_handler(context, error) if not result: compat.reraise(*sys.exc_info()) else: error_template = errors.html_error_template() if context._outputting_as_unicode: context._buffer_stack[:] = [ util.FastEncodingBuffer(as_unicode=True)] else: context._buffer_stack[:] = [util.FastEncodingBuffer( error_template.output_encoding, error_template.encoding_errors)] context._set_with_template(error_template) error_template.render_context(context, error=error)
PypiClean
/MetaCalls-0.0.5-cp310-cp310-manylinux2014_x86_64.whl/metacalls/node_modules/wide-align/README.md
wide-align ---------- A wide-character aware text alignment function for use in terminals / on the console. ### Usage ``` var align = require('wide-align') // Note that if you view this on a unicode console, all of the slashes are // aligned. This is because on a console, all narrow characters are // an en wide and all wide characters are an em. In browsers, this isn't // held to and wide characters like "古" can be less than two narrow // characters even with a fixed width font. console.log(align.center('abc', 10)) // ' abc ' console.log(align.center('古古古', 10)) // ' 古古古 ' console.log(align.left('abc', 10)) // 'abc ' console.log(align.left('古古古', 10)) // '古古古 ' console.log(align.right('abc', 10)) // ' abc' console.log(align.right('古古古', 10)) // ' 古古古' ``` ### Functions #### `align.center(str, length)` → `str` Returns *str* with spaces added to both sides such that that it is *length* chars long and centered in the spaces. #### `align.left(str, length)` → `str` Returns *str* with spaces to the right such that it is *length* chars long. ### `align.right(str, length)` → `str` Returns *str* with spaces to the left such that it is *length* chars long. ### Origins These functions were originally taken from [cliui](https://npmjs.com/package/cliui). Changes include switching to the MUCH faster pad generation function from [lodash](https://npmjs.com/package/lodash), making center alignment pad both sides and adding left alignment.
PypiClean
/EnergyCapSdk-8.2304.4743.tar.gz/EnergyCapSdk-8.2304.4743/energycap/sdk/models/place_group_digest_area_ranking_child.py
from msrest.serialization import Model class PlaceGroupDigestAreaRankingChild(Model): """PlaceGroupDigestAreaRankingChild. :param cost: The cost for this place :type cost: float :param use: The use for this place :type use: float :param value: The benchmark value for this place :type value: float :param area: The area for this place :type area: int :param savings_opportunity: The savings opportunity for this place :type savings_opportunity: float :param incomplete_data: Does this place have incomplete data? :type incomplete_data: bool :param place_id: :type place_id: int :param place_code: :type place_code: str :param place_info: :type place_info: str :param place_display: :type place_display: str :param include_in_charts: :type include_in_charts: bool """ _attribute_map = { 'cost': {'key': 'cost', 'type': 'float'}, 'use': {'key': 'use', 'type': 'float'}, 'value': {'key': 'value', 'type': 'float'}, 'area': {'key': 'area', 'type': 'int'}, 'savings_opportunity': {'key': 'savingsOpportunity', 'type': 'float'}, 'incomplete_data': {'key': 'incompleteData', 'type': 'bool'}, 'place_id': {'key': 'placeId', 'type': 'int'}, 'place_code': {'key': 'placeCode', 'type': 'str'}, 'place_info': {'key': 'placeInfo', 'type': 'str'}, 'place_display': {'key': 'placeDisplay', 'type': 'str'}, 'include_in_charts': {'key': 'includeInCharts', 'type': 'bool'}, } def __init__(self, **kwargs): super(PlaceGroupDigestAreaRankingChild, self).__init__(**kwargs) self.cost = kwargs.get('cost', None) self.use = kwargs.get('use', None) self.value = kwargs.get('value', None) self.area = kwargs.get('area', None) self.savings_opportunity = kwargs.get('savings_opportunity', None) self.incomplete_data = kwargs.get('incomplete_data', None) self.place_id = kwargs.get('place_id', None) self.place_code = kwargs.get('place_code', None) self.place_info = kwargs.get('place_info', None) self.place_display = kwargs.get('place_display', None) self.include_in_charts = kwargs.get('include_in_charts', None)
PypiClean
/DuHast-1.0.7-py3-none-any.whl/duHast/APISamples/RevitSharedParameterData.py
from IFamilyData import IFamilyData import IFamilyData as IFamData import Utility as util import RevitSharedParameters as rSharedPara # import Autodesk import Autodesk.Revit.DB as rdb PARAMETER_GUID = 'parameterGUID' PARAMETER_NAME = 'parameterName' PARAMETER_ID = 'parameterId' class SharedParameterData(IFamilyData): def __init__(self, rootPath, rootCategoryPath, dataType): self.data = [] if(dataType != None): self.dataType = dataType else: self.dataType = 'not declared' if(rootPath != None): self.rootPath = rootPath else: self.rootPath = '-' if(rootCategoryPath != None): self.rootCategoryPath = rootCategoryPath else: self.rootCategoryPath = '-' def process(self, doc): collector = rSharedPara.GetAllSharedParameters(doc) for para in collector: # just in case parameter name is not unicode parameterName = 'unknown' try: parameterName = util.EncodeAscii(rdb.Element.Name.GetValue(para)) except Exception as ex: parameterName = 'Exception: ' + str(ex) # check if used: useCounter = 0 usedByData = {} if(rSharedPara.IsSharedParameterDefinitionUsed(doc, para)): useCounter = 1 # build used by data as required to be the same as post process update usedByData = { PARAMETER_GUID : para.GuidValue.ToString(), PARAMETER_NAME : parameterName, IFamData.ROOT : self.rootPath } # build data self.data.append({ IFamData.ROOT : self.rootPath, IFamData.ROOT_CATEGORY : self.rootCategoryPath, IFamData.FAMILY_NAME : self._stripFileExtension(doc.Title), IFamData.FAMILY_FILE_PATH : doc.PathName, PARAMETER_GUID : para.GuidValue.ToString(), PARAMETER_NAME : parameterName, PARAMETER_ID : para.Id.IntegerValue, IFamData.USAGE_COUNTER : useCounter, IFamData.USED_BY : [usedByData] } ) # check if any shared parameter was found if(len(self.data) == 0): # add message no shared parameter found self.data.append({ IFamData.ROOT : self.rootPath, IFamData.ROOT_CATEGORY : self.rootCategoryPath, IFamData.FAMILY_NAME : self._stripFileExtension(doc.Title), IFamData.FAMILY_FILE_PATH : doc.PathName, PARAMETER_GUID : '', PARAMETER_NAME : 'No shared parameter present in family.', PARAMETER_ID : -1, IFamData.USAGE_COUNTER : 0, IFamData.USED_BY : [] } ) def get_Data(self): return self.data
PypiClean
/Cad_usd_forecast_model-0.0.1.tar.gz/Cad_usd_forecast_model-0.0.1/README.md
This package contains the pipeline of the ML model - forecast_model, the requirements, tests as well as other set up files. You can install this package and use the forecast_model to predict the future price of CAD-USD exchange. Find below the description of the different components & their respective uses: A. forecast_model: This is the main module of this package. It contains a number of sub modules and files. 1. config: Contains 'core.py' which is used to set the configuration for all the variables & file paths needed to run the package. The variables are listed in the config.yml file 2. datasets: This contains the original dataset used to train the model 3. processing: This contains other modules such as: - data_manager: contains functions which can be used to load a dataset from the datasets module, and save, load or remove a trained model. - preprocessing: contains functions necessary to transform raw data into the format expected by the trained model. Hence, this module is the preprocessing pipeline for this model. 4. trained_models: This module contains the latest version of the trained forecast_model 5. connfig.yml: Contains names of all the variables & file paths used in the model 6. forecast.py: for forecasting CADUSD Price 7. train_pipeline.py: for training the forecast_model 8. VERSION: for setting the version of the model B. Requirements: contains dependencies required to use or test the package C. tests: contains scripts for testing the package 1. conftest.py - contains a fixture fxn which is used to provide forecast period to the other test. 2. test_prediction.py - used to test the predition fucntion of forecast_model D. Manifest.in: contains instructions for what to include or exclude when building the package E. pyproject.toml: this file contains basic dependencies for setting up the package and also the configuration options for pytest. F. tox.ini: this file contains the settings for using tox for automated test but I didnt use tox to test this package. Testing: - Because my model using Prophet and prophet can not be installed without g++ compiler, I could not test this package with tox and so I used pytest on the cmd How to use this package: **To run the different files and test the modules, I created a conda environment for this project, installed all the dependencies in the requirements.txt except prophet. and then followed the steps in this link to install prophet. https://stackoverflow.com/questions/53178281/installing-fbprophet-python-on-windows-10 ** If testing or using the package file on your computer, you have to add the directory to your PYTHONPATH, So that python can find it. Search for 'andrei' on https://stackoverflow.com/questions/3402168/permanently-add-a-directory-to-pythonpath . If you don't do this, python will not be able to find the package and so will not be able to run the import statements
PypiClean
/2vyper-0.3.0.tar.gz/2vyper-0.3.0/src/twovyper/ast/arithmetic.py
from twovyper.utils import Subscriptable def sign(a: int) -> int: if a > 0: return 1 elif a < 0: return -1 else: return 0 def div(a: int, b: int) -> int: """ Truncating division of two integers. """ return sign(a) * sign(b) * (abs(a) // abs(b)) def mod(a: int, b: int) -> int: """ Truncating modulo of two integers. """ return sign(a) * (abs(a) % abs(b)) class Decimal(object, metaclass=Subscriptable): def __init__(self): assert False _cache = {} def _subscript(number_of_digits: int): # This is the function that gets called when using dictionary lookup syntax. # For example, Decimal[10] returns a class of decimals with 10 digits. The class # is cached so that Decimal[10] always returns the same class, which means that # type(Decimal[10](1)) == type(Decimal[10](2)). cached_class = Decimal._cache.get(number_of_digits) if cached_class: return cached_class class _Decimal(Decimal): def __init__(self, value: int = None, scaled_value: int = None): assert (value is None) != (scaled_value is None) self.number_of_digits = number_of_digits self.scaling_factor = 10 ** number_of_digits self.scaled_value = scaled_value if value is None else value * self.scaling_factor def __eq__(self, other): if isinstance(other, _Decimal): return self.scaled_value == other.scaled_value else: return False def __hash__(self): return hash(self.scaled_value) def __str__(self): dv = div(self.scaled_value, self.scaling_factor) md = mod(self.scaled_value, self.scaling_factor) return f'{dv}.{str(md).zfill(self.number_of_digits)}' Decimal._cache[number_of_digits] = _Decimal return _Decimal
PypiClean
/MutagenTagWrapper-0.2.0.tar.gz/MutagenTagWrapper-0.2.0/src/tagwrapper/monkeysaudio.py
from __future__ import annotations from copy import deepcopy as dp from typing import Type from mutagen import apev2, flac from mutagen import monkeysaudio from .common import TagWrapper from .util import get_extension_from_data, mkpicture __all__ = ['MonkeysAudio'] class MonkeysAudio(TagWrapper): @property def raw_tag_type(self) -> Type[monkeysaudio.MonkeysAudio]: return monkeysaudio.MonkeysAudio @property def field_names(self) -> dict[str, str]: return { 'contact': 'CONTACT', 'copyright': 'COPYRIGHT', 'encoder': 'ENCODER', 'ISRC': 'ISRC', 'label': 'LABEL', 'license': 'LICENSE', 'performer': 'PERFORMER', 'tracktotal': 'TRACKTOTAL', 'version': 'VERSION', 'description': 'DESCRIPTION', 'organization': 'PUBLISHER', 'title': 'TITLE', 'artist': 'ARTIST', 'album': 'ALBUM', 'date': 'YEAR', 'tracknumber': 'TRACK', 'genre': 'GENRE', 'comment': 'COMMENT', 'albumartist': 'ALBUMARTIST', 'composer': 'COMPOSER', 'discnumber': 'DISCNUMBER' } @property def field_names_apevalues(self) -> dict[str, Type[apev2.APETextValue]]: return { 'contact': apev2.APETextValue, 'copyright': apev2.APETextValue, 'encoder': apev2.APETextValue, 'ISRC': apev2.APETextValue, 'label': apev2.APETextValue, 'license': apev2.APETextValue, 'performer': apev2.APETextValue, 'tracktotal': apev2.APETextValue, 'version': apev2.APETextValue, 'description': apev2.APETextValue, 'organization': apev2.APETextValue, 'title': apev2.APETextValue, 'artist': apev2.APETextValue, 'album': apev2.APETextValue, 'date': apev2.APETextValue, 'tracknumber': apev2.APETextValue, 'genre': apev2.APETextValue, 'comment': apev2.APETextValue, 'albumartist': apev2.APETextValue, 'composer': apev2.APETextValue, 'discnumber': apev2.APETextValue } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) captialize = {} for k, v in self._raw_tag.items(): captialize[k.upper()] = v self._raw_tag.clear() self._raw_tag.update(captialize) def setter_hook(self, value: str | list[str], setter_name: str) -> apev2.APETextValue: text = super().setter_hook(value, setter_name) return self.field_names_apevalues[setter_name]('\x00'.join(text)) @property def cover(self) -> flac.Picture | None: ape_binary_value: apev2.APEBinaryValue = self.raw_tag.get('COVER ART (FRONT)') if ape_binary_value is None: return pic_data = bytes(ape_binary_value) splitted = pic_data.split(b'\x00', maxsplit=1) if splitted[0].upper().startswith(b'COVER ART (FRONT)'): if len(splitted) > 1: pic_data = b'\x00'.join(splitted[1:]) elif len(splitted) == 0: return picture = flac.Picture() picture.data = pic_data picture.type = 3 return mkpicture(data=pic_data, type=3) @cover.setter def cover(self, obj: flac.Picture | bytes | dict[str, bytes | str | int]) -> None: if isinstance(obj, flac.Picture): picture = dp(obj) elif isinstance(obj, bytes): picture = mkpicture(data=obj) elif isinstance(obj, dict): picture = mkpicture(**obj) else: raise TypeError(f"'{type(obj).__name__}' object cannot be interpreted as cover") pic_data = picture.data target_data = b'\x00'.join( [ b'COVER ART (FRONT)' + get_extension_from_data(pic_data).encode().upper(), pic_data ] ) self.raw_tag['COVER ART (FRONT)'] = apev2.APEBinaryValue(target_data) @cover.deleter def cover(self) -> None: del self.raw_tag['COVER ART (FRONT)']
PypiClean
/NNGT-2.7.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl/nngt/analysis/clustering.py
import numpy as np import nngt from nngt.lib import nonstring_container from nngt.lib.graph_helpers import _get_matrices __all__ = [ "global_clustering", "global_clustering_binary_undirected", "local_closure", "local_clustering", "local_clustering_binary_undirected", "triplet_count", "triangle_count", ] def global_clustering_binary_undirected(g): ''' Returns the undirected global clustering coefficient. This corresponds to the ratio of undirected triangles to the number of undirected triads. Parameters ---------- g : :class:`~nngt.Graph` Graph to analyze. ''' # Note, this function is overloaded by the library-specific version # if igraph, graph-tool, or networkx is used triangles = triangle_count(g, weights=None, directed=False) triplets = triplet_count(g, weights=None, directed=False) return np.sum(triangles) / np.sum(triplets) def global_clustering(g, directed=True, weights=None, method="continuous", mode="total", combine_weights="mean"): ''' Returns the global clustering coefficient. This corresponds to the ratio of triangles to the number of triplets. For directed and weighted cases, see definitions of generalized triangles and triplets in the associated functions below. Parameters ---------- g : :class:`~nngt.Graph` Graph to analyze. directed : bool, optional (default: True) Whether to compute the directed clustering if the graph is directed. weights : bool or str, optional (default: binary edges) Whether edge weights should be considered; if ``None`` or ``False`` then use binary edges; if ``True``, uses the 'weight' edge attribute, otherwise uses any valid edge attribute required. method : str, optional (default: 'continuous') Method used to compute the weighted clustering, either 'barrat' [Barrat2004]_, 'continuous' [Fardet2021]_, 'onnela' [Onnela2005]_, or 'zhang' [Zhang2005]_. mode : str, optional (default: "total") Type of clustering to use for directed graphs, among "total", "fan-in", "fan-out", "middleman", and "cycle" [Fagiolo2007]_. combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "sum": the sum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. Reference --------- .. [gt-global-clustering] :gtdoc:`clustering.global_clustering` .. [ig-global-clustering] :igdoc:`transitivity_undirected` .. [nx-global-clustering] :nxdoc:`algorithms.cluster.transitivity` .. [Barrat2004] Barrat, Barthelemy, Pastor-Satorras, Vespignani. The Architecture of Complex Weighted Networks. PNAS 2004, 101 (11). :doi:`10.1073/pnas.0400087101`. .. [Onnela2005] Onnela, Saramäki, Kertész, Kaski. Intensity and Coherence of Motifs in Weighted Complex Networks. Phys. Rev. E 2005, 71 (6), 065103. :doi:`10.1103/physreve.71.065103`, arxiv:`cond-mat/0408629`. .. [Fagiolo2007] Fagiolo. Clustering in Complex Directed Networks. Phys. Rev. E 2007, 76 (2), 026107. :doi:`10.1103/PhysRevE.76.026107`, :arxiv:`physics/0612169`. .. [Zhang2005] Zhang, Horvath. A General Framework for Weighted Gene Co-Expression Network Analysis. Statistical Applications in Genetics and Molecular Biology 2005, 4 (1). :doi:`10.2202/1544-6115.1128`, `PDF <https://dibernardo.tigem.it/files/papers/2008/ zhangbin-statappsgeneticsmolbio.pdf>`_. .. [Fardet2021] Fardet, Levina. Weighted directed clustering: interpretations and requirements for heterogeneous, inferred, and measured networks. 2021. :arxiv:`2105.06318`. See also -------- :func:`~nngt.analysis.triplet_count` :func:`~nngt.analysis.triangle_count` ''' assert method in ("barrat", "continuous", "onnela", "zhang"), \ "Unknown method '{}'".format(method) # check directivity and weights directed *= g.is_directed() weighted = weights not in (False, None) if not directed and not weighted: return global_clustering_binary_undirected(g) elif not weighted: # directed clustering triangles = triangle_count(g, mode=mode) triplets = triplet_count(g, mode=mode) return np.sum(triangles) / np.sum(triplets) triangles, triplets = _triangles_and_triplets(g, directed, weights, method, mode, combine_weights, None) return np.sum(triangles) / np.sum(triplets) def local_closure(g, directed=True, weights=None, method=None, mode="cycle-out", combine_weights="mean"): r''' Compute the local closure for each node, as defined in [Yin2019]_ as the fraction of 2-walks that are closed. For undirected binary or weighted adjacency matrices :math:`W = \{ w_{ij} \}`, the normal (or Zhang-like) definition is given by: .. math:: H_i^0 = \frac{\sum_{j\neq k} w_{ij} w_{jk} w_{ki}} {\sum_{j\neq k\neq i} w_{ij}w_{jk}} = \frac{W^3_{ii}}{\sum_{j \neq i} W^2_{ij}} While a continuous version of the local closure is also proposed as: .. math:: H_i = \frac{\sum_{j\neq k} \sqrt[3]{w_{ij} w_{jk} w_{ki}}^2} {\sum_{j\neq k\neq i} \sqrt{w_{ij}w_{jk}}} = \frac{\left( W^{\left[ \frac{2}{3} \right]} \right)_{ii}^3} {\sum_{j \neq i} \left( W^{\left[ \frac{1}{2} \right]} \right)^2_{ij}} with :math:`W^{[\alpha]} = \{ w^\alpha_{ij} \}`. Directed versions of the local closure where defined as follow for a node :math:`i` connected to nodes :math:`j` and :math:`k`: * "cycle-out" is given by the pattern [(i, j), (j, k), (k, i)], * "cycle-in" is given by the pattern [(k, j), (j, i), (i, k)], * "fan-in" is given by the pattern [(k, j), (j, i), (k, i)], * "fan-out" is given by the pattern [(i, j), (j, k), (i, k)]. See [Fardet2021]_ for more details. Parameters ---------- g : :class:`~nngt.Graph` Graph to analyze. directed : bool, optional (default: True) Whether to compute the directed clustering if the graph is directed. weights : bool or str, optional (default: binary edges) Whether edge weights should be considered; if ``None`` or ``False`` then use binary edges; if ``True``, uses the 'weight' edge attribute, otherwise uses any valid edge attribute required. method : str, optional (default: 'continuous') Method used to compute the weighted clustering, either 'normal'/'zhang' or 'continuous'. mode : str, optional (default: "circle-out") Type of clustering to use for directed graphs, among "circle-out", "circle-in", "fan-in", or "fan-out". combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "sum": the sum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. References ---------- .. [Yin2019] Yin, Benson, and Leskovec. The Local Closure Coefficient: A New Perspective On Network Clustering. Proceedings of the Twelfth ACM International Conference on Web Search and Data Mining 2019, 303-311. :doi:`10.1145/3289600.3290991`, `PDF <https://www.cs.cornell.edu/~arb/ papers/closure-coefficients-WSDM-2019.pdf>`_. .. [Fardet2021] Fardet, Levina. Weighted directed clustering: interpretations and requirements for heterogeneous, inferred, and measured networks. 2021. :arxiv:`2105.06318`. ''' directed *= g.is_directed() weighted = weights not in (False, None) mat, numer, denom = None, None, None if not directed and g.is_directed(): _, mat = _get_matrices(g, directed, weights, weighted, combine_weights, normed=True) else: mat = g.adjacency_matrix(weights=weights).astype(float) mat /= mat.max() mat.setdiag(0) mat2, mat3 = None, None if directed: # set correct matrix if mode.endswith("-in"): mat = mat.T if method == "continuous" and weights is not None: sqmat = mat.sqrt() cbmat = mat.power(2/3) mat2 = sqmat@sqmat if mode in ("cycle-in", "cycle-out"): mat3 = cbmat@cbmat@cbmat elif mode in ("fan-in", "fan-out"): mat3 = cbmat@cbmat@cbmat.T else: raise ValueError("Unknown `mode`: '" + mode + "'.'") elif method in ("normal", "zhang", None): mat2 = mat@mat if mode in ("cycle-in", "cycle-out"): mat3 = mat2@mat elif mode in ("fan-in", "fan-out"): mat3 = mat2@mat.T else: raise ValueError("Unknown `mode`: '" + mode + "'.'") else: raise ValueError("Unknown `method`: '" + method + "'.'") else: # undirected if method == "continuous" and weights is not None: sqmat = mat.sqrt() cbmat = mat.power(2/3) mat2 = sqmat@sqmat mat3 = cbmat@cbmat@cbmat elif method in ("normal", "zhang", None): mat2 = mat@mat mat3 = mat2@mat else: raise ValueError("Unknown `method`: '" + method + "'.'") numer = mat3.diagonal() denom = _sum(mat2, axis=1) - mat2.diagonal() denom[denom == 0] = 1 return numer / denom def local_clustering_binary_undirected(g, nodes=None): r''' Returns the undirected local clustering coefficient of some `nodes`. .. math:: C_i = \frac{A^3_{ii}}{d_i(d_i - 1)} = \frac{\Delta_i}{T_i} with :math:`A` the adjacency matrix, :math:`d_i` the degree of node :math:`i`, :math:`\Delta_i` is the number of triangles, and :math:`T_i` is the number of triplets to which :math:`i` belongs. If `g` is directed, then it is converted to a simple undirected graph (no parallel edges), both directed and reciprocal edges are merged into a single edge. Parameters ---------- g : :class:`~nngt.Graph` Graph to analyze. nodes : list, optional (default: all nodes) The list of nodes for which the clustering will be returned Returns ------- lc : :class:`numpy.ndarray` The list of clustering coefficients, on per node. References ---------- .. [gt-local-clustering] :gtdoc:`clustering.local_clustering` .. [ig-local-clustering] :igdoc:`transitivity_local_undirected` .. [nx-local-clustering] :nxdoc:`algorithms.cluster.clustering` ''' # Note, this function is overloaded by the library-specific version # if igraph, graph-tool, or networkx is used triangles = triangle_count(g, weights=None, nodes=nodes, directed=False) triplets = triplet_count(g, weights=None, nodes=nodes, directed=False) if nonstring_container(triangles): triplets[triangles == 0] = 1 elif triangles == 0: return 0 return triangles / triplets def local_clustering(g, nodes=None, directed=True, weights=None, method="continuous", mode="total", combine_weights="mean"): r''' Local (weighted directed) clustering coefficient of the nodes, ignoring self-loops. If no weights are requested and the graph is undirected, returns the undirected binary clustering. For all weighted cases, the weights are assumed to be positive and they are normalized to dimensionless values between 0 and 1 through a division by the highest weight. The default `method` for weighted networks is the continuous definition [Fardet2021]_ and is defined as: .. math:: C_i = \frac{\sum_{jk} \sqrt[3]{w_{ij} w_{ik} w_{jk}}} {\sum_{j\neq k} \sqrt{w_{ij} w_{ik}}} = \frac{\left(W^{\left[\frac{2}{3}\right]}\right)^3_{ii}} {\left(s^{\left[\frac{1}{2}\right]}_i\right)^2 - s_i} for undirected networks, with :math:`W = \{ w_{ij}\} = \tilde{W} / \max(\tilde{W})` the normalized weight matrix, :math:`s_i` the normalized strength of node :math:`i`, and :math:`s^{[\frac{1}{2}]}_i = \sum_k \sqrt{w_{ik}}` the strength associated to the matrix :math:`W^{[\frac{1}{2}]} = \{\sqrt{w_{ij}}\}`. For directed networks, we used the total clustering defined in [Fagiolo2007]_ by default, hence the second equation becomes: .. math:: C_i = \frac{\frac{1}{2}\left(W^{\left[\frac{2}{3}\right]} + W^{\left[\frac{2}{3}\right],T}\right)^3_{ii}} {\left(s^{\left[\frac{1}{2}\right]}_i\right)^2 - 2s^{\leftrightarrow}_i - s_i} with :math:`s^{\leftrightarrow} = \sum_k \sqrt{w_{ik}w_{ki}}` the reciprocal strength (associated to reciprocal connections). For the other modes, see the generalized definitions in [Fagiolo2007]_. Contrary to 'barrat' and 'onnela' [Saramaki2007]_, this method displays *all* following properties: * fully continuous (no jump in clustering when weights go to zero), * equivalent to binary clustering when all weights are 1, * equivalence between no-edge and zero-weight edge cases, * normalized (always between zero and 1). Using either 'continuous' or 'zhang' is usually recommended for weighted graphs, see the discussion in [Fardet2021]_ for details. Parameters ---------- g : :class:`~nngt.Graph` object Graph to analyze. nodes : array-like container with node ids, optional (default = all nodes) Nodes for which the local clustering coefficient should be computed. directed : bool, optional (default: True) Whether to compute the directed clustering if the graph is directed. weights : bool or str, optional (default: binary edges) Whether edge weights should be considered; if ``None`` or ``False`` then use binary edges; if ``True``, uses the 'weight' edge attribute, otherwise uses any valid edge attribute required. method : str, optional (default: 'continuous') Method used to compute the weighted clustering, either 'barrat' [Barrat2004]_/[Clemente2018]_, 'continuous' [Fardet2021]_, 'onnela' [Onnela2005]_/[Fagiolo2007]_, or 'zhang' [Zhang2005]_. mode : str, optional (default: "total") Type of clustering to use for directed graphs, among "total", "fan-in", "fan-out", "middleman", and "cycle" [Fagiolo2007]_. combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "sum": equivalent to mean due to weight normalization. Returns ------- lc : :class:`numpy.ndarray` The list of clustering coefficients, on per node. References ---------- .. [Barrat2004] Barrat, Barthelemy, Pastor-Satorras, Vespignani. The Architecture of Complex Weighted Networks. PNAS 2004, 101 (11). :doi:`10.1073/pnas.0400087101`. .. [Clemente2018] Clemente, Grassi. Directed Clustering in Weighted Networks: A New Perspective. Chaos, Solitons & Fractals 2018, 107, 26–38. :doi:`10.1016/j.chaos.2017.12.007`, :arxiv:`1706.07322`. .. [Fagiolo2007] Fagiolo. Clustering in Complex Directed Networks. Phys. Rev. E 2007, 76, (2), 026107. :doi:`10.1103/PhysRevE.76.026107`, :arxiv:`physics/0612169`. .. [Onnela2005] Onnela, Saramäki, Kertész, Kaski. Intensity and Coherence of Motifs in Weighted Complex Networks. Phys. Rev. E 2005, 71 (6), 065103. :doi:`10.1103/physreve.71.065103`, :arxiv:`cond-mat/0408629`. .. [Saramaki2007] Saramäki, Kivelä, Onnela, Kaski, Kertész. Generalizations of the Clustering Coefficient to Weighted Complex Networks. Phys. Rev. E 2007, 75 (2), 027105. :doi:`10.1103/PhysRevE.75.027105`, :arxiv:`cond-mat/0608670`. .. [Zhang2005] Zhang, Horvath. A General Framework for Weighted Gene Co-Expression Network Analysis. Statistical Applications in Genetics and Molecular Biology 2005, 4 (1). :doi:`10.2202/1544-6115.1128`, `PDF <https://dibernardo.tigem.it/files/papers/2008/ zhangbin-statappsgeneticsmolbio.pdf>`_. .. [Fardet2021] Fardet, Levina. Weighted directed clustering: interpretations and requirements for heterogeneous, inferred, and measured networks. 2021. :arxiv:`2105.06318`. See also -------- :func:`undirected_binary_clustering` :func:`global_clustering` ''' # check directivity and weights directed *= g.is_directed() weighted = weights not in (None, False) triplets, triangles = None, None if not directed and not weighted: # undirected binary clustering uses the library method return local_clustering_binary_undirected(g, nodes=nodes) elif not weighted: # directed clustering triangles = triangle_count(g, nodes=nodes, mode=mode) triplets = triplet_count(g, nodes, mode=mode).astype(float) else: triangles, triplets = _triangles_and_triplets( g, directed, weights, method, mode, combine_weights, nodes) if nonstring_container(triplets): triplets[triangles == 0] = 1 elif triangles == 0: return 0 return triangles / triplets def triangle_count(g, nodes=None, directed=True, weights=None, method="normal", mode="total", combine_weights="mean"): ''' Returns the number or the strength (also called intensity) of triangles for each node. Parameters ---------- g : :class:`~nngt.Graph` object Graph to analyze. nodes : array-like container with node ids, optional (default = all nodes) Nodes for which the local clustering coefficient should be computed. directed : bool, optional (default: True) Whether to compute the directed clustering if the graph is directed. weights : bool or str, optional (default: binary edges) Whether edge weights should be considered; if ``None`` or ``False`` then use binary edges; if ``True``, uses the 'weight' edge attribute, otherwise uses any valid edge attribute required. method : str, optional (default: 'normal') Method used to compute the weighted triangles, either 'normal', where the weights are directly used, or the definitions associated to the weighted clustering: 'barrat' [Barrat2004]_, 'continuous', 'onnela' [Onnela2005]_, or 'zhang' [Zhang2005]_. mode : str, optional (default: "total") Type of clustering to use for directed graphs, among "total", "fan-in", "fan-out", "middleman", and "cycle" [Fagiolo2007]_. combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "sum": the sum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. Returns ------- tr : array Number or weight of triangles to which each node belongs. References ---------- .. [Barrat2004] Barrat, Barthelemy, Pastor-Satorras, Vespignani. The Architecture of Complex Weighted Networks. PNAS 2004, 101 (11). :doi:`10.1073/pnas.0400087101`. .. [Fagiolo2007] Fagiolo. Clustering in Complex Directed Networks. Phys. Rev. E 2007, 76, (2), 026107. :doi:`10.1103/PhysRevE.76.026107`, :arxiv:`physics/0612169`. .. [Onnela2005] Onnela, Saramäki, Kertész, Kaski. Intensity and Coherence of Motifs in Weighted Complex Networks. Phys. Rev. E 2005, 71 (6), 065103. :doi:`10.1103/physreve.71.065103`, :arxiv:`cond-mat/0408629`. .. [Zhang2005] Zhang, Horvath. A General Framework for Weighted Gene Co-Expression Network Analysis. Statistical Applications in Genetics and Molecular Biology 2005, 4 (1). :doi:`10.2202/1544-6115.1128`, `PDF <https://dibernardo.tigem.it/files/papers/2008/ zhangbin-statappsgeneticsmolbio.pdf>`_. ''' directed *= g.is_directed() weighted = weights not in (False, None) exponent = None if method == "onnela": exponent = 1/3 elif method == "continuous": exponent = 2/3 # get relevant matrices (use directed=False to get both dir/undir mat) mat, matsym = _get_matrices( g, directed, weights, weighted, combine_weights, exponent=exponent, normed=True) # if unweighted, adj is mat, adjsym is matsym adj, adjsym = mat, matsym # for barrat, we need both weighted and binary matrices if method == "barrat" and weighted: adj, adjsym = _get_matrices(g, directed, None, False, combine_weights) return _triangle_count(mat, matsym, adj, adjsym, method, mode, weighted, directed, nodes) def triplet_count(g, nodes=None, directed=True, weights=None, method="normal", mode="total", combine_weights="mean"): r''' Returns the number or the strength (also called intensity) of triplets for each node. For binary networks, the triplets of node :math:`i` are defined as: .. math:: T_i = \sum_{j,k} a_{ij}a_{ik} Parameters ---------- g : :class:`~nngt.Graph` object Graph to analyze. nodes : array-like container with node ids, optional (default = all nodes) Nodes for which the local clustering coefficient should be computed. directed : bool, optional (default: True) Whether to compute the directed clustering if the graph is directed. weights : bool or str, optional (default: binary edges) Whether edge weights should be considered; if ``None`` or ``False`` then use binary edges; if ``True``, uses the 'weight' edge attribute, otherwise uses any valid edge attribute required. method : str, optional (default: 'continuous') Method used to compute the weighted triplets, either 'normal', where the edge weights are directly used, or the definitions used for weighted clustering coefficients, 'barrat' [Barrat2004]_, 'continuous', 'onnela' [Onnela2005]_, or 'zhang' [Zhang2005]_. mode : str, optional (default: "total") Type of clustering to use for directed graphs, among "total", "fan-in", "fan-out", "middleman", and "cycle" [Fagiolo2007]_. combine_weights : str, optional (default: 'mean') How to combine the weights of reciprocal edges if the graph is directed but `directed` is set to False. It can be: * "sum": the sum of the edge attribute values will be used for the new edge. * "mean": the mean of the edge attribute values will be used for the new edge. * "min": the minimum of the edge attribute values will be used for the new edge. * "max": the maximum of the edge attribute values will be used for the new edge. Returns ------- tr : array Number or weight of triplets to which each node belongs. References ---------- .. [Barrat2004] Barrat, Barthelemy, Pastor-Satorras, Vespignani. The Architecture of Complex Weighted Networks. PNAS 2004, 101 (11). :doi:`10.1073/pnas.0400087101`. .. [Fagiolo2007] Fagiolo. Clustering in Complex Directed Networks. Phys. Rev. E 2007, 76, (2), 026107. :doi:`10.1103/PhysRevE.76.026107`, :arxiv:`physics/0612169`. .. [Zhang2005] Zhang, Horvath. A General Framework for Weighted Gene Co-Expression Network Analysis. Statistical Applications in Genetics and Molecular Biology 2005, 4 (1). :doi:`10.2202/1544-6115.1128`, `PDF <https://dibernardo.tigem.it/files/papers/2008/ zhangbin-statappsgeneticsmolbio.pdf>`_. ''' directed *= g.is_directed() weighted = weights not in (False, None) # simple binary cases if not weighted or method == "onnela": # undirected if not directed: deg = None if g.is_directed(): _, adjsym = _get_matrices(g, directed, None, False, combine_weights) if nodes is None: deg = _sum(adjsym, axis=0) else: deg = _sum(adjsym, axis=0)[nodes] else: deg = g.get_degrees(nodes=nodes) if nodes is None or nonstring_container(nodes): return (0.5*deg*(deg - 1)).astype(int) return 0.5*deg*(deg - 1) # directed if mode in ("total", "cycle", "middleman"): adj = g.adjacency_matrix() d_recip = (adj@adj).diagonal() if nodes is not None: d_recip = d_recip[nodes] din = g.get_degrees("in", nodes=nodes) dout = g.get_degrees("out", nodes=nodes) if mode == "total": dtot = din + dout return dtot*(dtot - 1) - 2*d_recip return din*dout - d_recip else: assert mode in ("fan-in", "fan-out"), \ "Unknown mode '{}'".format(mode) deg = g.get_degrees(mode[4:], nodes=nodes) return deg*(deg - 1) # check method for weighted W, Wu, A, Au = None, None, None, None if method in ("continuous", "normal", "zhang"): # we need only the weighted matrices W, Wu = _get_matrices(g, directed, weights, weighted, combine_weights=combine_weights, normed=True) elif method == "barrat": # we need only the (potentially) directed matrices W = g.adjacency_matrix(weights=weights) A = g.adjacency_matrix() else: raise ValueError("`method` must be either 'barrat', 'onnela', " "'zhang', or 'continuous'/'normal' (identical " "options).") return _triplet_count_weighted( g, W, Wu, A, Au, method, mode, directed, weights, nodes) # ---------------------------------------------------------- # # Overwrite binary clusterings with library-specific version # # ---------------------------------------------------------- # if nngt._config["backend"] == "networkx": from .nx_functions import (global_clustering_binary_undirected, local_clustering_binary_undirected) if nngt._config["backend"] == "igraph": from .ig_functions import (global_clustering_binary_undirected, local_clustering_binary_undirected) if nngt._config["backend"] == "graph-tool": from .gt_functions import (global_clustering_binary_undirected, local_clustering_binary_undirected) # -------------- # # Tool functions # # -------------- # def _triangles_and_triplets(g, directed, weights, method, mode, combine_weights, nodes): ''' Return the triangles and triplets ''' # weighted clustering W, Wu, A, Au = None, None, None, None triplets = None # check the method to get the relevant matrices if method == "continuous": W, Wu = _get_matrices(g, directed, weights, True, combine_weights, exponent=2/3, normed=True) Wtr, Wtru = _get_matrices(g, directed, weights, True, combine_weights, normed=True) triplets = _triplet_count_weighted( g, Wtr, Wtru, A, Au, method, mode, directed, weights, nodes) if method == "zhang": W, Wu = _get_matrices(g, directed, weights, True, combine_weights, normed=True) triplets = _triplet_count_weighted( g, W, Wu, A, Au, method, mode, directed, weights, nodes) elif method == "onnela": W, Wu = _get_matrices(g, directed, weights, True, combine_weights, exponent=1/3, normed=True) # onnela uses the binary triplets triplets = triplet_count(g, nodes=nodes, directed=directed, mode=mode, weights=None) elif method == "barrat": # we need all matrices W, Wu = _get_matrices(g, directed, weights, True, combine_weights, normed=True) A, Au = _get_matrices(g, directed, None, False, combine_weights) triplets = _triplet_count_weighted( g, W, Wu, A, Au, method, mode, directed, weights, nodes) # get triangles and triplet strength triangles = _triangle_count(W, Wu, A, Au, method, mode, weighted=True, directed=directed, nodes=nodes) return triangles, triplets def _triangle_count(mat, matsym, adj, adjsym, method, mode, weighted, directed, nodes): ''' (Un)weighted (un)directed triangle count. ''' tr = None if method == "barrat": if mode == "total": tr = 0.5*(matsym@adjsym@adjsym).diagonal() elif mode == "cycle": tr = 0.5*(mat@adj@adj + mat.T@adj.T@adj.T).diagonal() elif mode == "middleman": tr = 0.5*(mat.T@adj@adj.T + mat@adj.T@adj).diagonal() elif mode == "fan-in": tr = 0.5*(mat.T@adjsym@adj).diagonal() elif mode == "fan-out": tr = 0.5*(mat@adjsym@adj.T).diagonal() else: raise ValueError("Unknown mode ''.".format(mode)) else: if not weighted: mat, matsym = adj, adjsym elif method not in ("continuous", "zhang", "normal", "onnela"): raise ValueError("Invalid `method`: '{}'".format(method)) if mode == "total": tr = 0.5*(matsym@matsym@matsym).diagonal() elif mode == "cycle": tr = (mat@mat@mat).diagonal() elif mode == "middleman": tr = (mat@mat.T@mat).diagonal() elif mode == "fan-in": tr = (mat.T@mat@mat).diagonal() elif mode == "fan-out": tr = (mat@mat@mat.T).diagonal() else: raise ValueError("Unknown mode ''.".format(mode)) if isinstance(tr, np.matrix): tr = tr.A1 if nodes is None: return tr return tr[nodes] def _triplet_count_weighted(g, mat, matsym, adj, adjsym, method, mode, directed, weights, nodes): ''' triplet count, weighted only. ''' tr = None if method == "normal": pass elif method == "continuous": if directed: sqmat = mat.sqrt() if mode == "total": s2_sq_tot = np.square( _sum(sqmat, axis=0) + _sum(sqmat, axis=1)) s_tot = _sum(mat, axis=0) + _sum(mat, axis=1) s_recip = 2*(sqmat@sqmat).diagonal() tr = s2_sq_tot - s_tot - s_recip elif mode in ("cycle", "middleman"): s_sq_out = _sum(sqmat, axis=0) s_sq_in = _sum(sqmat, axis=1) s_recip = (sqmat@sqmat).diagonal() tr = s_sq_in*s_sq_out - s_recip elif mode in ("fan-in", "fan-out"): axis = 0 if mode == "fan-in" else 1 s2_sq = np.square(_sum(sqmat, axis=axis)) sgth = _sum(mat, axis=axis) tr = s2_sq - sgth else: raise ValueError("Unknown mode ''.".format(mode)) else: sqmat = matsym.sqrt() s2_sq = np.square(_sum(sqmat, axis=0)) s = _sum(matsym, axis=0) tr = 0.5*(s2_sq - s) elif method == "zhang": if directed: mat2 = mat.power(2) if mode == "total": s2_sq_tot = np.square(_sum(mat, axis=0) + _sum(mat, axis=1)) s_tot = _sum(mat2, axis=0) + _sum(mat2, axis=1) s_recip = 2*(mat@mat).diagonal() tr = s2_sq_tot - s_tot - s_recip elif mode in ("cycle", "middleman"): s_sq_out = _sum(mat, axis=0) s_sq_in = _sum(mat, axis=1) s_recip = (mat@mat).diagonal() tr = s_sq_in*s_sq_out - s_recip elif mode in ("fan-in", "fan-out"): axis = 0 if mode == "fan-in" else 1 s2_sq = np.square(_sum(mat, axis=axis)) sgth = _sum(mat2, axis=axis) tr = s2_sq - sgth else: raise ValueError("Unknown mode ''.".format(mode)) else: mat2 = matsym.power(2) s2_sq = np.square(_sum(matsym, axis=0)) s = _sum(mat2, axis=0) tr = 0.5*(s2_sq - s) elif method == "barrat": if directed: # specifc definition of the reciprocal strength from Clemente if mode == "total": s_recip = 0.5*(mat@adj + adj@mat).diagonal() dtot = g.get_degrees("total") wmax = np.max(g.get_weights()) stot = g.get_degrees("total", weights=weights) / wmax tr = stot*(dtot - 1) - 2*s_recip elif mode in ("cycle", "middleman"): s_recip = 0.5*(mat@adj + adj@mat).diagonal() s_in = _sum(mat, axis=0) s_out = _sum(mat, axis=1) d_in = g.get_degrees("in") d_out = g.get_degrees("out") tr = 0.5*(s_in*d_out + s_out*d_in) - s_recip elif mode in ("fan-in", "fan-out"): axis = 0 if mode == "fan-in" else 1 sgth = _sum(mat, axis=axis) deg = g.get_degrees(mode[4:]) tr = sgth*(deg - 1) else: raise ValueError("Unknown mode ''.".format(mode)) elif g.is_directed(): d = _sum(adjsym, axis=0) s = _sum(matsym, axis=0) tr = 0.5*s*(d - 1) else: d = g.get_degrees() s = _sum(matsym, axis=0) tr = 0.5*s*(d - 1) else: raise ValueError( "Invalid `method` for triplet count: '{}'".format(method)) if nodes is None: return tr return tr[nodes] def _sum(mat, axis): ''' Sum either sparse matrix or array ''' res = mat.sum(axis=axis) if "matrix" in str(type(mat)): return res.A1 return res
PypiClean
/AutoDiffX-0.2.tar.gz/AutoDiffX-0.2/ad/ad.py
import numpy as np __all__ = ['Expression', 'Variable', 'Constant'] class Expression(object): '''Base expression class that represents anything in our computational graph. Everything should be one of these.''' def __init__(self, grad=False): self.grad = grad self.children = [] self.dep_vars = set() def eval(self, feed_dict): '''Evaluates the entire computation graph given a dictionary of variables mapped to values.''' return self._eval(feed_dict, dict()) def _eval(self, feed_dict, cache_dict): '''Helper - Evaluates the computation graph recursively.''' raise NotImplementedError def d(self, feed_dict): '''Evaluates the derivative at the points given, returns to user''' res = self._d(feed_dict, dict(), dict()) if len(self.dep_vars) == 0: # No dependent variables - it is a constant return 0 if len(res) == 1: # This is the non-vectorized case, scalar func of scalar # Return a number, not a dictionary return list(res.values())[0] return res def _d(self, feed_dict, e_cache_dict, d_cache_dict): '''Helper - Evaluates the differentiation products recursively. @param: feed_dict: dictionary mapping var names @param: e_cache_dict: cache for previously evaluated values @param: d_cache_dict: cache for previously calculated derivatives ''' raise NotImplementedError('Jacobian not implemented for this expr') def hessian(self, feed_dict): '''Evaluates the hessian at the points given, returns to user as a dictionary of dictionarys (to be indexed as [var1][var2] for the derivative with respect to var1 then var2)''' res = self._h(feed_dict, dict(), dict(), dict()) if len(self.dep_vars) == 0: return 0 elif len(self.dep_vars) == 1: # This is the 1D hessian case, so just a scalar return list(list(res.values())[0].values())[0] else: return res def _h(self, feed_dict, e_cache_dict, d_cache_dict, h_cache_dict): '''Helper - Evaluates the differentiation products recursively. @param: feed_dict: dictionary mapping var names @param: e_cache_dict: cache for previously evaluated values @param: d_cache_dict: cache for previously calculated derivatives @param: h_cache_dict: cache for previously calculated double derivatives ''' raise NotImplementedError('Hessian not implemented for this expr') def d_expr(self, n=1): """Return n-th order derivative as an Expression. Scalar input only. """ var = list(self.dep_vars)[0] di = self for i in range(n): di = di._d_expr(var) return di def _d_expr(self, var): """Helper - Evaluates the partial derivative as an Expression.""" raise NotImplementedError def d_n(self, n, val): """Return the value of n-th order derivative. Scalar input only. Expressions that implements d_n method are: Variable, Constant, Negation, Addition, Subtraction, Multiplication, Division, Expression ** Constant, Sin, Cos, Exp, Log, and their combinations. """ var = list(self.dep_vars)[0] return self._d_n(n, {var: val}, {}, {}) * np.math.factorial(n) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): """ Helper - Evaluates (the n-th order derivative) / (n!). @param: n: the order of derivative @param: feed_dict: dictionary mapping var names @param: e_cache_dict: cache for previously evaluated values @param: d_cache_dict: cache for previously calculated derivatives @return: the value of the n-th order derivative """ raise NotImplementedError def __add__(self, other): try: # Propagate the need for gradient if one thing needs gradient # Need to call other.grad first since self.grad may shortcircuit return Addition(self, other, grad=(other.grad and self.grad)) except AttributeError: return Addition(self, Constant(other), grad=self.grad) def __radd__(self, other): return self.__add__(other) def __sub__(self, other): try: return Subtraction(self, other, grad=(other.grad and self.grad)) except AttributeError: return Subtraction(self, Constant(other), grad=self.grad) def __rsub__(self, other): try: return Subtraction(other, self, grad=(other.grad and self.grad)) except AttributeError: return Subtraction(Constant(other), self, grad=self.grad) def __mul__(self, other): try: return Multiplication(self, other, grad=(other.grad and self.grad)) except AttributeError: return Multiplication(self, Constant(other), grad=self.grad) def __rmul__(self, other): # TODO: Multiplication not commutative if we enable matrix support return self.__mul__(other) def __truediv__(self, other): try: return Division(self, other, grad=(other.grad and self.grad)) except AttributeError: return Division(self, Constant(other), grad=self.grad) def __rtruediv__(self, other): try: return Division(other, self, grad=(other.grad and self.grad)) except AttributeError: return Division(Constant(other), self, grad=self.grad) def __neg__(self): return Negation(self, grad=self.grad) def __pow__(self, other): try: return Power(self, other, grad=(other.grad and self.grad)) except AttributeError: return Power(self, Constant(other), grad=(self.grad)) class Variable(Expression): def __init__(self, name=None, grad=True): self.grad = grad self.name = None if not name else str(name) # A variable only depends on itself self.dep_vars = set([self]) def _eval(self, feed_dict, cache_dict): # Check if the user specified either the object in feed_dict or # the name of the object in feed_dict if self in feed_dict: return feed_dict[self] elif self.name in feed_dict: return feed_dict[self.name] else: raise ValueError('Unbound variable %s' % self.name) def _d(self, feed_dict, e_cache_dict, d_cache_dict): return {self: 1.0} def _h(self, feed_dict, e_cache_dict, d_cache_dict, h_cache_dict): return {self: {self: 0}} def _d_expr(self, var): if var == self: return Constant(1.0) else: return Constant(0) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if n == 0: return self._eval(feed_dict, e_cache_dict) elif n == 1: return 1.0 else: return 0.0 def __repr__(self): if self.name: return self.name else: return "Var" class Constant(Expression): '''Represents a constant.''' def __init__(self, val, grad=False): super().__init__(grad=grad) self.val = val self.dep_vars = set() def _eval(self, feed_dict, cache_dict): return self.val def _d(self, feed_dict, e_cache_dict, d_cache_dict): return {} def _d_expr(self, var): return Constant(0.0) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if n == 0: return self.val else: return 0.0 def _h(self, feed_dict, e_cache_dict, d_cache_dict, h_cache_dict): return {} class Unop(Expression): """Utilities common to all unary operations in the form Op(a) Attributes ---------- expr1: Expression Input of the unary function children: list of Expression The children of the unary function, i.e. expr1 """ def __init__(self, expr1, grad=False): """ Parameters ---------- expr1 : Expression Input of the unary function. grad : bool, optional If True, then allow the Expression to calculate the derivative. """ super().__init__(grad=grad) self.expr1 = expr1 self.children = [self.expr1] # Deep copy the set self.dep_vars = set(expr1.dep_vars) class Negation(Unop): """Negation, in the form - A""" def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) cache_dict[id(self)] = -res1 return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): if id(self) not in d_cache_dict: d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) ret = {} for var in self.dep_vars: ret[var] = -d1.get(var, 0) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _h(self, feed_dict, e_cache, d_cache, h_cache): if id(self) not in h_cache: # Both dx^2 and dxdy are just the negations too h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: ret[var1][var2] = - h1.get(var1, {}).get(var2, 0) h_cache[id(self)] = ret return h_cache[id(self)] def _d_expr(self, var): return - self.expr1._d_expr(var) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res1 = self.expr1._eval(feed_dict, e_cache_dict) else: res1 = self.expr1._d_n(n, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self), n)] = -res1 return d_cache_dict[(id(self), n)] class Binop(Expression): '''Utilities common to all binary operations in the form Op(a, b)''' def __init__(self, expr1, expr2, grad=False): super().__init__(grad=grad) try: expr1.grad except AttributeError: expr1 = Constant(expr1) try: expr2.grad except AttributeError: expr2 = Constant(expr1) self.expr1 = expr1 self.expr2 = expr2 self.children = [self.expr1, self.expr2] self.dep_vars = expr1.dep_vars | expr2.dep_vars class Power(Binop): """Power function, the input is raised to the power of exponent. Examples -------- >>> import ad >>> x = ad.Variable('x') >>> y = x ** 2 >>> y.eval({x: 10.0}) 100.0 >>> y.d({x: 10.0}) 20.0 """ def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) res2 = self.expr2._eval(feed_dict, cache_dict) # cast to float necessary, numpy complains about raising # integers to negative integer powers otherwise. cache_dict[id(self)] = np.power(float(res1), res2) return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): """derivative is y x^(y-1) x_dot + x^y log(x) y_dot""" if id(self) not in d_cache_dict: res1 = self.expr1._eval(feed_dict, e_cache_dict) res2 = self.expr2._eval(feed_dict, e_cache_dict) d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) d2 = self.expr2._d(feed_dict, e_cache_dict, d_cache_dict) ret = {} # cast to float necessary, numpy complains about raising # integers to negative integer powers otherwise. for var in self.dep_vars: # Short circuit to prevent taking log of zero if d2.get(var, 0) == 0: ret[var] = res2 * np.power(float(res1), res2 - 1) * d1.get(var, 0) else: ret[var] = res2 * np.power(float(res1), res2 - 1) * d1.get(var, 0) + \ np.power(float(res1), res2) * np.log(res1) * d2.get(var, 0) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _d_expr(self, var): if var not in self.dep_vars: return Constant(0) if isinstance(self.expr1, Constant): return np.log(self.expr1.val) * (self.expr1 ** self.expr2) elif isinstance(self.expr2, Constant): return self.expr2.val * (self.expr1 ** (self.expr2.val - 1)) else: msg = "Do not support f(x) ** g(x)" raise NotImplementedError(msg) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if not isinstance(self.expr2, Constant): msg = "Do not support c ** g(x) or f(x) ** g(x)" raise NotImplementedError(msg) if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res = self._eval(feed_dict, e_cache_dict) d_cache_dict[(id(self), 0)] = res return d_cache_dict[(id(self), 0)] a = self.expr2.val if (id(self.expr1), 0) not in d_cache_dict: g_0 = self.expr1._d_n(0, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr1), 0)] = g_0 g_0 = d_cache_dict[(id(self.expr1), 0)] if np.isclose(g_0, 0): if a < 0: msg = "The exponent should be greater than 0 when the base is 0" raise ZeroDivisionError(msg) elif np.isclose(a, int(a)) or a >= n: d_cache_dict[(id(self), n)] = 0.0 return 0.0 else: msg = "If base of power is 0 and exponent is not an " \ "integer, the exponent should be greater than n" raise ZeroDivisionError(msg) res = 0 for i in range(1, n+1): if (id(self.expr1), i) not in d_cache_dict: g_i = self.expr1._d_n(i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr1), i)] = g_i if (id(self), n-i) not in d_cache_dict: ga_ni = self._d_n(n-i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self), n-i)] = ga_ni g_i = d_cache_dict[(id(self.expr1), i)] ga_ni = d_cache_dict[(id(self), n-i)] res += (float(a + 1) * i / n - 1) * g_i * ga_ni res /= g_0 d_cache_dict[(id(self), n)] = res return d_cache_dict[(id(self), n)] def _h(self, feed_dict, e_cache, d_cache, h_cache): """For expressions in the form x^y, I was only able to get a closed form solution for if y is a constant. The general case is way to complicated for me to solve on a piece of paper""" if id(self) not in h_cache: # Both dx^2 and dxdy are just the additions h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) h2 = self.expr2._h(feed_dict, e_cache, d_cache, h_cache) if h2 != {}: msg = 'Hessian only implemented for x^[constant]' raise NotImplementedError(msg) d1 = self.expr1._d(feed_dict, e_cache, d_cache) v1 = self.expr1._eval(feed_dict, e_cache) v2 = self.expr2._eval(feed_dict, e_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: dxy1 = h1.get(var1, {}).get(var2, 0) dx1, dx2 = d1.get(var1, 0), d1.get(var2, 0) term1 = (v2 - 1) * v2 * (v1 ** (v2 - 2)) * dx1 * dx2 term2 = v2 * (v1 ** (v2 - 1)) * dxy1 ret[var1][var2] = term1 + term2 h_cache[id(self)] = ret return h_cache[id(self)] class Addition(Binop): '''Addition, in the form A + B''' def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) res2 = self.expr2._eval(feed_dict, cache_dict) cache_dict[id(self)] = res1 + res2 return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): if id(self) not in d_cache_dict: d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) d2 = self.expr2._d(feed_dict, e_cache_dict, d_cache_dict) ret = {} for var in self.dep_vars: ret[var] = d1.get(var, 0) + d2.get(var, 0) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _d_expr(self, var): if var not in self.dep_vars: return Constant(0) return self.expr1._d_expr(var) + self.expr2._d_expr(var) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res1 = self._eval(feed_dict, e_cache_dict) else: res1 = self.expr1._d_n(n, feed_dict, e_cache_dict, d_cache_dict) + \ self.expr2._d_n(n, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self), n)] = res1 return d_cache_dict[(id(self), n)] def _h(self, feed_dict, e_cache, d_cache, h_cache): if id(self) not in h_cache: # Both dx^2 and dxdy are just the additions h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) h2 = self.expr2._h(feed_dict, e_cache, d_cache, h_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: dxy1 = h1.get(var1, {}).get(var2, 0) dxy2 = h2.get(var1, {}).get(var2, 0) ret[var1][var2] = dxy1 + dxy2 h_cache[id(self)] = ret return h_cache[id(self)] class Subtraction(Binop): '''Subtraction, in the form A - B''' def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) res2 = self.expr2._eval(feed_dict, cache_dict) cache_dict[id(self)] = res1 - res2 return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): if id(self) not in d_cache_dict: d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) d2 = self.expr2._d(feed_dict, e_cache_dict, d_cache_dict) ret = {} for var in self.dep_vars: ret[var] = d1.get(var, 0) - d2.get(var, 0) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _d_expr(self, var): if var not in self.dep_vars: return Constant(0) return self.expr1._d_expr(var) - self.expr2._d_expr(var) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res1 = self._eval(feed_dict, e_cache_dict) else: res1 = self.expr1._d_n(n, feed_dict, e_cache_dict, d_cache_dict) - \ self.expr2._d_n(n, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self), n)] = res1 return d_cache_dict[(id(self), n)] def _h(self, feed_dict, e_cache, d_cache, h_cache): if id(self) not in h_cache: # Both dx^2 and dxdy are just the additions h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) h2 = self.expr2._h(feed_dict, e_cache, d_cache, h_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: dxy1 = h1.get(var1, {}).get(var2, 0) dxy2 = h2.get(var1, {}).get(var2, 0) ret[var1][var2] = dxy1 - dxy2 h_cache[id(self)] = ret return h_cache[id(self)] class Multiplication(Binop): '''Multiplication, in the form A * B''' def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) res2 = self.expr2._eval(feed_dict, cache_dict) cache_dict[id(self)] = res1 * res2 return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): if id(self) not in d_cache_dict: d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) d2 = self.expr2._d(feed_dict, e_cache_dict, d_cache_dict) res1 = self.expr1._eval(feed_dict, e_cache_dict) res2 = self.expr2._eval(feed_dict, e_cache_dict) ret = {} for var in self.dep_vars: ret[var] = res1 * d2.get(var, 0) + res2 * d1.get(var, 0) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _h(self, feed_dict, e_cache, d_cache, h_cache): if id(self) not in h_cache: # Both dx^2 and dxdy are just the additions h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) h2 = self.expr2._h(feed_dict, e_cache, d_cache, h_cache) d1 = self.expr1._d(feed_dict, e_cache, d_cache) d2 = self.expr2._d(feed_dict, e_cache, d_cache) v1 = self.expr1._eval(feed_dict, e_cache) v2 = self.expr2._eval(feed_dict, e_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: dxy1 = h1.get(var1, {}).get(var2, 0) dxy2 = h2.get(var1, {}).get(var2, 0) ret[var1][var2] = (d1.get(var1, 0) * d2.get(var2, 0) + d1.get(var2, 0) * d2.get(var1, 0) + v1 * dxy2 + v2 * dxy1) h_cache[id(self)] = ret return h_cache[id(self)] def _d_expr(self, var): if var not in self.dep_vars: return Constant(0) if isinstance(self.expr1, Constant): return self.expr1.val * self.expr2._d_expr(var) elif isinstance(self.expr2, Constant): return self.expr2.val * self.expr1._d_expr(var) else: return self.expr1 * self.expr2._d_expr(var) + self.expr2 * \ self.expr1._d_expr(var) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res = self._eval(feed_dict, e_cache_dict) d_cache_dict[(id(self), 0)] = res return d_cache_dict[(id(self), 0)] res = 0 for i in range(n+1): if (id(self.expr1), i) not in d_cache_dict: f_i = self.expr1._d_n(i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr1), i)] = f_i if (id(self.expr2), n-i) not in d_cache_dict: g_ni = self.expr2._d_n(n-i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr2), n-i)] = g_ni f_i = d_cache_dict[(id(self.expr1), i)] g_ni = d_cache_dict[(id(self.expr2), n-i)] res += f_i * g_ni d_cache_dict[(id(self), n)] = res return d_cache_dict[(id(self), n)] class Division(Binop): '''Division, in the form A / B''' def _eval(self, feed_dict, cache_dict): if id(self) not in cache_dict: res1 = self.expr1._eval(feed_dict, cache_dict) res2 = self.expr2._eval(feed_dict, cache_dict) cache_dict[id(self)] = res1 / res2 return cache_dict[id(self)] def _d(self, feed_dict, e_cache_dict, d_cache_dict): if id(self) not in d_cache_dict: d1 = self.expr1._d(feed_dict, e_cache_dict, d_cache_dict) d2 = self.expr2._d(feed_dict, e_cache_dict, d_cache_dict) res1 = self.expr1._eval(feed_dict, e_cache_dict) res2 = self.expr2._eval(feed_dict, e_cache_dict) ret = {} for var in self.dep_vars: ret[var] = (d1.get(var, 0) / res2) - (d2.get(var, 0) * res1 / (res2 * res2)) d_cache_dict[id(self)] = ret return d_cache_dict[id(self)] def _d_expr(self, var): if var not in self.dep_vars: return Constant(0) if isinstance(self.expr1, Constant): return - self.expr1.val * self.expr2._d_expr(var) / (self.expr2 * self.expr2) elif isinstance(self.expr2, Constant): return self.expr1._d_expr(var) * (1.0 / self.expr2.val) else: return self.expr1._d_expr(var) / self.expr2 - self.expr1 * \ self.expr2._d_expr(var) / (self.expr2 * self.expr2) def _d_n(self, n, feed_dict, e_cache_dict, d_cache_dict): if (id(self), n) in d_cache_dict: return d_cache_dict[(id(self), n)] if n == 0: res = self._eval(feed_dict, e_cache_dict) d_cache_dict[(id(self), 0)] = res return d_cache_dict[(id(self), 0)] res = 0 for i in range(n): if (id(self), i) not in d_cache_dict: div_i = self._d_n(i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self), i)] = div_i if (id(self.expr2), n-i) not in d_cache_dict: g_ni = self.expr2._d_n(n-i, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr2), n-i)] = g_ni div_i = d_cache_dict[(id(self), i)] g_ni = d_cache_dict[(id(self.expr2), n-i)] res -= div_i * g_ni if (id(self.expr1), n) not in d_cache_dict: f_n = self.expr1._d_n(n, feed_dict, e_cache_dict, d_cache_dict) d_cache_dict[(id(self.expr1), n)] = f_n f_n = d_cache_dict[(id(self.expr1), n)] res += f_n if (id(self.expr2), 0) not in d_cache_dict: g_0 = self.expr2._eval(feed_dict, e_cache_dict) d_cache_dict[(id(self.expr2), 0)] = g_0 g_0 = d_cache_dict[(id(self.expr2), 0)] res /= g_0 d_cache_dict[(id(self), n)] = res return d_cache_dict[(id(self), n)] def _h(self, feed_dict, e_cache, d_cache, h_cache): if id(self) not in h_cache: # Both dx^2 and dxdy are just the additions h1 = self.expr1._h(feed_dict, e_cache, d_cache, h_cache) h2 = self.expr2._h(feed_dict, e_cache, d_cache, h_cache) d1 = self.expr1._d(feed_dict, e_cache, d_cache) d2 = self.expr2._d(feed_dict, e_cache, d_cache) f = self.expr1._eval(feed_dict, e_cache) g = self.expr2._eval(feed_dict, e_cache) ret = {var:{} for var in self.dep_vars} for var1 in self.dep_vars: for var2 in self.dep_vars: fxy = h1.get(var1, {}).get(var2, 0) gxy = h2.get(var1, {}).get(var2, 0) fx, fy = d1.get(var1, 0), d1.get(var2, 0) gx, gy = d2.get(var1, 0), d2.get(var2, 0) term1 = - (gx * fy + gy * fx) / (g ** 2) term2 = (2 * f * gy * gx) / (g ** 3) term3 = (fxy / g) - (f * gxy) / (g ** 2) ret[var1][var2] = term1 + term2 + term3 h_cache[id(self)] = ret return h_cache[id(self)]
PypiClean
/DamPy-0.12.9.tar.gz/DamPy-0.12.9/dampy/lib/Assets.py
import requests, json from requests.auth import HTTPBasicAuth import logging import csv, ast import hashlib from dampy.lib.Config import * from dampy.lib.Util import * from dampy.lib.Env import Env class Assets: '''Class abstracting the DAM operations ''' def __init__(self, conn): ''' Initialize an Assets instance with a AEM handle ''' self.conn = conn def list(self, path='/content/dam', csv_dump=False, csv_file='output/asset_list.csv'): ''' Get the list of all assets under the path given as parameter and optionally write it to a CSV file ''' asset_list = [] url = urls['list'] + path logging.debug('URL : '+url) response = self.conn.get(url) if response.success: for e in response.data[keys.assets_key]: asset_list.append(e[keys.path_key]) else: logging.error('Error getting the assets list') logging.error('Failed due to : '+response.message) logging.error('Empty list returned') if csv_dump or csv_file: logging.debug("Writing asset list of assets to : " + csv_file) dir, fname = dir_n_file(csv_file, 'csv') env = Env(dir) env.writeCSV(fname, list=asset_list) return asset_list def metadata(self, asset_path, level=1): ''' Get the metadata of the asset. Level specifies for nesting levels for metadata fetch ''' asset_metadata = {} url = asset_path + urls['metadata_suffix'] + str(level) + urls['metadata_type'] response = self.conn.get(url) if response.success: asset_metadata = response.data else: logging.error('Error getting the asset metadata') logging.error('Failed due to : '+response.message) logging.error('Empty metadata returned') return asset_metadata def _metaVal(self, asset, key): ''' Finds the key in the asset json and returns its vale ''' path = key.split('/') p_obj = asset try: for k in path: p_obj = p_obj[k] except: return None return p_obj def _csvRead(self, csv_file, header=True, type=True): ''' Reads the CSV file and returns the headers, types and data as per the flags passed in ''' headers = [] types = [] csv_data = [] with open(csv_file,'r') as cFile: csv_reader = csv.reader(cFile, delimiter=',') for row in csv_reader: csv_data.append(row) if csv_data and header : headers = csv_data.pop(0) if csv_data and type : types = csv_data.pop(0) return headers, types, csv_data def xprops(self, path='/content/dam', props=['jcr:path','jcr:content/metadata/dc:title'], csv_file='output/asset_props.csv'): ''' Extracts the metadata properties of the assets under the given path and writes it to an output csv file ''' asset_data = [] url = urls['xprops'] + path url = url.replace('$props', ' '.join(props)) logging.debug(url) response = self.conn.get(url) if response.success: asset_data.append(props) for asset in response.data[keys.assets_key]: asset_props = [] for key in props: asset_props.append(self._metaVal(asset, key)) asset_data.append(asset_props) logging.debug("Writing asset list of assets to : " + csv_file) dir, fname = dir_n_file(csv_file, 'csv') env = Env(dir) env.writeCSV(fname, data=asset_data) return True else: logging.error('Error extracting asset properties') logging.error('Failed due to : '+response.message) logging.error('Empty list returned') return False def uprops(self, csv_file='input/asset_props.csv'): ''' Reads a CSV file and updates the asset perperties based on this CSV data ''' headers, types, csv_data = self._csvRead(csv_file) if not headers: logging.error('Invalid CSV input file') logging.error('First row of CSV must be headers') return False elif ( "jcr:path" != headers[0]): logging.error('Invalid CSV input file') logging.error('The first column of header must be jcr:path property') return False if not types: logging.error('Invalid CSV input file') logging.error('Second row of CSV must be types') return False overall_status = True for row in csv_data: api_a_path = row[0][12:] update_properties = ast.literal_eval(msgs['uprops']) for index, header in enumerate(headers): if index > 0 and header: if '[]' in types[index]: vals = ast.literal_eval(row[index]) for v in vals: update_properties.append(('.' + api_a_path + '/' + header, v)) else: update_properties.append(('.' + api_a_path + '/' + header, row[index])) update_properties.append(('.' + api_a_path + '/' + header + '@TypeHint', types[index])) logging.debug('Updating with : ' + json.dumps(update_properties)) response = self.conn.post(urls['uprops'], data = update_properties) if not response.success : logging.error('Error updating properties for asset : ',update_properties) overall_status = False return overall_status def _download(self, asset_path, env, retain_dam_path): ''' Downlods the asset to the directory represented by the env object ''' logging.debug("Downloading asset : " + str(asset_path)) response = self.conn.rawget(asset_path) env.store(asset_path, response.data.content, retain_dam_path) return True def downloadAsset(self, asset_path, dir='download', retain_dam_path=False): ''' Downlods the asset to the dir ''' env = Env(dir) return self._download(asset_path, env, retain_dam_path) def downloadFolder(self, path='/content/dam', dir='download', retain_dam_path=True): ''' Downlods all assets under the mentioned DAM path to the dir ''' asset_list = self.list(path) logging.debug("Asset list : "+str(asset_list)) overall_status = True if asset_list: env = Env(dir) for asset in asset_list: status = self._download(asset, env, retain_dam_path) overall_status &= status return overall_status def createFolder(self, path, title=None, ignore_error = False): ''' Creates the folder specified by the path in DAM ''' parent, name = splitPath(path) n_name=namify(name) n_path=namify(path) data = msgs['createFolder'].replace('$name', n_name) if title: data = data.replace('$title', title) else: data = data.replace('$title', name) data = json.loads(data) logging.debug('URL - '+ n_path) logging.debug('Data - '+ str(data)) response = self.conn.post(n_path, data = data) if not (ignore_error or response.success): logging.error('Error creating folder') logging.error('Failed due to : '+response.message) logging.error('Check if the folder already exists') return response.success def createFolderTree(self, path='/content/dam', srcDir=None, srcList=None, ignore_error = False): ''' Creates the folder tree structure in DAM under the given path, reflecting the structure in local dir ''' dirList = [] if srcList: if isinstance(srcList, list): dirList += cleanseDirList('', srcList, path ) elif isinstance(srcList, str): headers, types, csv_data = self._csvRead(srcList, False, False) for row in csv_data: dirList += cleanseDirList('', row, path ) else: logging.error('Invalid input for srcList') if srcDir: env = Env(srcDir) dirList += cleanseDirList(srcDir, env.listDirs(), path ) logging.debug('Creating Folders for - '+ str(dirList)) overall_status = True for dir in dirList: logging.debug('Creating Folder - '+ dir) status = self.createFolder(dir) overall_status &= status return overall_status def fetchFolderTree(self, path='/content/dam', csv_file='output/folder_tree.csv', props=['jcr:path', 'jcr:content/jcr:title']): ''' Fetches the folder structure under the given path and writes it to an output csv file ''' folder_data = [] url = urls['fetchFolderTree'] + path url = url.replace('$props', ' '.join(props)) logging.debug(url) response = self.conn.get(url) if response.success: folder_data.append(props) for folder in response.data[keys.assets_key]: folder_props = [] for key in props: folder_props.append(self._metaVal(folder, key)) folder_data.append(folder_props) logging.debug("Writing folder list to : " + csv_file) dir, fname = dir_n_file(csv_file, 'csv') env = Env(dir) env.writeCSV(fname, data=folder_data) else: logging.error('Error fetching folder list') logging.error('Failed due to : '+response.message) logging.error('Empty list returned') return folder_data def updateFolderTitle(self, path, newTitle): ''' Updates the folder title with the new value provided ''' url = urls['updateFolderTitle'] data = json.loads(msgs['updateFolderTitle'].replace('$path', path).replace('$title',newTitle)) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not response.success: logging.error('Error updating folder title') logging.error('Failed due to : '+response.message) return response.success def restructure(self, inputCSV='input/restructure.csv'): ''' Restructures the DAM folder structure based on the input CSV file ''' headers, types, csv_data = self._csvRead(inputCSV, True, False) overall_status = True for row in csv_data: logging.debug('Processing row - '+ str(row)) if('Move' == row[0]): srcPath = row[1] destPath = row[3] dparent, dname = splitPath(destPath) status = self.move(srcPath, dparent, dname) if(row[1] != row[4]): self.updateFolderTitle(destPath,row[4]) elif ('Delete' == row[0]): status = self.delete(row[1]) overall_status &= status return overall_status def uploadAsset(self, file, path='/content/dam'): ''' Uploads the single file to DAM at the specified path ''' path = trimPath(path) self.createFolder(path, None, True) url = path + '.createasset.html' logging.debug('URL - '+ path) logging.debug('file - '+ file) files = {'file': open(file, 'rb')} response = self.conn.post(url, files = files) if not response.success: logging.error('Error getting uploading file') logging.error('Failed due to : '+response.message) return response.success def uploadFolder(self, dir='upload', path='/content/dam'): ''' Upload all the assets under the dir parameter. Folder structure under dir replicated onto DAM, under the path specified ''' env = Env(dir) path_map = cleansePaths(dir, env.listFiles(), path ) overall_status = True for file in path_map: logging.debug('Uploading file - '+ file) status = self.uploadAsset(file, path_map[file]) overall_status &= status return overall_status def move(self, srcPath, destPath, newName=None): ''' Move the asset or folder from the srcPath to the destPath ''' url = urls['move'] data = msgs['move'].replace('$srcPath', srcPath).replace('$destParentPath',destPath) if newName: data = data.replace('$destName', newName) else: parent, name = splitPath(srcPath) data = data.replace('$destName', name) data = json.loads(data) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not response.success: logging.error('Error moving ' + srcPath + ' to ' + destPath) logging.error('Failed due to : '+response.message) return response.success def activate(self, path, force='true'): ''' Activate the asset or folder specified by the path parameter ''' metadata = self.metadata(path) if('dam:AssetContent' == metadata['jcr:primaryType']) : url = urls['activate'] else : url = urls['activateTree'] data = json.loads(msgs['activate'].replace('$path', path)) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not response.success: logging.error('Error Activating the asset') logging.error('Failed due to : '+response.message) return response.success def deactivate(self, path, force='true'): ''' Deactivate the asset or folder specified by the path parameter ''' url = urls['deactivate'] data = json.loads(msgs['deactivate'].replace('$path', path)) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not response.success: logging.error('Error Deactivating the asset') logging.error('Failed due to : '+response.message) return response.success def delete(self, path, force='true'): ''' Delete the asset or folder specified by the path parameter ''' url = urls['delete'] data = json.loads(msgs['delete'].replace('$path', path)) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not response.success: logging.error('Error Deactivating the asset') logging.error('Failed due to : '+response.message) return response.success def activateList(self, listSrc): ''' Activate all the assets provided by the listSrc. listSrc can be a list of all assets to activate or the file name containing the list of assets ''' return self._perform(self.activate, listSrc) def deactivateList(self, listSrc): ''' Deactivate all the assets provided by the listSrc. listSrc can be a list of all assets to deactivate or the file name containing the list of assets ''' return self._perform(self.deactivate, listSrc) def deleteList(self, listSrc): ''' Delete all the assets provided by the listSrc. listSrc can be a list of all assets to delete or the file name containing the list of assets ''' return self._perform(self.delete, listSrc) def _perform(self, action, listSrc): ''' Creates the folder tree structure in DAM under the given path, reflecting the structure in local dir ''' assetList = [] if listSrc: if isinstance(listSrc, list): assetList += cleanseDirList('', listSrc, '/content/dam' ) elif isinstance(listSrc, str): headers, types, csv_data = self._csvRead(listSrc, False, False) logging.debug('Asset list from ' + listSrc + ' - '+ str(csv_data)) for row in csv_data: assetList += cleanseDirList('', row, '/content/dam' ) else: logging.error('Invalid input for listSrc') logging.debug('Performing '+ str(action) +' for - '+ str(assetList)) overall_status = True for asset in assetList: logging.debug('Processing asset - '+ asset) overall_status &= action(asset) return overall_status def exists(self, asset): ''' Check if the file is available in DAM and returns the list of paths at which the file is available ''' fcontent = open(asset, 'rb').read() _sha1 = hashlib.sha1(fcontent).hexdigest() url = urls['exists'] + _sha1 logging.debug('URL - '+ url) response = self.conn.get(url) duplicates = [] if response.success: for e in response.data[keys.assets_key]: duplicates.append(e[keys.path_key]) else: logging.error('Error checking if the given asset exists in DAM') logging.error('Failed due to : '+response.message) logging.error('Empty list returned') return duplicates def duplicates(self, path='/content/dam'): ''' Find all the duplicate binaries under the given path and returns it. Returns empty if no duplicates are identified ''' url = urls['duplicates'] + path logging.debug('URL - '+ url) response = self.conn.get(url) duplicates = {} removals = [] if response.success: for e in response.data[keys.assets_key]: sha_val = self._metaVal(e, keys.sha1_key) if sha_val in duplicates: duplicates[sha_val].append(e[keys.path_key]) else: duplicates[sha_val] = [e[keys.path_key]] for k in duplicates: if len(duplicates[k]) <=1: removals.append(k) for k in removals: duplicates.pop(k) else: logging.error('Error checking for duplicates in DAM') logging.error('Failed due to : '+response.message) logging.error('Empty list returned') return duplicates def checkout(self, path, action='checkout'): ''' Check-out/check-in an asset in DAM ''' url = path + urls['checkout'] data = json.loads(msgs[action]) logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not (response.success): logging.error('Error checking out the asset') logging.error('Failed due to : '+response.message) logging.error('Check if the asset exists and is not locked') return response.success def checkin(self, path): ''' Check-in an asset in DAM. Calls checkout method with action param as 'checkin' to accomplish the task ''' return self.checkout(path, action='checkin') def edit(self, path, crop='', rotate='', flip='', map=''): ''' Edit an asset in DAM. Support cropping, rotating, flipping and mapping of the asset in DAM ''' url = path + urls['edit'] data = msgs['edit'] data = data.replace('$crop', crop) data = data.replace('$rotate', rotate) flipHorizontal = '' flipVertical = '' if flip in ('h', 'b', 'horizontal', 'both'): flipHorizontal = 'fliphorizontal' if flip in ('v', 'b', 'vertical', 'both'): flipVertical = 'flipvertical' data = data.replace('$flipHorizontal', flipHorizontal) data = data.replace('$flipVertical', flipVertical) data = json.loads(data) data['./imageMap'] = map logging.debug('URL - '+ url) logging.debug('Data - '+ str(data)) response = self.conn.post(url, data = data) if not (response.success): logging.error('Error editing the asset') logging.error('Failed due to : '+response.message) logging.error('Check if the asset exists and is not checked out by someone else') return response.success def crop(self, path, top_left, bottom_right): ''' Crop an asset in DAM. ''' if not (top_left or bottom_right): logging.error('Top left and bottom right parameter mandatory to crop an asset') return False if (len(top_left) != 2) or (len(bottom_right) != 2): logging.error('Invalid values for top left or bottom right parameters') return False if not (isinstance(top_left[0], int) and isinstance(top_left[1], int) and isinstance(bottom_right[0], int) and isinstance(bottom_right[1], int)): logging.error('Invalid values for top left or bottom right parameters') return False crop_str = ','.join(str(x) for x in (top_left + bottom_right)) return self.edit(path, crop=crop_str) def rotate(self, path, angle): ''' Rotate an asset in DAM. ''' if not angle: logging.error('Angle parameter mandatory to rotate an asset') return False if not isinstance(angle, int): logging.error('Invalid values for angle parameter') return False return self.edit(path, rotate=str(angle)) def flip(self, path, type): ''' Flip an asset in DAM horizontally or veritcally Set type to 'h' or 'horizontal' to flip the asset horizontally Set type to 'v' or 'vertical' to flip the asset vertically Set type to 'b' or 'both' to flip the asset both horizontally and vertically ''' if not type: logging.error('type parameter mandatory to flip an asset') return False if not type in ('h', 'v', 'b', 'horizontal', 'vertical', 'both'): logging.error('Invalid values for type parameter') return False return self.edit(path, flip=type) def map(self, path, data): ''' Image map an asset in DAM based on the data ''' if not data: logging.error('data parameter mandatory to image map an asset') return False return self.edit(path, map=data) def getMapData(self, currentMap='', type='rect', dimension=(0,0,100,100), link='#', alt='Click', target='_self'): ''' From map data based on input parameters, add it to current map data supplied and return it ''' mapData = '[' + type + str(dimension) + '\"' + link +'\"|\"' + target + '\"|\"' + alt + '\"]' return currentMap + mapData
PypiClean
/0-orchestrator-1.1.0a7.tar.gz/0-orchestrator-1.1.0a7/zeroos/orchestrator/sal/Container.py
import json from io import BytesIO import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Containers: def __init__(self, node): self.node = node def list(self): containers = [] for container in self.node.client.container.list().values(): try: containers.append(Container.from_containerinfo(container, self.node)) except ValueError: # skip containers withouth tags pass return containers def get(self, name): containers = list(self.node.client.container.find(name).values()) if not containers: raise LookupError("Could not find container with name {}".format(name)) if len(containers) > 1: raise LookupError("Found more than one containter with name {}".format(name)) return Container.from_containerinfo(containers[0], self.node) def create(self, name, flist, hostname=None, mounts=None, nics=None, host_network=False, ports=None, storage=None, init_processes=None, privileged=False): logger.debug("create container %s", name) container = Container(name, self.node, flist, hostname, mounts, nics, host_network, ports, storage, init_processes, privileged) container.start() return container class Container: """G8SO Container""" def __init__(self, name, node, flist, hostname=None, mounts=None, nics=None, host_network=False, ports=None, storage=None, init_processes=None, privileged=False, identity=None): """ TODO: write doc string filesystems: dict {filesystemObj: target} """ self.name = name self.node = node self.mounts = mounts or {} self.hostname = hostname self.flist = flist self.ports = ports or {} self.nics = nics or [] self.host_network = host_network self.storage = storage self.init_processes = init_processes or [] self._client = None self.privileged = privileged self.identity = identity self._ays = None for nic in self.nics: nic.pop('token', None) if nic.get('config', {}).get('gateway', ''): nic['monitor'] = True @classmethod def from_containerinfo(cls, containerinfo, node): logger.debug("create container from info") arguments = containerinfo['container']['arguments'] if not arguments['tags']: # we don't deal with tagless containers raise ValueError("Could not load containerinfo withouth tags") return cls(arguments['tags'][0], node, arguments['root'], arguments['hostname'], arguments['mount'], arguments['nics'], arguments['host_network'], arguments['port'], arguments['storage'], arguments['privileged'], arguments['identity']) @classmethod def from_ays(cls, service, password=None): logger.debug("create container from service (%s)", service) from .Node import Node node = Node.from_ays(service.parent, password) ports = {} for portmap in service.model.data.ports: source, dest = portmap.split(':') ports[int(source)] = int(dest) nics = [nic.to_dict() for nic in service.model.data.nics] mounts = {} for mount in service.model.data.mounts: fs_service = service.aysrepo.serviceGet('filesystem', mount.filesystem) try: sp = node.storagepools.get(fs_service.parent.name) fs = sp.get(fs_service.name) except KeyError: continue mounts[fs.path] = mount.target container = cls( name=service.name, node=node, mounts=mounts, nics=nics, hostname=service.model.data.hostname, flist=service.model.data.flist, ports=ports, host_network=service.model.data.hostNetworking, storage=service.model.data.storage, init_processes=[p.to_dict() for p in service.model.data.initProcesses], privileged=service.model.data.privileged, identity=service.model.data.identity, ) return container @property def id(self): logger.debug("get container id") info = self.info if info: return info['container']['id'] return @property def info(self): logger.debug("get container info") for containerid, container in self.node.client.container.list().items(): if self.name in (container['container']['arguments']['tags'] or []): container['container']['id'] = int(containerid) return container return @property def client(self): if self._client is None: self._client = self.node.client.container.client(self.id) return self._client def upload_content(self, remote, content): if isinstance(content, str): content = content.encode('utf8') bytes = BytesIO(content) self.client.filesystem.upload(remote, bytes) def download_content(self, remote): buff = BytesIO() self.client.filesystem.download(remote, buff) return buff.getvalue().decode() def _create_container(self, timeout=60): logger.debug("send create container command to g8os") tags = [self.name] if self.hostname and self.hostname != self.name: tags.append(self.hostname) job = self.node.client.container.create( root_url=self.flist, mount=self.mounts, host_network=self.host_network, nics=self.nics, port=self.ports, tags=tags, hostname=self.hostname, storage=self.storage, privileged=self.privileged, identity=self.identity, ) containerid = job.get(timeout) self._client = self.node.client.container.client(containerid) def is_job_running(self, cmd): try: for job in self._client.job.list(): arguments = job['cmd']['arguments'] if 'name' in arguments and arguments['name'] == cmd: return job return False except Exception as err: if str(err).find("invalid container id"): return False raise def is_port_listening(self, port, timeout=60): import time start = time.time() while start + timeout > time.time(): if port not in self.node.freeports(port, nrports=3): return True time.sleep(0.2) return False def start(self): if not self.is_running(): logger.debug("start %s", self) self._create_container() for process in self.init_processes: cmd = "{} {}".format(process['name'], ' '.join(process.get('args', []))) pwd = process.get('pwd', '') stdin = process.get('stdin', '') env = {} for x in process.get('environment', []): k, v = x.split("=") env[k] = v self.client.system(command=cmd, dir=pwd, stdin=stdin, env=env) def stop(self): if not self.is_running(): return logger.debug("stop %s", self) self.node.client.container.terminate(self.id) self._client = None def is_running(self): return self.id is not None @property def ays(self): if self._ays is None: from JumpScale.sal.g8os.atyourservice.StorageCluster import ContainerAYS self._ays = ContainerAYS(self) return self._ays def __str__(self): return "Container <{}>".format(self.name) def __repr__(self): return str(self)
PypiClean
/Feature_Format-0.1.tar.gz/Feature_Format-0.1/Feature_Format/Feature_Format.py
if __name__ == "__main__": # !/usr/bin/python """ A general tool for converting data from the dictionary format to an (n x k) python list that's ready for training an sklearn algorithm n--no. of key-value pairs in dictonary k--no. of features being extracted dictionary keys are names of persons in dataset dictionary values are dictionaries, where each key-value pair in the dict is the name of a feature, and its value for that person In addition to converting a dictionary to a numpy array, you may want to separate the labels from the features--this is what targetFeatureSplit is for so, if you want to have the poi label as the target, and the features you want to use are the person's salary and bonus, here's what you would do: feature_list = ["poi", "salary", "bonus"] data_array = featureFormat( data_dictionary, feature_list ) label, features = targetFeatureSplit(data_array) the line above (targetFeatureSplit) assumes that the label is the _first_ item in feature_list--very important that poi is listed first! """ import numpy as np def featureFormat(dictionary, features, remove_NaN=True, remove_all_zeroes=True, remove_any_zeroes=False, sort_keys=False): """ convert dictionary to numpy array of features remove_NaN = True will convert "NaN" string to 0.0 remove_all_zeroes = True will omit any data points for which all the features you seek are 0.0 remove_any_zeroes = True will omit any data points for which any of the features you seek are 0.0 sort_keys = True sorts keys by alphabetical order. Setting the value as a string opens the corresponding pickle file with a preset key order (this is used for Python 3 compatibility, and sort_keys should be left as False for the course mini-projects). NOTE: first feature is assumed to be 'poi' and is not checked for removal for zero or missing values. """ return_list = [] # Key order - first branch is for Python 3 compatibility on mini-projects, # second branch is for compatibility on final project. if isinstance(sort_keys, str): import pickle keys = pickle.load(open(sort_keys, "rb")) elif sort_keys: keys = sorted(dictionary.keys()) else: keys = dictionary.keys() for key in keys: tmp_list = [] for feature in features: try: dictionary[key][feature] except KeyError: print("error: key ", feature, " not present") return value = dictionary[key][feature] if value == "NaN" and remove_NaN: value = 0 tmp_list.append(float(value)) # Logic for deciding whether or not to add the data point. append = True # exclude 'poi' class as criteria. if features[0] == 'poi': test_list = tmp_list[1:] else: test_list = tmp_list ### if all features are zero and you want to remove ### data points that are all zero, do that here if remove_all_zeroes: append = False for item in test_list: if item != 0 and item != "NaN": append = True break ### if any features for a given data point are zero ### and you want to remove data points with any zeroes, ### handle that here if remove_any_zeroes: if 0 in test_list or "NaN" in test_list: append = False ### Append the data point if flagged for addition. if append: return_list.append(np.array(tmp_list)) return np.array(return_list) def targetFeatureSplit(data): """ given a numpy array like the one returned from featureFormat, separate out the first feature and put it into its own list (this should be the quantity you want to predict) return targets and features as separate lists (sklearn can generally handle both lists and numpy arrays as input formats when training/predicting) """ target = [] features = [] for item in data: target.append(item[0]) features.append(item[1:]) return target, features
PypiClean
/OERPLib-0.8.4.tar.gz/OERPLib-0.8.4/oerplib/rpc/xmlrpclib_custom.py
import xmlrpclib import httplib import socket import sys from urlparse import urlparse # Defined later following the version of Python used TimeoutTransport = None TimeoutSafeTransport = None class TimeoutServerProxy(xmlrpclib.ServerProxy): """xmlrpclib.ServerProxy overload to manage the timeout of the socket.""" def __init__(self, *args, **kwargs): url = args[0] https_ok = urlparse(url).scheme == 'https' t = https_ok and TimeoutSafeTransport() or TimeoutTransport() t.timeout = kwargs.get('timeout', 120) if 'timeout' in kwargs: del kwargs['timeout'] kwargs['transport'] = t xmlrpclib.ServerProxy.__init__(self, *args, **kwargs) if sys.version_info <= (2, 7): # Python 2.5 and 2.6 # -- xmlrpclib.Transport with timeout support -- class TimeoutHTTPPy26(httplib.HTTP): def __init__(self, host='', port=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if port == 0: port = None self._setup(self._connection_class(host, port, strict, timeout)) class TimeoutTransportPy26(xmlrpclib.Transport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.Transport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): host, extra_headers, x509 = self.get_host_info(host) conn = TimeoutHTTPPy26(host, timeout=self.timeout) return conn # -- xmlrpclib.SafeTransport with timeout support -- class TimeoutHTTPSPy26(httplib.HTTPS): def __init__(self, host='', port=None, key_file=None, cert_file=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): if port == 0: port = None self._setup(self._connection_class( host, port, key_file, cert_file, strict, timeout)) self.key_file = key_file self.cert_file = cert_file class TimeoutSafeTransportPy26(xmlrpclib.SafeTransport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.Transport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): host, extra_headers, x509 = self.get_host_info(host) conn = TimeoutHTTPSPy26(host, timeout=self.timeout) return conn # Define the TimeTransport and TimeSafeTransport class version to use TimeoutTransport = TimeoutTransportPy26 TimeoutSafeTransport = TimeoutSafeTransportPy26 else: # Python 2.7 and 3.X # -- xmlrpclib.Transport with timeout support -- class TimeoutHTTPConnectionPy27(httplib.HTTPConnection): def __init__(self, timeout, *args, **kwargs): httplib.HTTPConnection.__init__(self, *args, **kwargs) self.timeout = timeout def connect(self): httplib.HTTPConnection.connect(self) self.sock.settimeout(self.timeout) class TimeoutTransportPy27(xmlrpclib.Transport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.Transport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, TimeoutHTTPConnectionPy27( self.timeout, chost) return self._connection[1] # -- xmlrpclib.SafeTransport with timeout support -- class TimeoutHTTPSConnectionPy27(httplib.HTTPSConnection): def __init__(self, timeout, *args, **kwargs): httplib.HTTPSConnection.__init__(self, *args, **kwargs) self.timeout = timeout def connect(self): httplib.HTTPSConnection.connect(self) self.sock.settimeout(self.timeout) class TimeoutSafeTransportPy27(xmlrpclib.SafeTransport): def __init__(self, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *args, **kwargs): xmlrpclib.SafeTransport.__init__(self, *args, **kwargs) self.timeout = timeout def make_connection(self, host): if self._connection and host == self._connection[0]: return self._connection[1] chost, self._extra_headers, x509 = self.get_host_info(host) self._connection = host, TimeoutHTTPSConnectionPy27( self.timeout, chost) return self._connection[1] # Define the TimeTransport and TimeSafeTransport class version to use TimeoutTransport = TimeoutTransportPy27 TimeoutSafeTransport = TimeoutSafeTransportPy27 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
PypiClean
/IneryPy-0.1.tar.gz/IneryPy-0.1/api/types.py
import datetime as dt import pytz from api.utils import * import json import binascii import struct import six import colander from colander import Invalid from collections import OrderedDict from api.utils import * from api.types import * from api.keys import * class BaseSchema(colander.SchemaNode): required = True class StringSchema(BaseSchema): schema_type = colander.String # str schemas class NameSchema(StringSchema): pass class AccountNameSchema(NameSchema): pass class PermissionNameSchema(NameSchema): pass class ActionNameSchema(NameSchema): pass class TableNameSchema(NameSchema): pass class ScopeNameSchema(NameSchema): pass # boolean class BooleanSchema(BaseSchema): schema_type = colander.Bool # numeric class IntSchema(BaseSchema): schema_type = colander.Int class HexBytesSchema(StringSchema): missing = colander.drop # Authority/permission class ThresholdSchema(IntSchema): pass class PublicKeySchema(StringSchema): pass class WeightSchema(IntSchema): pass class KeyWeightSchema(colander.MappingSchema): key = PublicKeySchema() weight = WeightSchema() class KeyWeightsSchema(colander.SequenceSchema): key = KeyWeightSchema() class PermissionLevelSchema(colander.MappingSchema): actor = AccountNameSchema() permission = PermissionNameSchema() class PermissionLevelsSchema(colander.SequenceSchema): permission = PermissionLevelSchema() class PermissionLevelWeightSchema(colander.MappingSchema): permission = PermissionLevelSchema() weight = WeightSchema() class PermissionLevelWeightsSchema(colander.SequenceSchema): permission_level = PermissionLevelWeightSchema() class WaitSecSchema(IntSchema): pass class WaitWeightSchema(colander.MappingSchema): wait_sec = WaitSecSchema() weight = WeightSchema() class WaitWeightsSchema(colander.SequenceSchema): waits = WaitWeightSchema() class AuthoritySchema(colander.MappingSchema): threshold = ThresholdSchema() keys = KeyWeightsSchema() accounts = PermissionLevelWeightsSchema() waits = WaitWeightsSchema() class PermNameSchema(BaseSchema): schema_type = colander.String class ParentSchema(StringSchema): pass class PermissionSchema(colander.MappingSchema): perm_name = PermNameSchema() parent = ParentSchema() required_auth = AuthoritySchema() # def validate_data_schema(node, value): # if not isinstance(value, dict) or not isinstance(value, str): # raise colander.Invalid(node, '{} is not a valid data schema'.format(value)) class DataSchema(colander.SchemaType): def serialize(self, node, appstruct): if appstruct is colander.null: return colander.null impl = colander.Mapping() if isinstance(appstruct, str): impl = StringSchema() return impl.serialize(node, appstruct) def deserialize(self, node, cstruct): return cstruct ############################# # message actions attributes ############################# class ActionSchema(colander.MappingSchema): account = AccountNameSchema() name = ActionNameSchema() authorization = PermissionLevelsSchema() # if data is there it can be a HexBytesSchema or DataSchema hex_data = HexBytesSchema() data = colander.SchemaNode(DataSchema()) class ActionsSchema(colander.SequenceSchema): action = ActionSchema() class ContextActionsSchema(colander.SequenceSchema): default = [] missing = [] action = ActionSchema() class ExtensionSchema(colander.MappingSchema): type = IntSchema() data = HexBytesSchema() class ExtensionsSchema(colander.SequenceSchema): default = [] missing = [] extension = ExtensionSchema() ############################# # message header attributes ############################# class TimeSchema(BaseSchema): schema_type = colander.DateTime class RefBlockNumSchema(IntSchema): pass class RefBlockPrefixSchema(IntSchema): pass class NetUsageWordsSchema(IntSchema): default = 0 missing = 0 class MaxCpuUsageMsSchema(IntSchema): default = 0 missing = 0 class DelaySecSchema(IntSchema): default = 0 missing = 0 class SignaturesSchema(colander.Sequence): signatures = StringSchema() class TransactionSchema(colander.MappingSchema): # header expiration = TimeSchema() ref_block_num = RefBlockNumSchema() ref_block_prefix = RefBlockPrefixSchema() net_usage_words = NetUsageWordsSchema() max_cpu_usage_ms = MaxCpuUsageMsSchema() delay_sec = DelaySecSchema() # body context_free_actions = ContextActionsSchema() actions = ActionsSchema() transaction_extensions = ExtensionsSchema() # signed transaction class SignedTransactionSchema(colander.MappingSchema): compression = StringSchema transaction = TransactionSchema() signatures = SignaturesSchema() # final transaction class PushTransactionSchema(colander.MappingSchema): transaction_id = StringSchema() broadcast = BooleanSchema() transaction = SignedTransactionSchema() class TransactionsSchema(colander.SequenceSchema): transactions = TransactionSchema() ############################# # get info ############################# class ChainInfoSchema(colander.MappingSchema): server_version = StringSchema() chain_id = StringSchema() head_block_num = IntSchema() last_irreversible_block_num = IntSchema() last_irreversible_block_id = StringSchema() head_block_id = StringSchema() head_block_time = TimeSchema() head_block_producer = StringSchema() virtual_block_cpu_limit = IntSchema() virtual_block_net_limit = IntSchema() block_cpu_limit = IntSchema() block_net_limit = IntSchema() ############################# # get block ############################# class ProducerSchema(colander.SchemaNode): schema_type = colander.String missing = 'null' default = 'null' required = False class HeaderExtsSchema(colander.SequenceSchema): header_extensions = ExtensionsSchema() class BlockExtsSchema(colander.SequenceSchema): block_extensions = ExtensionsSchema() class BlockInfoSchema(colander.MappingSchema): timestamp = TimeSchema() producer = StringSchema() confirmed = IntSchema() previous = StringSchema() transaction_mroot = StringSchema() action_mroot = StringSchema() schedule_version = IntSchema new_producers = ProducerSchema() header_extensions = HeaderExtsSchema() producer_signature = StringSchema # TODO #transactions = [], block_extensions = BlockExtsSchema() id = StringSchema() block_num = IntSchema() ref_block_prefix = IntSchema() ############################# # abi ############################# class AbiTypeSchema(colander.MappingSchema): new_type_name = StringSchema() type = StringSchema() class AbiTypesSchema(colander.SequenceSchema): default = [] missing = [] types = AbiTypeSchema() class AbiStructFieldSchema(colander.MappingSchema): name = StringSchema() type = StringSchema() class AbiStructFieldsSchema(colander.SequenceSchema): default = [] missing = [] fields = AbiStructFieldSchema() class AbiStructBaseSchema(StringSchema): default = "" missing = "" class AbiStructSchema(colander.MappingSchema): name = StringSchema() base = AbiStructBaseSchema() fields = AbiStructFieldsSchema() class AbiStructsSchema(colander.SequenceSchema): structs = AbiStructSchema() class AbiRicardianStrSchema(StringSchema): default = "" missing = "" required = False class AbiActionSchema(colander.MappingSchema): name = StringSchema() type = StringSchema() ricardian_contract = AbiRicardianStrSchema() class AbiActionsSchema(colander.SequenceSchema): actions = AbiActionSchema() class AbiTableKey(StringSchema): pass # required = False class AbiTablesKey(colander.SequenceSchema): default = [] missing = [] keys = AbiTableKey() class AbiTableSchema(colander.MappingSchema): name = StringSchema() index_type = StringSchema() key_names = AbiTablesKey() key_types = AbiTablesKey() type = StringSchema() class AbiTablesSchema(colander.SequenceSchema): missing = [] default = [] tables = AbiTableSchema() class AbiRicardianClauseSchema(colander.MappingSchema): id = StringSchema() body = StringSchema() class AbiRicardianClausesSchema(colander.SequenceSchema): required = False missing = [] default = [] rcs = AbiRicardianClauseSchema() # placeholder class AbiErrorMessageSchema(StringSchema): required = False class AbiErrorMessagesSchema(colander.SequenceSchema): default = [] missing = [] required = False error_messages = AbiErrorMessageSchema() # placeholder class AbiExtensionSchema(StringSchema): required = False class AbiExtensionsSchema(colander.SequenceSchema): default = [] missing = [] required = False abi_extensions = AbiExtensionSchema() # placeholder class AbiVariantSchema(StringSchema): required = False class AbiVariantsSchema(colander.SequenceSchema): default = [] missing = [] required = False variants = AbiVariantSchema() class AbiCommentSchema(StringSchema): required = False default = "" missing = "" class AbiSchema(colander.MappingSchema): version = StringSchema() types = AbiTypesSchema() structs = AbiStructsSchema() actions = AbiActionsSchema() tables = AbiTablesSchema() ricardian_clauses = AbiRicardianClausesSchema() error_messages = AbiErrorMessagesSchema() abi_extensions = AbiExtensionsSchema() variants = AbiVariantsSchema() ############################# # ineryytest ############################# def test_param_validator(node, value): if not isinstance(value, dict): raise colander.Invalid(node, '{} is not a valid dictionary'.format(value)) class TestEnvSchema(colander.MappingSchema): url = StringSchema() class TestAuthSchema(colander.MappingSchema): required = False default = {} missing = {} actor = StringSchema() permission = StringSchema() key = StringSchema() class TestResultsSchema(colander.SequenceSchema): results = StringSchema() class TestQuerySchema(colander.MappingSchema): query = StringSchema() parameters = colander.SchemaNode( colander.Mapping(unknown='preserve'), validator=test_param_validator ) results = TestResultsSchema() class TestQueriesSchema(colander.SequenceSchema): required = False missing = [] default = [] queries = TestQuerySchema() class TestCommentSchema(colander.String): required = False missing = "" default = "" class TestActionSchema(colander.MappingSchema): comment = TestCommentSchema() action = StringSchema() contract = StringSchema() authorization = TestAuthSchema() parameters = colander.SchemaNode( colander.Mapping(unknown='preserve'), validator=test_param_validator ) exception = BooleanSchema() queries = TestQueriesSchema() class TestActionsSchema(colander.SequenceSchema): actions = TestActionSchema() class TestSchema(colander.MappingSchema): name = StringSchema() authorization = TestAuthSchema() actions = TestActionsSchema() class TestsSchema(colander.SequenceSchema): tests = TestSchema() class TestDocSchema(colander.MappingSchema): environment = TestEnvSchema() tests = TestsSchema() class BaseSchema(colander.SchemaNode): required = True class StringSchema(BaseSchema): schema_type = colander.String # str schemas class NameSchema(StringSchema): pass class AccountNameSchema(NameSchema): pass class PermissionNameSchema(NameSchema): pass class ActionNameSchema(NameSchema): pass class TableNameSchema(NameSchema): pass class ScopeNameSchema(NameSchema): pass # boolean class BooleanSchema(BaseSchema): schema_type = colander.Bool # numeric class IntSchema(BaseSchema): schema_type = colander.Int class HexBytesSchema(StringSchema): missing = colander.drop # Authority/permission class ThresholdSchema(IntSchema): pass class PublicKeySchema(StringSchema): pass class WeightSchema(IntSchema): pass class KeyWeightSchema(colander.MappingSchema): key = PublicKeySchema() weight = WeightSchema() class KeyWeightsSchema(colander.SequenceSchema): key = KeyWeightSchema() class PermissionLevelSchema(colander.MappingSchema): actor = AccountNameSchema() permission = PermissionNameSchema() class PermissionLevelsSchema(colander.SequenceSchema): permission = PermissionLevelSchema() class PermissionLevelWeightSchema(colander.MappingSchema): permission = PermissionLevelSchema() weight = WeightSchema() class PermissionLevelWeightsSchema(colander.SequenceSchema): permission_level = PermissionLevelWeightSchema() class WaitSecSchema(IntSchema): pass class WaitWeightSchema(colander.MappingSchema): wait_sec = WaitSecSchema() weight = WeightSchema() class WaitWeightsSchema(colander.SequenceSchema): waits = WaitWeightSchema() class AuthoritySchema(colander.MappingSchema): threshold = ThresholdSchema() keys = KeyWeightsSchema() accounts = PermissionLevelWeightsSchema() waits = WaitWeightsSchema() class PermNameSchema(BaseSchema): schema_type = colander.String class ParentSchema(StringSchema): pass class PermissionSchema(colander.MappingSchema): perm_name = PermNameSchema() parent = ParentSchema() required_auth = AuthoritySchema() # def validate_data_schema(node, value): # if not isinstance(value, dict) or not isinstance(value, str): # raise colander.Invalid(node, '{} is not a valid data schema'.format(value)) class DataSchema(colander.SchemaType): def serialize(self, node, appstruct): if appstruct is colander.null: return colander.null impl = colander.Mapping() if isinstance(appstruct, str): impl = StringSchema() return impl.serialize(node, appstruct) def deserialize(self, node, cstruct): return cstruct ############################# # message actions attributes ############################# class ActionSchema(colander.MappingSchema): account = AccountNameSchema() name = ActionNameSchema() authorization = PermissionLevelsSchema() # if data is there it can be a HexBytesSchema or DataSchema hex_data = HexBytesSchema() data = colander.SchemaNode(DataSchema()) class ActionsSchema(colander.SequenceSchema): action = ActionSchema() class ContextActionsSchema(colander.SequenceSchema): default = [] missing = [] action = ActionSchema() class ExtensionSchema(colander.MappingSchema): type = IntSchema() data = HexBytesSchema() class ExtensionsSchema(colander.SequenceSchema): default = [] missing = [] extension = ExtensionSchema() ############################# # message header attributes ############################# class TimeSchema(BaseSchema): schema_type = colander.DateTime class RefBlockNumSchema(IntSchema): pass class RefBlockPrefixSchema(IntSchema): pass class NetUsageWordsSchema(IntSchema): default = 0 missing = 0 class MaxCpuUsageMsSchema(IntSchema): default = 0 missing = 0 class DelaySecSchema(IntSchema): default = 0 missing = 0 class SignaturesSchema(colander.Sequence): signatures = StringSchema() class TransactionSchema(colander.MappingSchema): # header expiration = TimeSchema() ref_block_num = RefBlockNumSchema() ref_block_prefix = RefBlockPrefixSchema() net_usage_words = NetUsageWordsSchema() max_cpu_usage_ms = MaxCpuUsageMsSchema() delay_sec = DelaySecSchema() # body context_free_actions = ContextActionsSchema() actions = ActionsSchema() transaction_extensions = ExtensionsSchema() # signed transaction class SignedTransactionSchema(colander.MappingSchema): compression = StringSchema transaction = TransactionSchema() signatures = SignaturesSchema() # final transaction class PushTransactionSchema(colander.MappingSchema): transaction_id = StringSchema() broadcast = BooleanSchema() transaction = SignedTransactionSchema() class TransactionsSchema(colander.SequenceSchema): transactions = TransactionSchema() ############################# # get info ############################# class ChainInfoSchema(colander.MappingSchema): server_version = StringSchema() chain_id = StringSchema() head_block_num = IntSchema() last_irreversible_block_num = IntSchema() last_irreversible_block_id = StringSchema() head_block_id = StringSchema() head_block_time = TimeSchema() head_block_producer = StringSchema() virtual_block_cpu_limit = IntSchema() virtual_block_net_limit = IntSchema() block_cpu_limit = IntSchema() block_net_limit = IntSchema() ############################# # get block ############################# class ProducerSchema(colander.SchemaNode): schema_type = colander.String missing = 'null' default = 'null' required = False class HeaderExtsSchema(colander.SequenceSchema): header_extensions = ExtensionsSchema() class BlockExtsSchema(colander.SequenceSchema): block_extensions = ExtensionsSchema() class BlockInfoSchema(colander.MappingSchema): timestamp = TimeSchema() producer = StringSchema() confirmed = IntSchema() previous = StringSchema() transaction_mroot = StringSchema() action_mroot = StringSchema() schedule_version = IntSchema new_producers = ProducerSchema() header_extensions = HeaderExtsSchema() producer_signature = StringSchema # TODO #transactions = [], block_extensions = BlockExtsSchema() id = StringSchema() block_num = IntSchema() ref_block_prefix = IntSchema() ############################# # abi ############################# class AbiTypeSchema(colander.MappingSchema): new_type_name = StringSchema() type = StringSchema() class AbiTypesSchema(colander.SequenceSchema): default = [] missing = [] types = AbiTypeSchema() class AbiStructFieldSchema(colander.MappingSchema): name = StringSchema() type = StringSchema() class AbiStructFieldsSchema(colander.SequenceSchema): default = [] missing = [] fields = AbiStructFieldSchema() class AbiStructBaseSchema(StringSchema): default = "" missing = "" class AbiStructSchema(colander.MappingSchema): name = StringSchema() base = AbiStructBaseSchema() fields = AbiStructFieldsSchema() class AbiStructsSchema(colander.SequenceSchema): structs = AbiStructSchema() class AbiRicardianStrSchema(StringSchema): default = "" missing = "" required = False class AbiActionSchema(colander.MappingSchema): name = StringSchema() type = StringSchema() ricardian_contract = AbiRicardianStrSchema() class AbiActionsSchema(colander.SequenceSchema): actions = AbiActionSchema() class AbiTableKey(StringSchema): pass # required = False class AbiTablesKey(colander.SequenceSchema): default = [] missing = [] keys = AbiTableKey() class AbiTableSchema(colander.MappingSchema): name = StringSchema() index_type = StringSchema() key_names = AbiTablesKey() key_types = AbiTablesKey() type = StringSchema() class AbiTablesSchema(colander.SequenceSchema): missing = [] default = [] tables = AbiTableSchema() class AbiRicardianClauseSchema(colander.MappingSchema): id = StringSchema() body = StringSchema() class AbiRicardianClausesSchema(colander.SequenceSchema): required = False missing = [] default = [] rcs = AbiRicardianClauseSchema() # placeholder class AbiErrorMessageSchema(StringSchema): required = False class AbiErrorMessagesSchema(colander.SequenceSchema): default = [] missing = [] required = False error_messages = AbiErrorMessageSchema() # placeholder class AbiExtensionSchema(StringSchema): required = False class AbiExtensionsSchema(colander.SequenceSchema): default = [] missing = [] required = False abi_extensions = AbiExtensionSchema() # placeholder class AbiVariantSchema(StringSchema): required = False class AbiVariantsSchema(colander.SequenceSchema): default = [] missing = [] required = False variants = AbiVariantSchema() class AbiCommentSchema(StringSchema): required = False default = "" missing = "" class AbiSchema(colander.MappingSchema): version = StringSchema() types = AbiTypesSchema() structs = AbiStructsSchema() actions = AbiActionsSchema() tables = AbiTablesSchema() ricardian_clauses = AbiRicardianClausesSchema() error_messages = AbiErrorMessagesSchema() abi_extensions = AbiExtensionsSchema() variants = AbiVariantsSchema() ############################# # ineryytest ############################# def test_param_validator(node, value): if not isinstance(value, dict): raise colander.Invalid(node, '{} is not a valid dictionary'.format(value)) class TestEnvSchema(colander.MappingSchema): url = StringSchema() class TestAuthSchema(colander.MappingSchema): required = False default = {} missing = {} actor = StringSchema() permission = StringSchema() key = StringSchema() class TestResultsSchema(colander.SequenceSchema): results = StringSchema() class TestQuerySchema(colander.MappingSchema): query = StringSchema() parameters = colander.SchemaNode( colander.Mapping(unknown='preserve'), validator=test_param_validator ) results = TestResultsSchema() class TestQueriesSchema(colander.SequenceSchema): required = False missing = [] default = [] queries = TestQuerySchema() class TestCommentSchema(colander.String): required = False missing = "" default = "" class TestActionSchema(colander.MappingSchema): comment = TestCommentSchema() action = StringSchema() contract = StringSchema() authorization = TestAuthSchema() parameters = colander.SchemaNode( colander.Mapping(unknown='preserve'), validator=test_param_validator ) exception = BooleanSchema() queries = TestQueriesSchema() class TestActionsSchema(colander.SequenceSchema): actions = TestActionSchema() class TestSchema(colander.MappingSchema): name = StringSchema() authorization = TestAuthSchema() actions = TestActionsSchema() class TestsSchema(colander.SequenceSchema): tests = TestSchema() class TestDocSchema(colander.MappingSchema): environment = TestEnvSchema() tests = TestsSchema() def convert_little_endian(buf, format='q'): ''' ''' return struct.pack('<{}'.format(format), buf) def convert_big_endian(buf, format="I"): ''' ''' # return the first value of the tuple that is returned by unpack return struct.unpack('<{}'.format(format), buf)[0] # json encoder class INREncoder(json.JSONEncoder): def default(self, o): if isinstance(o, Action): return o.__dict__ if isinstance(o, Authorization): return o.__dict__ if isinstance(o, dt.datetime): return o.isoformat() class Name(str): hex_str_len = 16 class AccountName(Name): pass class PermissionName(Name): pass class ActionName(Name): pass class TableName(Name): pass class ScopeName(Name): pass class Byte(int): # length of hex str hex_str_len = 2 class UInt16(int): # length of hex str hex_str_len = 4 class UInt32(int): # length of hex str hex_str_len = 8 class UInt64(int): # length of hex str hex_str_len = 16 class Int16(int): # length of hex str hex_str_len = 4 class Int32(int): # length of hex str hex_str_len = 8 class Int64(int): # length of hex str hex_str_len = 16 class Float(float): # length of hex str hex_str_len = 8 class VarUInt: def __init__(self, val=""): ''' ''' self._val = val self._b_arr = bytearray() def _push_byte(self, val): self._b_arr.append(int(val)) def encode(self): ''' ''' # ensure value is an int val = int(self._val) buf = int((val) & 0x7f) val >>= 7 buf |= (((val > 0) if 1 else 0) << 7) self._push_byte(buf) while val: buf = int((val) & 0x7f) val >>= 7 buf |= (((val > 0) if 1 else 0) << 7) self._push_byte(buf) return self._b_arr def _pop(self, buf, length): return buf[:length], buf[length:] def decode(self, buf): ''' ''' shift = 0 result = 0 while True: tmp, buf = self._pop(buf, 2) i = hex_to_int(tmp) result |= (i & 0x7f) << shift shift += 7 if not(i & 0x80): break return result, buf class BaseObject(object): def __init__(self, d): ''' ''' try: self._obj = self._validator.deserialize(d) except Invalid: raise INRInvalidSchema('Unable to process schema for {}'.format(type(self))) # instantiate the class for k, v in self._obj.items(): setattr(self, k, v) # clean up del self._obj del self._validator def __repr__(self): ''' ''' return '{}({})'.format(self.__class__, self.__dict__) def _encode_buffer(self, value): ''' ''' return INRBuffer(value).encode() def _create_obj_array(self, arr, class_type): ''' ''' new_arr = [] for item in arr: new_arr.append(class_type(item)) return new_arr class Action(BaseObject): def __init__(self, d): ''' ''' self._validator = ActionSchema() super(Action, self).__init__(d) # setup permissions self.authorization = self._create_obj_array(self.authorization, Authorization) def encode(self): ''' ''' acct = self._encode_buffer(AccountName(self.account)) name = self._encode_buffer(Name(self.name)) auth = self._encode_buffer(self.authorization) # need to figure out how to process data # get length data_len = self._encode_buffer(VarUInt(len(self.data) / 2)) data = data_len + self.data return '{}{}{}{}'.format(acct, name, auth, data) class Asset: def __init__(self, value, precision=4): # self.amount = amt # self.symbol = sym # self.precision = precision self.from_string(value) def __str__(self): return '{amount:.{precision}f} {symbol}'.format(amount=self.amount, symbol=self.symbol, precision=self.precision) def __add__(self, other): if self.symbol != other.symbol: raise TypeError('Symbols must match: {} != {}', self.symbol, other.symbol) return Asset(self.amount + other.amount, self.symbol) def __sub__(self, other): if self.amount - other.amount < 0: raise ValueError('Subtraction would result in a negative.') if self.symbol != other.symbol: raise TypeError('Symbols must match: {} != {}', self.symbol, other.symbol) return Asset(self.amount - other.amount, self.symbol) def from_string(self, s): splt = s.split() try: self.amount = float(splt[0]) self.symbol = splt[1] self.precision = len(splt[0].split(".")[1]) except IndexError: raise IndexError('Invalid string format given. Must be in the formst <float> <currency_type>') def _string_to_symbol(self): ''' ''' rslt = 0 cnt = 0 while cnt < len(self.symbol): letter = self.symbol[cnt] if letter >= 'A' or letter <= 'Z': l = ord(letter) rslt |= (UInt64(l) << (8 * (cnt + 1))) else: raise ValueError("{} contains an invalid symbol. Must be [A-Z].".format(self.symbol)) cnt += 1 rslt |= UInt64(self.precision) return INRBuffer(UInt64(rslt)).encode() def encode(self): ''' ''' power = '1'.ljust(self.precision + len('1'), '0') amount = INRBuffer(UInt64(self.amount * UInt64(power))).encode() symbol = self._string_to_symbol() return '{amount}{symbol}'.format(amount=amount, symbol=symbol) class AbiType(BaseObject): def __init__(self, d): self._validator = AbiTypeSchema() super(AbiType, self).__init__(d) def encode(self): new_type_name = self._encode_buffer(self.new_type_name) type = self._encode_buffer(self.type) return '{}{}'.format(new_type_name, type) class AbiStructField(BaseObject): def __init__(self, d): self._validator = AbiStructFieldSchema() super(AbiStructField, self).__init__(d) def encode(self): name = self._encode_buffer(self.name) type = self._encode_buffer(self.type) return '{}{}'.format(name, type) class AbiStruct(BaseObject): def __init__(self, d): self._validator = AbiStructSchema() super(AbiStruct, self).__init__(d) self.fields = self._create_obj_array(self.fields, AbiStructField) def encode(self): name = self._encode_buffer(self.name) base = self._encode_buffer(self.base) fields = self._encode_buffer(self.fields) return '{}{}{}'.format(name, base, fields) class AbiAction(BaseObject): def __init__(self, d): self._validator = AbiActionSchema() super(AbiAction, self).__init__(d) def encode(self): name = self._encode_buffer(Name(self.name)) type = self._encode_buffer(self.type) ricardian_contract = self._encode_buffer(self.ricardian_contract) return '{}{}{}'.format(name, type, ricardian_contract) class AbiTable(BaseObject): def __init__(self, d): self._validator = AbiTableSchema() super(AbiTable, self).__init__(d) def encode(self): name = self._encode_buffer(Name(self.name)) index_type = self._encode_buffer(self.index_type) key_names = self._encode_buffer(self.key_names) key_types = self._encode_buffer(self.key_types) type = self._encode_buffer(self.type) return '{}{}{}{}{}'.format(name, index_type, key_names, key_types, type) class AbiRicardianClauses(BaseObject): def __init__(self, d): self._validator = AbiRicardianClauseSchema() super(AbiRicardianClauses, self).__init__(d) def encode(self): id = self._encode_buffer(self.id) body = self._encode_buffer(self.body) return '{}{}'.format(id, body) class AbiErrorMessages(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiErrorMessagesSchema() super(AbiErrorMessages, self).__init__(d) def encode(): raise NotImplementedError class AbiExtensions(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiExtensionsSchema() super(AbiExtensions, self).__init__(d) def encode(): raise NotImplementedError class AbiVariants(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiVariantsSchema() super(AbiVariants, self).__init__(d) def encode(): raise NotImplementedError class Abi(BaseObject): _abi_map = { # name 'name': Name(), 'string': str(), # numbers 'bool': Byte(), 'uint8': Byte(), 'uint16': UInt16(), 'uint32': UInt32(), 'uint64': UInt64(), 'int8': Byte(), # NotImplemented 'int16': Int16(), # NotImplemented 'int32': Int32(), # NotImplemented 'int64': Int64(), # NotImplemented 'float64': Float(), # NotImplemented # 'varuint32': VarUInt # NotImplemented # complex 'asset': Asset("1.0000 INR"), # 'checksum256': str, # NotImplemented # 'block_timestamp_type': UInt64, # NotImplemented # 'time_point': UInt64, # NotImplemented # 'connector': str, # NotImplemented # 'public_key': str, # NotImplemented # 'authority': str, # NotImplemented # 'block_header': str, # NotImplemented # 'bytes': str, # NotImplemented # 'permission_level': str, # NotImplemented # 'permission_level_weight': str, #NotImplemented } def __init__(self, d): ''' ''' self._validator = AbiSchema() super(Abi, self).__init__(d) self.types = self._create_obj_array(self.types, AbiType) self.structs = self._create_obj_array(self.structs, AbiStruct) self.actions = self._create_obj_array(self.actions, AbiAction) self.tables = self._create_obj_array(self.tables, AbiTable) self.ricardian_clauses = self._create_obj_array(self.ricardian_clauses, AbiRicardianClauses) self.error_messages = self._create_obj_array(self.error_messages, AbiErrorMessages) self.abi_extensions = self._create_obj_array(self.abi_extensions, AbiExtensions) self.variants = self._create_obj_array(self.variants, AbiVariants) def get_action(self, name): ''' ''' for act in self.actions: if act.name == name: return act raise INRUnknownObj('{} is not a valid action for this contract'.format(name)) def get_actions(self): actions = [] for act in self.actions: actions.append(act.name) return actions def get_struct(self, name): ''' ''' for struct in self.structs: if struct.name == name: return struct raise INRUnknownObj('{} is not a valid struct for this contract'.format(name)) def get_action_parameters(self, name): ''' ''' parameters = OrderedDict() # get the struct struct = self.get_struct(name) for field in struct.fields: f = field.type.strip('[]') if(f in self._abi_map): field_type = self._abi_map[f] # check if the field is a list if '[]' in field.type: field_type = [field_type] parameters[field.name] = field_type else: raise INRUnknownObj("{} is not a known abi type".format(field.type)) return parameters def get_raw(self): version = self._encode_buffer(self.version) # encode types types = self._encode_buffer(self.types) structs = self._encode_buffer(self.structs) actions = self._encode_buffer(self.actions) tables = self._encode_buffer(self.tables) ricardian_clauses = self._encode_buffer(self.ricardian_clauses) error_messages = self._encode_buffer(self.error_messages) abi_extensions = self._encode_buffer(self.abi_extensions) variants = self._encode_buffer(self.variants) return '{}{}{}{}{}{}{}{}{}'.format(version, types, structs, actions, tables, ricardian_clauses, error_messages, abi_extensions, variants) def encode(self): ''' ''' raw_abi = self.get_raw() # divide by two because it is hex length = self._encode_buffer(VarUInt(len(raw_abi) / 2)) return length + raw_abi def json_to_bin(self, name, data): # act = self.get_action(name) params = self.get_action_parameters(name) bin_buffer = '' for field in data: # create INRBuffer with value as a type of field if isinstance(params[field], list): field_type = type(params[field][0]) arr = [] for f in data[field]: print(f) arr.append(field_type(f)) field_buffer = INRBuffer(arr) else: field_type = type(params[field]) field_buffer = INRBuffer(field_type(data[field])) bin_buffer += field_buffer.encode() return bin_buffer class Authorization(BaseObject): def __init__(self, d): ''' ''' # create validator self._validator = PermissionLevelSchema() super(Authorization, self).__init__(d) def encode(self): ''' ''' actor = self._encode_buffer(AccountName(self.actor)) perms = self._encode_buffer(PermissionName(self.permission)) return '{}{}'.format(actor, perms) class ChainInfo(BaseObject): def __init__(self, d): ''' ''' self._validator = ChainInfoSchema() super(ChainInfo, self).__init__(d) class BlockInfo(BaseObject): def __init__(self, d): ''' ''' self._validator = BlockInfoSchema() super(BlockInfo, self).__init__(d) class Transaction(BaseObject): def __init__(self, d, chain_info, lib_info): ''' ''' # add defaults if 'expiration' not in d: d['expiration'] = str((dt.datetime.utcnow() + dt.timedelta(seconds=30)).replace(tzinfo=pytz.UTC)) if 'ref_block_num' not in d: d['ref_block_num'] = chain_info['last_irreversible_block_num'] & 0xFFFF if 'ref_block_prefix' not in d: d['ref_block_prefix'] = lib_info['ref_block_prefix'] # validate self._validator = TransactionSchema() super(Transaction, self).__init__(d) # parse actions self.actions = self._create_obj_array(self.actions, Action) def _encode_hdr(self): ''' ''' # convert exp_ts = (self.expiration - dt.datetime(1970, 1, 1, tzinfo=self.expiration.tzinfo)).total_seconds() exp = self._encode_buffer(UInt32(exp_ts)) ref_blk = self._encode_buffer(UInt16(self.ref_block_num & 0xffff)) ref_block_prefix = self._encode_buffer(UInt32(self.ref_block_prefix)) net_usage_words = self._encode_buffer(VarUInt(self.net_usage_words)) max_cpu_usage_ms = self._encode_buffer(Byte(self.max_cpu_usage_ms)) delay_sec = self._encode_buffer(VarUInt(self.delay_sec)) # create hdr buffer hdr = '{}{}{}{}{}{}'.format(exp, ref_blk, ref_block_prefix, net_usage_words, max_cpu_usage_ms, delay_sec) return hdr def encode(self): ''' ''' hdr_buf = self._encode_hdr() context_actions = self._encode_buffer(self.context_free_actions) actions = self._encode_buffer(self.actions) trans_exts = self._encode_buffer(self.transaction_extensions) return bytearray.fromhex(hdr_buf + context_actions + actions + trans_exts) def get_id(self): return sha256(self.encode()) class PackedTransaction: def __init__(self, trx, ce): self._cline = ce self._packed_trx = trx # empty header self._is_unpacked = False self._unpacked_trx = OrderedDict() def _decode_buffer(self, objType, buf): ''' ''' eBuf = INRBuffer("") return eBuf.decode(objType, buf) def _decode_header(self, buf): ''' ''' buf = self._packed_trx # get expiration buffer (exp, buf) = self._decode_buffer(UInt32(), buf) # get expiration in UTC exp_dt = dt.datetime.utcfromtimestamp(exp) self._unpacked_trx['expiration'] = exp_dt.strftime("%Y-%m-%dT%H:%M:%S") # get ref_block (ref_blk, buf) = self._decode_buffer(UInt16(), buf) self._unpacked_trx['ref_block_num'] = ref_blk # get ref_block_prefix (ref_blk_pre, buf) = self._decode_buffer(UInt32(), buf) self._unpacked_trx['ref_block_prefix'] = ref_blk_pre # get net usage (max_net_usage, buf) = self._decode_buffer(VarUInt(), buf) self._unpacked_trx['max_net_usage_words'] = max_net_usage # get cpu usage (max_cpu_usage, buf) = self._decode_buffer(Byte(), buf) self._unpacked_trx['max_cpu_usage_ms'] = max_cpu_usage # get delay sec (delay_sec, buf) = self._decode_buffer(VarUInt(), buf) self._unpacked_trx['delay_sec'] = delay_sec return buf def decode_actions(self, buf): ''' ''' # get length of action array actions = [] (length, act_buf) = self._decode_buffer(VarUInt(), buf) cnt = 0 # loop through array while cnt < length and length: # process action account/name (acct_name, act_buf) = self._decode_buffer(AccountName(), act_buf) (action_name, act_buf) = self._decode_buffer(ActionName(), act_buf) # get authorizations (auth, act_buf) = self.decode_authorizations(act_buf) # get data length (hex_data_len, act_buf) = self._decode_buffer(VarUInt(), act_buf) # get abi information contract_abi = self._cline.get_abi(acct_name) abi = Abi(contract_abi["abi"]) abi_act = abi.get_action(action_name) # temp check need to handle this better if abi_act["type"] != action_name: raise INRAbiProcessingError("Error processing the {} action".format(action_name)) abi_struct = abi.get_action_parameters(action_name) data = OrderedDict() # save data for hex_data data_diff = act_buf for a in abi_struct: (act_data, act_buf) = self._decode_buffer(abi_struct[a], act_buf) data[a] = act_data act = OrderedDict({ 'account': acct_name, 'name': action_name, "authorization": auth, "data": data, "hex_data": data_diff.rstrip(act_buf), }) actions.append(act) # increment count cnt += 1 return (actions, act_buf) def decode_authorizations(self, buf): ''' ''' auths = [] (length, auth_buf) = self._decode_buffer(VarUInt(), buf) cnt = 0 while cnt < length and length: # process action account/name (acct_name, auth_buf) = self._decode_buffer(AccountName(), auth_buf) (perm, auth_buf) = self._decode_buffer(ActionName(), auth_buf) auth = OrderedDict({ 'actor': acct_name, 'permission': perm, }) auths.append(auth) cnt += 1 return (auths, auth_buf) # placeholder until context_free_actions are implemented. Might be able to use self.decode_actions def decode_context_actions(self, buf): ''' ''' (length, ctx_buf) = self._decode_buffer(VarUInt(), buf) if length > 0: raise NotImplementedError("Currently inerypy does not support context_free_actions") # get length of action array return (length, ctx_buf) # placeholder until context_free_actions are implemented. Might be able to use self.decode_actions def decode_trx_extensions(self, buf): ''' ''' trx_ext = [] (length, ctx_buf) = self._decode_buffer(VarUInt(), buf) if length > 0: raise NotImplementedError("Currently inerypy does not support transaction extensions") # get length of action array return (trx_ext, ctx_buf) def get_id(self): ''' ''' return sha256(bytearray.fromhex(self._packed_trx)) def get_transaction(self): ''' ''' # only unpack once if not self._is_unpacked: # decode the header and get the rest of the trx back trx_buf = self._decode_header(self._packed_trx) # process list of context free actions (context_actions, trx_buf) = self.decode_context_actions(trx_buf) self._unpacked_trx['context_free_actions'] = context_actions # process actions (actions, trx_buf) = self.decode_actions(trx_buf) self._unpacked_trx['actions'] = actions # process transaction extensions (trx_ext, trx_buf) = self.decode_trx_extensions(trx_buf) self._unpacked_trx['transaction_extensions'] = trx_ext # set boolean self._is_unpacked = True return self._unpacked_trx class INRBuffer: def __init__(self, v): self._value = v self._count = 0 def _decode_number(self, val, format='L'): byte_val = binascii.unhexlify(val) return convert_big_endian(byte_val, format) def _decode_float(self, val, format='f'): byte_val = binascii.unhexlify(val) return struct.unpack(">{}".format(format), byte_val) def _decode_name(self, val, format='Q'): ''' ''' num = self._decode_number(val, format) return name_to_string(num) def _decode_str(self, val): ''' ''' # get length vu = VarUInt() (length, val) = vu.decode(val) string = '' leftover = val # if there is data parse it if length > 0: (str_data, leftover) = self._splice_buf(val, length * 2) string = binascii.unhexlify(str_data).decode() return (string, leftover) def _splice_buf(self, buf, length): return buf[:length], buf[length:] def _write_number(self, val, format='q'): ''' ''' le = convert_little_endian(val, format) return binascii.hexlify(le).decode() def _write_name(self, w_str): ''' ''' val = string_to_name(w_str) le = convert_little_endian(val, 'Q') return binascii.hexlify(le).decode() def _write_str(self, w_str): b = bytearray() length = VarUInt(len(w_str)).encode() b.extend(map(ord, w_str)) return binascii.hexlify(length + b).decode() def _write_varuint(self, vuint): buf = vuint.encode() return binascii.hexlify(buf).decode() def decode(self, objType, buf=None): leftover = "" if not buf: buf = self._value if isinstance(objType, UInt32): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'I') elif isinstance(objType, UInt16): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'H') elif isinstance(objType, VarUInt): (val, leftover) = objType.decode(buf) elif(isinstance(objType, Byte) or isinstance(objType, bool)): (hex_str, leftover) = self._splice_buf(buf, 2) val = hex_to_int(hex_str) elif isinstance(objType, Float): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_float(val, 'f') elif(isinstance(objType, int) or isinstance(objType, long)): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'q') elif (isinstance(objType, Name) or isinstance(objType, AccountName) or isinstance(objType, PermissionName) or isinstance(objType, ActionName) or isinstance(objType, TableName) or isinstance(objType, ScopeName)): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_name(val) elif isinstance(objType, str): (val, leftover) = self._decode_str(buf) elif(isinstance(objType, list)): # get count(VarUint) val = [] (length, leftover) = VarUInt("").decode(buf) while len(val) < length: (out, leftover) = self.decode(objType[0], leftover) val.append(out) else: raise INRBufferInvalidType("Cannot decode type: {}".format(type(objType))) return (val, leftover) def encode(self, val=None): if not val: val = self._value if (isinstance(val, Name) or isinstance(val, AccountName) or isinstance(val, PermissionName) or isinstance(val, ActionName) or isinstance(val, TableName) or isinstance(val, ScopeName)): val = self._write_name(val) return val elif(isinstance(val, str)): return self._write_str(val) elif(isinstance(val, Byte) or isinstance(val, bool)): # return self._write_number(val, '?') return int_to_hex(val) elif(isinstance(val, UInt16)): return self._write_number(val, 'H') elif(isinstance(val, UInt32)): return self._write_number(val, 'I') elif(isinstance(val, UInt64)): return self._write_number(val, 'q') elif(isinstance(val, Float)): return self._write_number(val, 'f') elif(isinstance(val, VarUInt)): # temp encoding return self._write_varuint(val) elif(isinstance(val, int) or isinstance(val, long)): return self._write_number(val, 'l') elif(isinstance(val, Action) or isinstance(val, AbiStruct) or isinstance(val, AbiStructField) or isinstance(val, AbiType) or isinstance(val, AbiAction) or isinstance(val, AbiTable) or isinstance(val, AbiRicardianClauses) or isinstance(val, AbiErrorMessages) or isinstance(val, AbiExtensions) or isinstance(val, AbiVariants) or isinstance(val, Asset) or isinstance(val, Authorization)): return val.encode() elif(isinstance(val, list)): buf = self._write_varuint(VarUInt(len(val))) for item in val: e_item = self.encode(item) buf = '{}{}'.format(buf, e_item) return buf else: raise INRBufferInvalidType('Cannot encode type: {}'.format(type(val))) class InvalidKeyFile(Exception): ''' Raised when the key file format is invalid ''' pass class INRKeyError(Exception): ''' Raised when there is an INRKey error ''' pass class INRMsigInvalidProposal(Exception): ''' Raised when an invalid proposal is queried''' pass class INRBufferInvalidType(Exception): ''' Raised when trying to encode/decode an invalid type ''' pass class INRInvalidSchema(Exception): ''' Raised when trying to process a schema ''' pass class INRUnknownObj(Exception): ''' Raised when an object is not found in the ABI ''' pass class INRAbiProcessingError(Exception): ''' Raised when the abi action cannot be processed ''' pass class INRSetSameCode(Exception): ''' Raised when the code would not change on a set''' pass class INRSetSameAbi(Exception): ''' Raised when the abi would not change on a set''' pass def convert_little_endian(buf, format='q'): ''' ''' return struct.pack('<{}'.format(format), buf) def convert_big_endian(buf, format="I"): ''' ''' # return the first value of the tuple that is returned by unpack return struct.unpack('<{}'.format(format), buf)[0] # json encoder class INREncoder(json.JSONEncoder): def default(self, o): if isinstance(o, Action): return o.__dict__ if isinstance(o, Authorization): return o.__dict__ if isinstance(o, dt.datetime): return o.isoformat() class Name(str): hex_str_len = 16 class AccountName(Name): pass class PermissionName(Name): pass class ActionName(Name): pass class TableName(Name): pass class ScopeName(Name): pass class Byte(int): # length of hex str hex_str_len = 2 class UInt16(int): # length of hex str hex_str_len = 4 class UInt32(int): # length of hex str hex_str_len = 8 class UInt64(int): # length of hex str hex_str_len = 16 class Int16(int): # length of hex str hex_str_len = 4 class Int32(int): # length of hex str hex_str_len = 8 class Int64(int): # length of hex str hex_str_len = 16 class Float(float): # length of hex str hex_str_len = 8 if six.PY3: class long(int): pass class VarUInt: def __init__(self, val=""): ''' ''' self._val = val self._b_arr = bytearray() def _push_byte(self, val): self._b_arr.append(int(val)) def encode(self): ''' ''' # ensure value is an int val = int(self._val) buf = int((val) & 0x7f) val >>= 7 buf |= (((val > 0) if 1 else 0) << 7) self._push_byte(buf) while val: buf = int((val) & 0x7f) val >>= 7 buf |= (((val > 0) if 1 else 0) << 7) self._push_byte(buf) return self._b_arr def _pop(self, buf, length): return buf[:length], buf[length:] def decode(self, buf): ''' ''' shift = 0 result = 0 while True: tmp, buf = self._pop(buf, 2) i = hex_to_int(tmp) result |= (i & 0x7f) << shift shift += 7 if not(i & 0x80): break return result, buf class BaseObject(object): def __init__(self, d): ''' ''' try: self._obj = self._validator.deserialize(d) except Invalid: raise INRInvalidSchema('Unable to process schema for {}'.format(type(self))) # instantiate the class for k, v in self._obj.items(): setattr(self, k, v) # clean up del self._obj del self._validator def __repr__(self): ''' ''' return '{}({})'.format(self.__class__, self.__dict__) def _encode_buffer(self, value): ''' ''' return INRBuffer(value).encode() def _create_obj_array(self, arr, class_type): ''' ''' new_arr = [] for item in arr: new_arr.append(class_type(item)) return new_arr class Action(BaseObject): def __init__(self, d): ''' ''' self._validator = ActionSchema() super(Action, self).__init__(d) # setup permissions self.authorization = self._create_obj_array(self.authorization, Authorization) def encode(self): ''' ''' acct = self._encode_buffer(AccountName(self.account)) name = self._encode_buffer(Name(self.name)) auth = self._encode_buffer(self.authorization) # need to figure out how to process data # get length data_len = self._encode_buffer(VarUInt(len(self.data) / 2)) data = data_len + self.data return '{}{}{}{}'.format(acct, name, auth, data) class Asset: def __init__(self, value, precision=4): # self.amount = amt # self.symbol = sym # self.precision = precision self.from_string(value) def __str__(self): return '{amount:.{precision}f} {symbol}'.format(amount=self.amount, symbol=self.symbol, precision=self.precision) def __add__(self, other): if self.symbol != other.symbol: raise TypeError('Symbols must match: {} != {}', self.symbol, other.symbol) return Asset(self.amount + other.amount, self.symbol) def __sub__(self, other): if self.amount - other.amount < 0: raise ValueError('Subtraction would result in a negative.') if self.symbol != other.symbol: raise TypeError('Symbols must match: {} != {}', self.symbol, other.symbol) return Asset(self.amount - other.amount, self.symbol) def from_string(self, s): splt = s.split() try: self.amount = float(splt[0]) self.symbol = splt[1] self.precision = len(splt[0].split(".")[1]) except IndexError: raise IndexError('Invalid string format given. Must be in the formst <float> <currency_type>') def _string_to_symbol(self): ''' ''' rslt = 0 cnt = 0 while cnt < len(self.symbol): letter = self.symbol[cnt] if letter >= 'A' or letter <= 'Z': l = ord(letter) rslt |= (UInt64(l) << (8 * (cnt + 1))) else: raise ValueError("{} contains an invalid symbol. Must be [A-Z].".format(self.symbol)) cnt += 1 rslt |= UInt64(self.precision) return INRBuffer(UInt64(rslt)).encode() def encode(self): ''' ''' power = '1'.ljust(self.precision + len('1'), '0') amount = INRBuffer(UInt64(self.amount * UInt64(power))).encode() symbol = self._string_to_symbol() return '{amount}{symbol}'.format(amount=amount, symbol=symbol) class AbiType(BaseObject): def __init__(self, d): self._validator = AbiTypeSchema() super(AbiTypesSchema, self).__init__(d) def encode(self): new_type_name = self._encode_buffer(self.new_type_name) type = self._encode_buffer(self.type) return '{}{}'.format(new_type_name, type) class AbiStructField(BaseObject): def __init__(self, d): self._validator = AbiStructFieldSchema() super(AbiStructField, self).__init__(d) def encode(self): name = self._encode_buffer(self.name) type = self._encode_buffer(self.type) return '{}{}'.format(name, type) class AbiStruct(BaseObject): def __init__(self, d): self._validator = AbiStructSchema() super(AbiStruct, self).__init__(d) self.fields = self._create_obj_array(self.fields, AbiStructField) def encode(self): name = self._encode_buffer(self.name) base = self._encode_buffer(self.base) fields = self._encode_buffer(self.fields) return '{}{}{}'.format(name, base, fields) class AbiAction(BaseObject): def __init__(self, d): self._validator = AbiActionSchema() super(AbiAction, self).__init__(d) def encode(self): name = self._encode_buffer(Name(self.name)) type = self._encode_buffer(self.type) ricardian_contract = self._encode_buffer(self.ricardian_contract) return '{}{}{}'.format(name, type, ricardian_contract) class AbiTable(BaseObject): def __init__(self, d): self._validator = AbiTableSchema() super(AbiTable, self).__init__(d) def encode(self): name = self._encode_buffer(Name(self.name)) index_type = self._encode_buffer(self.index_type) key_names = self._encode_buffer(self.key_names) key_types = self._encode_buffer(self.key_types) type = self._encode_buffer(self.type) return '{}{}{}{}{}'.format(name, index_type, key_names, key_types, type) class AbiRicardianClauses(BaseObject): def __init__(self, d): self._validator = AbiRicardianClauseSchema() super(AbiRicardianClauses, self).__init__(d) def encode(self): id = self._encode_buffer(self.id) body = self._encode_buffer(self.body) return '{}{}'.format(id, body) class AbiErrorMessages(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiErrorMessagesSchema() super(AbiErrorMessages, self).__init__(d) class AbiExtensions(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiExtensionsSchema() super(AbiExtensions, self).__init__(d) class AbiVariants(BaseObject): # TODO implement encode def __init__(self, d): self._validator = AbiVariantsSchema() super(AbiVariants, self).__init__(d) class Abi(BaseObject): _abi_map = { # name 'name': Name(), 'string': str(), # numbers 'bool': Byte(), 'uint8': Byte(), 'uint16': UInt16(), 'uint32': UInt32(), 'uint64': UInt64(), 'int8': Byte(), # NotImplemented 'int16': Int16(), # NotImplemented 'int32': Int32(), # NotImplemented 'int64': Int64(), # NotImplemented 'float64': Float(), # NotImplemented # 'varuint32': VarUInt # NotImplemented # complex 'asset': Asset("1.0000 INR"), # 'checksum256': str, # NotImplemented # 'block_timestamp_type': UInt64, # NotImplemented # 'time_point': UInt64, # NotImplemented # 'connector': str, # NotImplemented # 'public_key': str, # NotImplemented # 'authority': str, # NotImplemented # 'block_header': str, # NotImplemented # 'bytes': str, # NotImplemented # 'permission_level': str, # NotImplemented # 'permission_level_weight': str, #NotImplemented } def __init__(self, d): ''' ''' self._validator = AbiSchema() super(Abi, self).__init__(d) self.types = self._create_obj_array(self.types, AbiType) self.structs = self._create_obj_array(self.structs, AbiStruct) self.actions = self._create_obj_array(self.actions, AbiAction) self.tables = self._create_obj_array(self.tables, AbiTable) self.ricardian_clauses = self._create_obj_array(self.ricardian_clauses, AbiRicardianClauses) self.error_messages = self._create_obj_array(self.error_messages, AbiErrorMessages) self.abi_extensions = self._create_obj_array(self.abi_extensions, AbiExtensions) self.variants = self._create_obj_array(self.variants, AbiVariants) def get_action(self, name): ''' ''' for act in self.actions: if act.name == name: return act raise INRUnknownObj('{} is not a valid action for this contract'.format(name)) def get_actions(self): actions = [] for act in self.actions: actions.append(act.name) return actions def get_struct(self, name): ''' ''' for struct in self.structs: if struct.name == name: return struct raise INRUnknownObj('{} is not a valid struct for this contract'.format(name)) def get_action_parameters(self, name): ''' ''' parameters = OrderedDict() # get the struct struct = self.get_struct(name) for field in struct.fields: f = field.type.strip('[]') if(f in self._abi_map): field_type = self._abi_map[f] # check if the field is a list if '[]' in field.type: field_type = [field_type] parameters[field.name] = field_type else: raise INRUnknownObj("{} is not a known abi type".format(field.type)) return parameters def get_raw(self): version = self._encode_buffer(self.version) # encode types types = self._encode_buffer(self.types) structs = self._encode_buffer(self.structs) actions = self._encode_buffer(self.actions) tables = self._encode_buffer(self.tables) ricardian_clauses = self._encode_buffer(self.ricardian_clauses) error_messages = self._encode_buffer(self.error_messages) abi_extensions = self._encode_buffer(self.abi_extensions) variants = self._encode_buffer(self.variants) return '{}{}{}{}{}{}{}{}{}'.format(version, types, structs, actions, tables, ricardian_clauses, error_messages, abi_extensions, variants) def encode(self): ''' ''' raw_abi = self.get_raw() # divide by two because it is hex length = self._encode_buffer(VarUInt(len(raw_abi) / 2)) return length + raw_abi def json_to_bin(self, name, data): # act = self.get_action(name) params = self.get_action_parameters(name) bin_buffer = '' for field in data: # create INRBuffer with value as a type of field if isinstance(params[field], list): field_type = type(params[field][0]) arr = [] for f in data[field]: print(f) arr.append(field_type(f)) field_buffer = INRBuffer(arr) else: field_type = type(params[field]) field_buffer = INRBuffer(field_type(data[field])) bin_buffer += field_buffer.encode() return bin_buffer class Authorization(BaseObject): def __init__(self, d): ''' ''' # create validator self._validator = PermissionLevelSchema() super(Authorization, self).__init__(d) def encode(self): ''' ''' actor = self._encode_buffer(AccountName(self.actor)) perms = self._encode_buffer(PermissionName(self.permission)) return '{}{}'.format(actor, perms) class ChainInfo(BaseObject): def __init__(self, d): ''' ''' self._validator = ChainInfoSchema() super(ChainInfo, self).__init__(d) class BlockInfo(BaseObject): def __init__(self, d): ''' ''' self._validator = BlockInfoSchema() super(BlockInfo, self).__init__(d) class Transaction(BaseObject): def __init__(self, d, chain_info, lib_info): ''' ''' # add defaults if 'expiration' not in d: d['expiration'] = str((dt.datetime.utcnow() + dt.timedelta(seconds=30)).replace(tzinfo=pytz.UTC)) if 'ref_block_num' not in d: d['ref_block_num'] = chain_info['last_irreversible_block_num'] & 0xFFFF if 'ref_block_prefix' not in d: d['ref_block_prefix'] = lib_info['ref_block_prefix'] # validate self._validator = TransactionSchema() super(Transaction, self).__init__(d) # parse actions self.actions = self._create_obj_array(self.actions, Action) def _encode_hdr(self): ''' ''' # convert exp_ts = (self.expiration - dt.datetime(1970, 1, 1, tzinfo=self.expiration.tzinfo)).total_seconds() exp = self._encode_buffer(UInt32(exp_ts)) ref_blk = self._encode_buffer(UInt16(self.ref_block_num & 0xffff)) ref_block_prefix = self._encode_buffer(UInt32(self.ref_block_prefix)) net_usage_words = self._encode_buffer(VarUInt(self.net_usage_words)) max_cpu_usage_ms = self._encode_buffer(Byte(self.max_cpu_usage_ms)) delay_sec = self._encode_buffer(VarUInt(self.delay_sec)) # create hdr buffer hdr = '{}{}{}{}{}{}'.format(exp, ref_blk, ref_block_prefix, net_usage_words, max_cpu_usage_ms, delay_sec) return hdr def encode(self): ''' ''' hdr_buf = self._encode_hdr() context_actions = self._encode_buffer(self.context_free_actions) actions = self._encode_buffer(self.actions) trans_exts = self._encode_buffer(self.transaction_extensions) return bytearray.fromhex(hdr_buf + context_actions + actions + trans_exts) def get_id(self): return sha256(self.encode()) class PackedTransaction: def __init__(self, trx, ce): self._cline = ce self._packed_trx = trx # empty header self._is_unpacked = False self._unpacked_trx = OrderedDict() def _decode_buffer(self, objType, buf): ''' ''' eBuf = INRBuffer("") return eBuf.decode(objType, buf) def _decode_header(self, buf): ''' ''' buf = self._packed_trx # get expiration buffer (exp, buf) = self._decode_buffer(UInt32(), buf) # get expiration in UTC exp_dt = dt.datetime.utcfromtimestamp(exp) self._unpacked_trx['expiration'] = exp_dt.strftime("%Y-%m-%dT%H:%M:%S") # get ref_block (ref_blk, buf) = self._decode_buffer(UInt16(), buf) self._unpacked_trx['ref_block_num'] = ref_blk # get ref_block_prefix (ref_blk_pre, buf) = self._decode_buffer(UInt32(), buf) self._unpacked_trx['ref_block_prefix'] = ref_blk_pre # get net usage (max_net_usage, buf) = self._decode_buffer(VarUInt(), buf) self._unpacked_trx['max_net_usage_words'] = max_net_usage # get cpu usage (max_cpu_usage, buf) = self._decode_buffer(Byte(), buf) self._unpacked_trx['max_cpu_usage_ms'] = max_cpu_usage # get delay sec (delay_sec, buf) = self._decode_buffer(VarUInt(), buf) self._unpacked_trx['delay_sec'] = delay_sec return buf def decode_actions(self, buf): ''' ''' # get length of action array actions = [] (length, act_buf) = self._decode_buffer(VarUInt(), buf) cnt = 0 # loop through array while cnt < length and length: # process action account/name (acct_name, act_buf) = self._decode_buffer(AccountName(), act_buf) (action_name, act_buf) = self._decode_buffer(ActionName(), act_buf) # get authorizations (auth, act_buf) = self.decode_authorizations(act_buf) # get data length (hex_data_len, act_buf) = self._decode_buffer(VarUInt(), act_buf) # get abi information contract_abi = self._cline.get_abi(acct_name) abi = Abi(contract_abi["abi"]) abi_act = abi.get_action(action_name) # temp check need to handle this better if abi_act["type"] != action_name: raise INRAbiProcessingError("Error processing the {} action".format(action_name)) abi_struct = abi.get_action_parameters(action_name) data = OrderedDict() # save data for hex_data data_diff = act_buf for a in abi_struct: (act_data, act_buf) = self._decode_buffer(abi_struct[a], act_buf) data[a] = act_data act = OrderedDict({ 'account': acct_name, 'name': action_name, "authorization": auth, "data": data, "hex_data": data_diff.rstrip(act_buf), }) actions.append(act) # increment count cnt += 1 return (actions, act_buf) def decode_authorizations(self, buf): ''' ''' auths = [] (length, auth_buf) = self._decode_buffer(VarUInt(), buf) cnt = 0 while cnt < length and length: # process action account/name (acct_name, auth_buf) = self._decode_buffer(AccountName(), auth_buf) (perm, auth_buf) = self._decode_buffer(ActionName(), auth_buf) auth = OrderedDict({ 'actor': acct_name, 'permission': perm, }) auths.append(auth) cnt += 1 return (auths, auth_buf) def decode_trx_extensions(self, buf): ''' ''' trx_ext = [] (length, ctx_buf) = self._decode_buffer(VarUInt(), buf) if length > 0: raise NotImplementedError("Currently inerypy does not support transaction extensions") # get length of action array return (trx_ext, ctx_buf) def get_id(self): ''' ''' return sha256(bytearray.fromhex(self._packed_trx)) def get_transaction(self): ''' ''' # only unpack once if not self._is_unpacked: # decode the header and get the rest of the trx back trx_buf = self._decode_header(self._packed_trx) # process list of context free actions (context_actions, trx_buf) = self.decode_context_actions(trx_buf) self._unpacked_trx['context_free_actions'] = context_actions # process actions (actions, trx_buf) = self.decode_actions(trx_buf) self._unpacked_trx['actions'] = actions # process transaction extensions (trx_ext, trx_buf) = self.decode_trx_extensions(trx_buf) self._unpacked_trx['transaction_extensions'] = trx_ext # set boolean self._is_unpacked = True return self._unpacked_trx class INRBuffer: def __init__(self, v): self._value = v self._count = 0 def _decode_number(self, val, format='L'): byte_val = binascii.unhexlify(val) return convert_big_endian(byte_val, format) def _decode_float(self, val, format='f'): byte_val = binascii.unhexlify(val) return struct.unpack(">{}".format(format), byte_val) def _decode_name(self, val, format='Q'): ''' ''' num = self._decode_number(val, format) return name_to_string(num) def _decode_str(self, val): ''' ''' # get length vu = VarUInt() (length, val) = vu.decode(val) string = '' leftover = val # if there is data parse it if length > 0: (str_data, leftover) = self._splice_buf(val, length * 2) string = binascii.unhexlify(str_data).decode() return (string, leftover) def _splice_buf(self, buf, length): return buf[:length], buf[length:] def _write_number(self, val, format='q'): ''' ''' le = convert_little_endian(val, format) return binascii.hexlify(le).decode() def _write_name(self, w_str): ''' ''' val = string_to_name(w_str) le = convert_little_endian(val, 'Q') return binascii.hexlify(le).decode() def _write_str(self, w_str): b = bytearray() length = VarUInt(len(w_str)).encode() b.extend(map(ord, w_str)) return binascii.hexlify(length + b).decode() def _write_varuint(self, vuint): buf = vuint.encode() return binascii.hexlify(buf).decode() def decode(self, objType, buf=None): leftover = "" if not buf: buf = self._value if isinstance(objType, UInt32): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'I') elif isinstance(objType, UInt16): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'H') elif isinstance(objType, VarUInt): (val, leftover) = objType.decode(buf) elif(isinstance(objType, Byte) or isinstance(objType, bool)): (hex_str, leftover) = self._splice_buf(buf, 2) val = hex_to_int(hex_str) elif isinstance(objType, Float): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_float(val, 'f') elif(isinstance(objType, int) or isinstance(objType, long)): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_number(val, 'q') elif (isinstance(objType, Name) or isinstance(objType, AccountName) or isinstance(objType, PermissionName) or isinstance(objType, ActionName) or isinstance(objType, TableName) or isinstance(objType, ScopeName)): (val, leftover) = self._splice_buf(buf, objType.hex_str_len) val = self._decode_name(val) elif isinstance(objType, str): (val, leftover) = self._decode_str(buf) elif(isinstance(objType, list)): # get count(VarUint) val = [] (length, leftover) = VarUInt("").decode(buf) while len(val) < length: (out, leftover) = self.decode(objType[0], leftover) val.append(out) else: raise INRBufferInvalidType("Cannot decode type: {}".format(type(objType))) return (val, leftover) def encode(self, val=None): if not val: val = self._value if (isinstance(val, Name) or isinstance(val, AccountName) or isinstance(val, PermissionName) or isinstance(val, ActionName) or isinstance(val, TableName) or isinstance(val, ScopeName)): val = self._write_name(val) return val elif(isinstance(val, str)): return self._write_str(val) elif(isinstance(val, Byte) or isinstance(val, bool)): # return self._write_number(val, '?') return int_to_hex(val) elif(isinstance(val, UInt16)): return self._write_number(val, 'H') elif(isinstance(val, UInt32)): return self._write_number(val, 'I') elif(isinstance(val, UInt64)): return self._write_number(val, 'q') elif(isinstance(val, Float)): return self._write_number(val, 'f') elif(isinstance(val, VarUInt)): # temp encoding return self._write_varuint(val) elif(isinstance(val, int) or isinstance(val, long)): return self._write_number(val, 'l') elif(isinstance(val, Action) or isinstance(val, AbiStruct) or isinstance(val, AbiStructField) or isinstance(val, AbiType) or isinstance(val, AbiAction) or isinstance(val, AbiTable) or isinstance(val, AbiRicardianClauses) or isinstance(val, AbiErrorMessages) or isinstance(val, AbiExtensions) or isinstance(val, AbiVariants) or isinstance(val, Asset) or isinstance(val, Authorization)): return val.encode() elif(isinstance(val, list)): buf = self._write_varuint(VarUInt(len(val))) for item in val: e_item = self.encode(item) buf = '{}{}'.format(buf, e_item) return buf else: raise INRBufferInvalidType('Cannot encode type: {}'.format(type(val)))
PypiClean
/HoleCardHandicapper-1.2.1.tar.gz/HoleCardHandicapper-1.2.1/holecardhandicapper/model/utils.py
import os import csv from holecardhandicapper.model.const import PREFLOP, FLOP, TURN, RIVER class Utils: @classmethod def build_preflop_winrate_table(self): fpath = self.get_preflop_winrate_data_path() table = [[0 for j in range(53)] for i in range(53)] with open(fpath, "rb") as f: reader = csv.reader(f) data = [] for id1, id2, win_rate in reader: id1, id2 = map(int, [id1, id2]) win_rate = float(win_rate) table[id1][id2] = win_rate return table @classmethod def get_preflop_winrate_data_path(self): root = self.__get_root_path() return os.path.join(root, "holecardhandicapper", "model", "data", "preflop_winrate.csv") @classmethod def get_model_weights_path(self, street): if PREFLOP == street: return self.get_preflop_model_weights_path() if FLOP == street: return self.get_flop_model_weights_path() if TURN == street: return self.get_turn_model_weights_path() if RIVER == street: return self.get_river_model_weights_path() raise ValueError("Unknown street [ %s ] received." % street) @classmethod def get_preflop_model_weights_path(self): root = self.__get_root_path() return os.path.join(root, "holecardhandicapper", "model", "weights", "preflop_neuralnet_model_weights.h5") @classmethod def get_flop_model_weights_path(self): root = self.__get_root_path() return os.path.join(root, "holecardhandicapper", "model", "weights", "flop_cnn_model_weights.h5") @classmethod def get_turn_model_weights_path(self): root = self.__get_root_path() return os.path.join(root, "holecardhandicapper", "model", "weights", "turn_cnn_model_weights.h5") @classmethod def get_river_model_weights_path(self): root = self.__get_root_path() return os.path.join(root, "holecardhandicapper", "model", "weights", "river_cnn_model_weights.h5") @classmethod def __get_root_path(self): return os.path.join(os.path.dirname(__file__), "..", "..")
PypiClean
/HiveNAS-0.1.5-py3-none-any.whl/config/params.py
import sys sys.path.append('..') import os import yaml from utils import FileHandler from functools import partial from tensorflow.keras.optimizers import RMSprop, Adam from tensorflow.keras.layers import Conv2D, Flatten, MaxPooling2D from tensorflow.keras.layers import SeparableConv2D, Dense, Dropout from tensorflow.keras.layers import AveragePooling2D, BatchNormalization, ReLU class Params: '''Wrapper for all global operational parameters and the configuration loader ''' @staticmethod def config_form(): '''Facilitates the configuration UI form (for the `Google Colab version \ <https://colab.research.google.com/github/ThunderStruct/HiveNAS/blob/main/colab/HiveNas.ipynb>`_) \ and exports all parameters as a dictionary Returns: dict: main global parameters dictionary (locals) ''' ''' Configuration Version (used as filenames) ''' CONFIG_VERSION = 'config_version' #@param {type:"string"} #@markdown ## ABC Optimizer Parameters #@markdown --- ''' Optimization problem (NAS or Numerical Benchmarks to test ABC) ''' OPTIMIZATION_OBJECTIVE = 'NAS' #@param ['NAS', 'Sphere_max', 'Sphere_min', 'Rosenbrock'] ''' Max trials per Scout (i.e initial Food Source) ''' ABANDONMENT_LIMIT = 3 #@param {type:"slider", min:1, max:50, step:1} ''' Number of bees in the colony (Employees + Onlookers) ''' COLONY_SIZE = 7 #@param {type:"slider", min:1, max:50, step:1} ''' Distribution of Employees to Onlookers, resulting number of EmployeeBees = # of ScoutBees ''' EMPLOYEE_ONLOOKER_RATIO = 0.43 #@param {type:"slider", min:0.1, max:1.0, step:0.05} ''' Number of ABC optimization iterations ''' ITERATIONS_COUNT = 12 #@param {type:"slider", min:1, max:100, step:1} #@markdown \ #@markdown ## File-Handling Parameters #@markdown --- ''' Save results every N evaluations (not iterations; iterations * colony_size) ''' RESULTS_SAVE_FREQUENCY = 1 #@param {type:"slider", min:1, max:100, step:1} ''' Result files base path (path will be created if it does not exist) A local folder will be created after the CONFIG_VERSION ''' RESULTS_BASE_PATH = '../res/archived results/' #@param {type:"string"} ''' Training history files sub-path ''' HISTORY_FILES_SUBPATH = 'training_history/' #@param {type:"string"} ''' Enable weights saving for resumed training ''' ENABLE_WEIGHT_SAVING = False #@param {type:"boolean"} ''' Weight files sub-path (ensure that the path exists) ''' WEIGHT_FILES_SUBPATH = 'weights/' #@param {type:"string"} ''' Specifies whether or not to resume from existing results file (if exists)''' RESUME_FROM_RESULTS_FILE = False #@param {type:'boolean'} #@markdown \ #@markdown ## NAS Search Space Parameters #@markdown --- ''' -- NAS Search Space configuration -- ''' #@markdown *( layers & hyperparameters must be defined as partial functions in code )* ''' Number of layers for sampled networks (excludes input/output stems) ''' DEPTH = 5 #@param {type:"slider", min:1, max:10, step:1} ''' Search space operations ''' OPERATIONS = { 'sep5x5_128': partial(SeparableConv2D, filters=128, kernel_size=(5,5), activation='relu', padding='same'), 'sep3x3_128': partial(SeparableConv2D, filters=128, kernel_size=(3,3), activation='relu', padding='same'), 'sep5x5_64': partial(SeparableConv2D, filters=64, kernel_size=(5,5), activation='relu', padding='same'), 'sep3x3_64': partial(SeparableConv2D, filters=64, kernel_size=(3,3), activation='relu', padding='same'), 'sep5x5_32': partial(SeparableConv2D, filters=32, kernel_size=(5,5), activation='relu', padding='same'), 'sep3x3_32': partial(SeparableConv2D, filters=32, kernel_size=(3,3), activation='relu', padding='same'), 'max_pool3x3': partial(MaxPooling2D, pool_size=(3,3), strides=(1,1), padding='same'), 'avg_pool3x3': partial(AveragePooling2D, pool_size=(3,3), strides=(1,1), padding='same'), 'batch_norm': partial(BatchNormalization), 'dropout': partial(Dropout, rate=0.2) } ''' ''' # Skip-Connections'/Residual Blocks' occurence rate (0.0 = disabled) RESIDUAL_BLOCKS_RATE = 0.15 #@param {type:"slider", min:0.0, max:1.0, step:0.05} #@markdown \ #@markdown ## NAS Evaluation Strategy Parameters #@markdown --- ''' -- NAS Evaluation Strategy configuration -- ''' ''' Dataset (classes/inputs are inferred internally) ''' DATASET = 'CIFAR10' #@param ["CIFAR10", "MNIST", "FASHION_MNIST"] ''' Static output stem, added to every candidate ''' OUTPUT_STEM = [ partial(Flatten), partial(Dropout, rate=0.15), partial(Dense, units=1024, activation='relu'), partial(Dropout, rate=0.15), partial(Dense, units=512, activation='relu') ] ''' Static input stem, added to every candidate ''' INPUT_STEM = [ partial(Conv2D, filters=32, kernel_size=(3,3)), partial(BatchNormalization), partial(ReLU) ] ''' Epochs count per candidate network ''' EPOCHS = 5 #@param {type:"slider", min:1, max:25, step:1} ''' Momentum Augmentation epochs (0 = disabled ; overrides ENABLE_WEIGHT_SAVING) ''' MOMENTUM_EPOCHS = 0 #@param {type:"slider", min:0, max:25} ''' Epochs count for the best performing candidate upon full training ''' FULL_TRAIN_EPOCHS = 50 #@param {type:"slider", min:1, max:150, step:1} ''' Threshold factor (beta) for early-stopping (refer to the TerminateOnThreshold class for details) 1.0 = all networks will be terminated (minimum accuracy = 100%) 0.0 = disable early-stopping, all networks will pass 0.25 = for 10 classes, val_acc > 0.325 at epoch 1 will not be terminated (tolerance decreased for every subsequent epoch) ''' TERMINATION_THRESHOLD_FACTOR = 0.0 #@param {type:"slider", min:0.0, max:1.0, step:0.05} ''' Diminishing factor (zeta) for termination threshold over epochs ''' TERMINATION_DIMINISHING_FACTOR = 0.25 #@param {type:"slider", min:0.1, max:1.0, step:0.05} ''' Learning rate (overrides default optimizer lr) ''' LR = 0.001 #@param {type:"slider", min:0.001, max:0.1, step:0.001} ''' Batch size for every candidate evaluation ''' BATCH_SIZE = 128 #@param {type:"slider", min:8, max:256, step:2} ''' Optimizer used for both NAS and full-training methods ''' OPTIMIZER = 'Adam' #@param ["Adam", "RMSprop"] #@markdown \ #@markdown ## Data Augmentation Parameters #@markdown --- ''' Enable affine transformations augmentation (horizontal/vertical shifts, rotation, etc...) ''' AFFINE_TRANSFORMATIONS_ENABLED = True #@param {type:"boolean"} ''' Probability of random cutout augmentation occurence (0.0 = disabled) ''' CUTOUT_PROB = 0.8 #@param {type:"slider", min:0.0, max:1.0, step:0.05} ''' Probability of random saturation augmentation occurence (0.0 = disabled) ''' SATURATION_AUG_PROB = 0.75 #@param {type:"slider", min:0.0, max:1.0, step:0.05} ''' Probability of random contrast augmentation occurence (0.0 = disabled) ''' CONTRAST_AUG_PROB = 0.75 #@param {type:"slider", min:0.0, max:1.0, step:0.05} return locals() ''' Main configuration dict ''' __CONFIG = config_form.__func__() @staticmethod def init_from_yaml(path): '''Initializes the global parameters from a given yaml config file Args: path (str): path to yaml configuration file ''' def param_op_constructor(loader: yaml.SafeLoader, node: yaml.nodes.MappingNode): '''Constructs NAS Search Space operations (using the custom \ yaml :code:`!Operation` tag) Args: loader (:class:`yaml.SafeLoader`): yaml default safe loader node (:class:`yaml.nodes.MappingNode`): yaml mapping node Returns: :class:`functools.partial`: partial function containing the neural operation ''' # constructs an operation partial function from yaml !Operation tags op_dict = loader.construct_mapping(node) op = op_dict['op'] del op_dict['op'] return partial(globals()[op], **op_dict) def param_tuple_constructor(loader: yaml.SafeLoader, node: yaml.nodes.MappingNode): '''Constructs a tuple from the standard \ :code:`tag:yaml.org,2002:python/tuple` (:code:`!!python/tuple`) yaml tag Args: loader (:class:`yaml.SafeLoader`): yaml default safe loader node (:class:`yaml.nodes.MappingNode`): yaml mapping node Returns: tuple: constructed tuple, \ typically used to define kernel sizes/shapes in yaml ''' # because for some reason we need an explicit tuple constructor return tuple(loader.construct_sequence(node)) # register constructors loader = yaml.SafeLoader loader.add_constructor(u'tag:yaml.org,2002:python/tuple', param_tuple_constructor) loader.add_constructor('!Operation', param_op_constructor) config = FileHandler.load_yaml(path, loader) if not config: print(f'\nConfig file ({path}) is either invalid or does not exist.\n\n') return for key,val in config.items(): if key not in Params.__CONFIG: # ensure config file keys are valid and match the hard-coded template print(f'\nConfig file ({path}) is invalid. Skipping item ({key})... \n\n') continue Params.__CONFIG[key] = val print(f'\nSuccessfully loaded the operational parameters from {path}.\n\n') @staticmethod def export_yaml(path, filename, from_formdata=False): '''Saves the current configurations to the given path as yaml Args: path (str): output path to save the yaml config file to filename (str): output file name from_formdata (bool, optional): determines whether the export instruction \ originated from the Google Colab UI form or called in code. *When it originates \ from the form, data reload is required to ensure consistency (could be \ altered within the form)* ''' def param_op_representer(dumper, data): '''Serializes a partial function into the custom :code:`!Operation` \ yaml tag Args: dumper (:class:`yaml.Dumper`): default pyyaml dumper data (partial): partial function data to be serialized Returns: :class:`yaml.nodes.MappingNode`: yaml mapping node representing \ the operation ''' # serialize partial functions into yaml !Operation serialized_data = {'op': data.func.__name__} serialized_data.update(data.keywords) return dumper.represent_mapping('!Operation', serialized_data, flow_style=True) def param_tuple_representer(dumper, data): '''Serializes a tuple into the :code:`tag:yaml.org,2002:python/tuple` \ (:code:`!!python/tuple`) yaml tag Args: dumper (:class:`yaml.Dumper`): default pyyaml dumper data (tuple): tuple data to be serialized Returns: :class:`yaml.nodes.MappingNode`: yaml mapping node representing \ the tuple ''' # serialize tuples into yaml !!python/tuple return dumper.represent_sequence(u'tag:yaml.org,2002:python/tuple', data, flow_style=True) # register representers yaml.add_representer(tuple, param_tuple_representer) yaml.add_representer(partial, param_op_representer) yaml.Dumper.ignore_aliases = lambda *args : True # data source (changing the Colab form does not reflect on the main dict) data = Params.config_form() if from_formdata else Params.__CONFIG if FileHandler.export_yaml(data, path, filename): print(f'\nConfiguration file saved successfully to ({os.path.join(path, filename)})!\n\n') else: print('\nFailed to save config file!\n\n') @staticmethod def search_space_config(): '''Returns the search space config dict Returns: dict: dictionary containing the :class:`~core.nas.search_space.NASSearchSpace`-related \ parameters ''' res = { 'depth': Params['DEPTH'], 'operations': Params['OPERATIONS'], 'residual_blocks_rate': Params['RESIDUAL_BLOCKS_RATE'] } return res @staticmethod def evaluation_strategy_config(): '''Returns the evaluation strategy config dict Returns: dict: dictionary containing the :class:`~core.nas.evaluation_strategy.NASEval`-related \ parameters ''' res = { 'dataset': Params['DATASET'], 'operations': Params['OPERATIONS'], 'output_stem': Params['OUTPUT_STEM'], 'input_stem': Params['INPUT_STEM'], 'epochs': Params['EPOCHS'], 'full_train_epochs': Params['FULL_TRAIN_EPOCHS'], 'lr': Params['LR'], 'batch_size': Params['BATCH_SIZE'], 'optimizer': globals()[Params['OPTIMIZER']], 'termination_threshold_factor': Params['TERMINATION_THRESHOLD_FACTOR'], 'termination_diminishing_factor': Params['TERMINATION_DIMINISHING_FACTOR'], 'momentum_epochs': Params['MOMENTUM_EPOCHS'] } return res @staticmethod def get_results_path(): '''Gets the results path from :code:`RESULTS_BASE_PATH` and :code:`CONFIG_VERSION` Returns: str: the joined path to the results directory or :code:`None` if either \ :code:`RESULTS_BASE_PATH` or :code:`CONFIG_VERSION` is invalid ''' path = os.path.join(Params.__CONFIG['RESULTS_BASE_PATH'], f'{Params.__CONFIG["CONFIG_VERSION"]}/') if FileHandler.validate_path(path): return path return None @staticmethod def get_all_config(): '''Returns all operational parameters Returns: dict: returns the dict containing all configurations *(for \ argparsing purposes)* ''' return Params.__CONFIG @staticmethod def set_parameter(key, val): '''Overrides a default parameter (used by argparser) Args: key (str): dictionary key to select parameter val (any): new value to override default parameter ''' if key not in Params.__CONFIG or not isinstance(val, type(Params.__CONFIG[key])): # invalid key or value type return False Params.__CONFIG[key] = val return True def __class_getitem__(cls, key): '''Subscript operator definition *Static class subscripting :code:`__class_getitem__` requires Python 3.7+* Used as :code:`Params['KEY']` Args: key (str): dictionary key to select parameter Returns: Any: subscripted parameter from the configuration dictionary ''' return Params.__CONFIG[key]
PypiClean
/observations-0.1.4.tar.gz/observations-0.1.4/observations/r/halley_life_table.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def halley_life_table(path): """Halley's Life Table In 1693 the famous English astronomer Edmond Halley studied the birth and death records of the city of Breslau, which had been transmitted to the Royal Society by Caspar Neumann. He produced a life table showing the number of people surviving to any age from a cohort born the same year. He also used his table to compute the price of life annuities. A data frame with 84 observations on the following 4 variables. `age` a numeric vector `deaths` number of deaths, *D\_k*, among people of age k, a numeric vector `number` size of the population, *P\_k* surviving until this age, a numeric vector `ratio` the ratio *P\_{k+1}/P\_k*, the conditional probability of surviving until age k + 1 given that one had already reached age k, a numeric vector N. Bacaer (2011), "Halley's life table (1693)", Ch 2, pp 5-10. In *A Short History of Mathematical Population Dynamics*, Springer-Verlag London, DOI 10.1007/978-0-85729-115-8\_2. Data taken from Table 1. Args: path: str. Path to directory which either stores file or otherwise file will be downloaded and extracted there. Filename is `halley_life_table.csv`. Returns: Tuple of np.ndarray `x_train` with 84 rows and 4 columns and dictionary `metadata` of column headers (feature names). """ import pandas as pd path = os.path.expanduser(path) filename = 'halley_life_table.csv' if not os.path.exists(os.path.join(path, filename)): url = 'http://dustintran.com/data/r/HistData/HalleyLifeTable.csv' maybe_download_and_extract(path, url, save_file_name='halley_life_table.csv', resume=False) data = pd.read_csv(os.path.join(path, filename), index_col=0, parse_dates=True) x_train = data.values metadata = {'columns': data.columns} return x_train, metadata
PypiClean
/DJModels-0.0.6-py3-none-any.whl/djmodels/utils/lorem_ipsum.py
import random COMMON_P = ( 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod ' 'tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim ' 'veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea ' 'commodo consequat. Duis aute irure dolor in reprehenderit in voluptate ' 'velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' 'occaecat cupidatat non proident, sunt in culpa qui officia deserunt ' 'mollit anim id est laborum.' ) WORDS = ( 'exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 'maxime', 'corrupti', ) COMMON_WORDS = ( 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua', ) def sentence(): """ Return a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))] s = ', '.join(sections) # Convert to sentence case and add end punctuation. return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.')) def paragraph(): """ Return a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return ' '.join(sentence() for i in range(random.randint(1, 4))) def paragraphs(count, common=True): """ Return a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Return a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ word_list = list(COMMON_WORDS) if common else [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return ' '.join(word_list)
PypiClean
/Cuckoo-2.0.7a1.tar.gz/Cuckoo-2.0.7a1/cuckoo/reporting/mongodb.py
import gridfs import os from cuckoo.common.abstracts import Report from cuckoo.common.exceptions import CuckooReportError from cuckoo.common.mongo import mongo from cuckoo.common.objects import File class MongoDB(Report): """Stores report in MongoDB.""" order = 2 # Mongo schema version, used for data migration. SCHEMA_VERSION = "1" db = None fs = None @classmethod def init_once(cls): if not mongo.init(): return mongo.connect() cls.db = mongo.db cls.fs = mongo.grid # Set MongoDB schema version. if "cuckoo_schema" in mongo.collection_names: version = mongo.db.cuckoo_schema.find_one()["version"] if version != cls.SCHEMA_VERSION: raise CuckooReportError( "Unknown MongoDB version schema version found. Cuckoo " "doesn't really know how to proceed now.." ) else: mongo.db.cuckoo_schema.save({"version": cls.SCHEMA_VERSION}) # Set an unique index on stored files to avoid duplicates. As per the # pymongo documentation this is basically a no-op if the index already # exists. So we don't have to do that check ourselves. mongo.db.fs.files.ensure_index( "sha256", unique=True, sparse=True, name="sha256_unique" ) def store_file(self, file_obj, filename=""): """Store a file in GridFS. @param file_obj: object to the file to store @param filename: name of the file to store @return: object id of the stored file """ if not filename: filename = file_obj.get_name() existing = self.db.fs.files.find_one({"sha256": file_obj.get_sha256()}) if existing: return existing["_id"] new = self.fs.new_file(filename=filename, contentType=file_obj.get_content_type(), sha256=file_obj.get_sha256()) for chunk in file_obj.get_chunks(): new.write(chunk) try: new.close() return new._id except gridfs.errors.FileExists: to_find = {"sha256": file_obj.get_sha256()} return self.db.fs.files.find_one(to_find)["_id"] def run(self, results): """Writes report. @param results: analysis results dictionary. @raise CuckooReportError: if fails to connect or write to MongoDB. """ # Create a copy of the dictionary. This is done in order to not modify # the original dictionary and possibly compromise the following # reporting modules. report = dict(results) if "network" not in report: report["network"] = {} # This will likely hardcode the cuckoo.log to this point, but that # should be fine. if report.get("debug"): report["debug"]["cuckoo"] = list(report["debug"]["cuckoo"]) # Store path of the analysis path. report["info"]["analysis_path"] = self.analysis_path # Store the sample in GridFS. if results.get("info", {}).get("category") == "file" and "target" in results: sample = File(self.file_path) if sample.valid(): fname = results["target"]["file"]["name"] sample_id = self.store_file(sample, filename=fname) report["target"] = {"file_id": sample_id} report["target"].update(results["target"]) # Store the PCAP file in GridFS and reference it back in the report. pcap_path = os.path.join(self.analysis_path, "dump.pcap") pcap = File(pcap_path) if pcap.valid(): pcap_id = self.store_file(pcap) report["network"]["pcap_id"] = pcap_id sorted_pcap_path = os.path.join(self.analysis_path, "dump_sorted.pcap") spcap = File(sorted_pcap_path) if spcap.valid(): spcap_id = self.store_file(spcap) report["network"]["sorted_pcap_id"] = spcap_id mitmproxy_path = os.path.join(self.analysis_path, "dump.mitm") mitmpr = File(mitmproxy_path) if mitmpr.valid(): mitmpr_id = self.store_file(mitmpr) report["network"]["mitmproxy_id"] = mitmpr_id # Store the process memory dump file and extracted files in GridFS and # reference it back in the report. if "procmemory" in report and self.options.get("store_memdump", False): for idx, procmem in enumerate(report["procmemory"]): procmem_path = os.path.join( self.analysis_path, "memory", "%s.dmp" % procmem["pid"] ) procmem_file = File(procmem_path) if procmem_file.valid(): procmem_id = self.store_file(procmem_file) procmem["procmem_id"] = procmem_id for extracted in procmem.get("extracted", []): f = File(extracted["path"]) if f.valid(): extracted["extracted_id"] = self.store_file(f) # Walk through the dropped files, store them in GridFS and update the # report with the ObjectIds. new_dropped = [] if "dropped" in report: for dropped in report["dropped"]: new_drop = dict(dropped) drop = File(dropped["path"]) if drop.valid(): dropped_id = self.store_file(drop, filename=dropped["name"]) new_drop["object_id"] = dropped_id new_dropped.append(new_drop) report["dropped"] = new_dropped new_extracted = [] if "extracted" in report: for extracted in report["extracted"]: new_extr = dict(extracted) extr = File(extracted["raw"]) if extr.valid(): extr_id = self.store_file(extr) new_extr["object_id"] = extr_id new_extracted.append(new_extr) report["extracted"] = new_extracted # Add screenshots. report["shots"] = [] if os.path.exists(self.shots_path): # Walk through the files and select the JPGs. for shot_file in sorted(os.listdir(self.shots_path)): if not shot_file.endswith(".jpg") or "_" in shot_file: continue shot_path = os.path.join(self.shots_path, shot_file) shot_path_dir = os.path.dirname(shot_path) shot_file_name, shot_file_ext = os.path.splitext(shot_file) shot_path_resized = os.path.join(shot_path_dir, "%s_small%s" % (shot_file_name, shot_file_ext)) shot_blob = {} # If the screenshot path is a valid file, store it and # reference it back in the report. if os.path.isfile(shot_path): shot = File(shot_path) if shot.valid(): shot_id = self.store_file(shot) shot_blob["original"] = shot_id # Try to get the alternative (small) size for this image, # store it and reference it back in the report. if os.path.isfile(shot_path_resized): shot_small = File(shot_path_resized) if shot_small.valid(): shot_id = self.store_file(shot_small) shot_blob["small"] = shot_id if shot_blob: report["shots"].append(shot_blob) paginate = self.options.get("paginate", 100) # Store chunks of API calls in a different collection and reference # those chunks back in the report. In this way we should defeat the # issue with the oversized reports exceeding MongoDB's boundaries. # Also allows paging of the reports. if "behavior" in report and "processes" in report["behavior"]: new_processes = [] for process in report["behavior"]["processes"]: new_process = dict(process) chunk = [] chunks_ids = [] # Loop on each process call. for call in process["calls"]: # If the chunk size is paginate or if the loop is # completed then store the chunk in MongoDB. if len(chunk) == paginate: to_insert = {"pid": process["pid"], "calls": chunk} chunk_id = self.db.calls.insert(to_insert) chunks_ids.append(chunk_id) # Reset the chunk. chunk = [] # Append call to the chunk. chunk.append(call) # Store leftovers. if chunk: to_insert = {"pid": process["pid"], "calls": chunk} chunk_id = self.db.calls.insert(to_insert) chunks_ids.append(chunk_id) # Add list of chunks. new_process["calls"] = chunks_ids new_processes.append(new_process) # Store the results in the report. report["behavior"] = dict(report["behavior"]) report["behavior"]["processes"] = new_processes if report.get("procmon"): procmon, chunk = [], [] for entry in report["procmon"]: if len(chunk) == paginate: procmon.append(self.db.procmon.insert(chunk)) chunk = [] chunk.append(entry) if chunk: procmon.append(self.db.procmon.insert(chunk)) report["procmon"] = procmon # Store the report and retrieve its object id. self.db.analysis.save(report)
PypiClean
/Audit-Alembic-0.1.0.tar.gz/Audit-Alembic-0.1.0/README.rst
======== Overview ======== .. start-badges .. list-table:: :stub-columns: 1 * - docs - |docs| * - tests - | |travis| |appveyor| |requires| | |codecov| * - package - | |version| |wheel| |supported-versions| |supported-implementations| | |commits-since| .. |docs| image:: https://readthedocs.org/projects/Audit-Alembic/badge/?style=flat :target: https://readthedocs.org/projects/Audit-Alembic :alt: Documentation Status .. |travis| image:: https://travis-ci.org/jpassaro/Audit-Alembic.svg?branch=master :alt: Travis-CI Build Status :target: https://travis-ci.org/jpassaro/Audit-Alembic .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/jpassaro/Audit-Alembic?branch=master&svg=true :alt: AppVeyor Build Status :target: https://ci.appveyor.com/project/jpassaro/Audit-Alembic .. |requires| image:: https://requires.io/github/jpassaro/Audit-Alembic/requirements.svg?branch=master :alt: Requirements Status :target: https://requires.io/github/jpassaro/Audit-Alembic/requirements/?branch=master .. |codecov| image:: https://codecov.io/github/jpassaro/Audit-Alembic/coverage.svg?branch=master :alt: Coverage Status :target: https://codecov.io/github/jpassaro/Audit-Alembic .. |version| image:: https://img.shields.io/pypi/v/Audit-Alembic.svg :alt: PyPI Package latest release :target: https://pypi.python.org/pypi/Audit-Alembic .. |commits-since| image:: https://img.shields.io/github/commits-since/jpassaro/Audit-Alembic/v0.1.0.svg :alt: Commits since latest release :target: https://github.com/jpassaro/Audit-Alembic/compare/v0.1.0...master .. |wheel| image:: https://img.shields.io/pypi/wheel/Audit-Alembic.svg :alt: PyPI Wheel :target: https://pypi.python.org/pypi/Audit-Alembic .. |supported-versions| image:: https://img.shields.io/pypi/pyversions/Audit-Alembic.svg :alt: Supported versions :target: https://pypi.python.org/pypi/Audit-Alembic .. |supported-implementations| image:: https://img.shields.io/pypi/implementation/Audit-Alembic.svg :alt: Supported implementations :target: https://pypi.python.org/pypi/Audit-Alembic .. end-badges An Alembic plugin to keep records of upgrades and downgrades. * Free software: MIT license Installation ============ :: pip install Audit-Alembic Getting started =============== Quickstart ---------- Add the following lines to your Alembic ``env.py``:: from audit_alembic import Auditor from myapp import version Auditor.create(version).setup() Slightly more involved:: # myapp.py alembic_auditor = Auditor.create(version, ...) # env.py from myapp import alembic_auditor def run_migrations_offline(): ... context.configure( ... on_version_apply=alembic_auditor.listen ) ... def run_migrations_offline(): ... context.configure( ... on_version_apply=alembic_auditor.listen ) ... More involved ------------- These functions create an alembic history table and merely ask you to specify your application version (though they allow much else to be customized as well). If you already have a table you wish to add records to whenever an alembic operation takes place, and you have a callable that creates a row for that table, you can instantiate ``Auditor`` directly:: alembic_auditor = Auditor(HistoryTable, HistoryTable.alembic_version_applied) In this case ``alembic_version_applied`` specifies how to build the row based on Alembic's ``on_version_apply`` hook. Customizing not just what data to populate a row with but whehter the row should appear at all is not currently supported. If you wish to do so, directly using Alembic's ``on_version_apply`` hook may be a better fit for you. Documentation ============= https://Audit-Alembic.readthedocs.io/ (not available yet) Development =========== Status ------ The most basic tests, for using Audit-Alembic "correctly", pass for Postgres, MYSQL, and SQLite as a file. Travis does not appear to support MSSQL or Oracle so test status for those DB backends is not known. The next tests that need to be written should get us to 100% code coverage as well as covering various error cases. Please feel free to expand from there. See the issues for a list of known issues to work on. Testing ------- To run basic tests:: $ virtualenv venv && source venv/bin/activate (venv) $ python setup.py install (venv) $ pip install pytest psycopg2 (venv) $ pytest To run all tests (i.e. py2 + py3, across all database drivers), run:: $ tox Also see our `Travis setup <https://travis-ci.org/jpassaro/Audit-Alembic>`_. Note, to combine the coverage data from all the tox environments run: .. list-table:: :widths: 10 90 :stub-columns: 1 - - Windows - :: set PYTEST_ADDOPTS=--cov-append tox - - Other - :: PYTEST_ADDOPTS=--cov-append tox
PypiClean
/CTFDump-0.3.0.tar.gz/CTFDump-0.3.0/CTFDump.py
import json import re import os import sys import codecs import logging from os import path from getpass import getpass from requests import Session from bs4 import BeautifulSoup from requests.utils import CaseInsensitiveDict from urllib.parse import urlparse, urljoin from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from urllib.parse import unquote __version__ = "0.3.0" class BadUserNameOrPasswordException(Exception): pass class BadTokenException(Exception): pass class NotLoggedInException(Exception): pass class UnknownFrameworkException(Exception): pass class Challenge(object): def __init__(self, session, url, name, category="", description="", files=None, value=0): self.url = url self.name = name self.value = value self.session = session self.category = category self.description = description self.logger = logging.getLogger(__name__) self.files = self.collect_files(files, description) @staticmethod def collect_files(files, description=""): files = files or [] files.extend(re.findall(r"https?://\w+(?:\.\w+)+(?:/[\w._-]+)+", description, re.DOTALL)) return files @staticmethod def escape_filename(filename): return re.sub(r"[^\w\s\-.()]", "", filename.strip()) def download_file(self, url, file_path): try: res = self.session.get(url, stream=True) with open(file_path, 'wb') as f: for chunk in res.iter_content(chunk_size=1024): if not chunk: continue f.write(chunk) f.flush() except Exception as ex: print(ex) def dump(self): # Create challenge directory if not exist challenge_path = path.join( self.escape_filename(urlparse(self.url).hostname), self.escape_filename(self.category), self.escape_filename(self.name) ) os.makedirs(challenge_path, exist_ok=True) with codecs.open(path.join(challenge_path, "ReadMe.md"), "wb", encoding='utf-8') as f: f.write(f"Name: {self.name}\n") f.write(f"Value: {self.value}\n") f.write(f"Description: {self.description}\n") self.logger.info(f"Creating Challenge [{self.category or 'No Category'}] {self.name}") for file_url in self.files: file_path = path.join(challenge_path, self.escape_filename(path.basename(urlparse(file_url).path))) self.download_file(file_url, file_path) class CTF(object): def __init__(self, url): self.url = url self.session = Session() self.logger = logging.getLogger(__name__) def iter_challenges(self): raise NotImplementedError() def login(self, username, password): raise NotImplementedError() def logout(self): self.session.get(urljoin(self.url, "/logout")) class CTFd(CTF): def __init__(self, url): super().__init__(url) @property def version(self): # CTFd >= v2 res = self.session.get(urljoin(self.url, "/api/v1/challenges")) if res.status_code == 403: # Unknown (Not logged In) return -1 if res.status_code != 404: return 2 # CTFd >= v1.2 res = self.session.get(urljoin(self.url, "/chals")) if res.status_code == 403: # Unknown (Not logged In) return -1 if 'description' not in res.json()['game'][0]: return 1 # CTFd <= v1.1 return 0 def __get_nonce(self): res = self.session.get(urljoin(self.url, "/login")) html = BeautifulSoup(res.text, 'html.parser') return html.find("input", {'type': 'hidden', 'name': 'nonce'}).get("value") def login(self, username, password): next_url = '/challenges' res = self.session.post( url=urljoin(self.url, "/login"), params={'next': next_url}, data={ 'name': username, 'password': password, 'nonce': self.__get_nonce() } ) if res.ok and urlparse(res.url).path == next_url: return True return False def __get_file_url(self, file_name): if not file_name.startswith('/files/'): file_name = f"/files/{file_name}" return urljoin(self.url, file_name) def __iter_challenges(self): version = self.version if version < 0: raise NotLoggedInException() if version >= 2: res_json = self.session.get(urljoin(self.url, "/api/v1/challenges")).json() challenges = res_json['data'] for challenge in challenges: challenge_json = self.session.get(urljoin(self.url, f"/api/v1/challenges/{challenge['id']}")).json() yield challenge_json['data'] return res_json = self.session.get(urljoin(self.url, "/chals")).json() challenges = res_json['game'] for challenge in challenges: if version >= 1: yield self.session.get(urljoin(self.url, f"/chals/{challenge['id']}")).json() continue yield challenge def iter_challenges(self): for challenge in self.__iter_challenges(): yield Challenge( session=self.session, url=self.url, name=challenge['name'], category=challenge['category'], description=challenge['description'], files=list(map(self.__get_file_url, challenge.get('files', []))) ) class rCTF(CTF): def __init__(self, url): super().__init__(url) self.BarerToken = '' @staticmethod def __get_file_url(file_info): return file_info['url'] def login(self, team_token, **kwargs): team_token = unquote(team_token) headers = { 'Content-type': 'application/json', 'Accept': 'application/json' } res = self.session.post( url=urljoin(self.url, "/api/v1/auth/login"), headers=headers, data=json.dumps({ 'teamToken': team_token }) ) if res.ok: self.BarerToken = json.loads(res.content)['data']['authToken'] return True return False def __iter_challenges(self): headers = { 'Content-type': 'application/json', 'Accept': 'application/json', 'Authorization': 'Bearer {}'.format(self.BarerToken) } res_json = self.session.get(urljoin(self.url, "/api/v1/challs"), headers=headers).json() challenges = res_json['data'] for challenge in challenges: yield challenge def iter_challenges(self): for challenge in self.__iter_challenges(): yield Challenge( session=self.session, url=self.url, name=challenge['name'], category=challenge['category'], description=challenge['description'], value=challenge['points'], files=list(map(self.__get_file_url, challenge.get('files', []))) ) def get_credentials(username=None, password=None): username = username or os.environ.get('CTF_USERNAME', input('User/Email: ')) password = password or os.environ.get('CTF_PASSWORD', getpass('Password: ', stream=False)) return username, password CTFs = CaseInsensitiveDict(data={ "CTFd": CTFd, "rCTF": rCTF }) def main(args=None): if args is None: args = sys.argv[1:] parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-v", "--version", action="version", version="%(prog)s {ver}".format(ver=__version__)) parser.add_argument("url", help="ctf url (for example: https://demo.ctfd.io/)") parser.add_argument("-c", "--ctf-platform", choices=CTFs, help="ctf platform", default="CTFd") parser.add_argument("-n", "--no-login", action="store_true", help="login is not needed") parser.add_argument("-u", "--username", help="username") parser.add_argument("-p", "--password", help="password") parser.add_argument("-t", "--token", help="team token for rCTF") sys_args = vars(parser.parse_args(args=args)) # Configure Logger logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%y %H:%M:%S') ctf = CTFs.get(sys_args['ctf_platform'])(sys_args['url']) if sys_args['ctf_platform'] == 'rCTF': if not ctf.login(sys_args['token']): raise BadTokenException() elif not sys_args['no_login'] or not os.environ.get('CTF_NO_LOGIN'): if not ctf.login(*get_credentials(sys_args['username'], sys_args['password'])): raise BadUserNameOrPasswordException() for challenge in ctf.iter_challenges(): challenge.dump() if not sys_args['no_login'] or not os.environ.get('CTF_NO_LOGIN'): ctf.logout() if __name__ == '__main__': main()
PypiClean
/HalRing-2.0.4-py3-none-any.whl/halring/crypto/halring_crypt.py
import base64 # from crypto.Cipher import AES from crypto.Cipher import AES ''' Crypt Util Author: rzzhou ''' class CryptUtil(object): """ AES加解密 """ # 密钥(key), 偏移量(vi) def __init__(self, args=None): self.BLOCK_SIZE = 16 self.pad = lambda s: s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * chr( self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) self.unpad = lambda s: s[:-ord(s[len(s) - 1:])] if args is None: self.tool_vi = "This_is_t00l_vi=" else: self.tool_vi = args ''' encypt @:param 密码 ''' def AES_Encrypt(self, data, key=None): """ 加密 :param data: 待加密数据 :param key: 加密秘钥 :return: 加密结果 """ self._KEY = key if self._KEY is None: self._KEY = "@Default_Key2020" if len(str(self.tool_vi)) == self.BLOCK_SIZE and len(str(self._KEY)) == self.BLOCK_SIZE: data = self.pad(data) cipher = AES.new(self._KEY.encode('utf8'), AES.MODE_CBC, self.tool_vi.encode('utf8')) encryptedbytes = cipher.encrypt(data.encode('utf8')) encodestrs = base64.b64encode(encryptedbytes) # 对byte字符串按 utf-8进行解码 enctext = encodestrs.decode('utf8') else: enctext = "error" return enctext def AES_Decrypt(self, data, key=None): """ 解密 :param data: 待解密数据 :param key: 解密秘钥 :return: 解密结果 """ self._KEY = key if self._KEY is None: self._KEY = "@Default_Key2020" if len(str(self.tool_vi)) == self.BLOCK_SIZE and len(str(key)) == self.BLOCK_SIZE: data = data.encode('utf8') encodebytes = base64.decodebytes(data) cipher = AES.new(self._KEY.encode('utf8'), AES.MODE_CBC, self.tool_vi.encode('utf8')) text_decrypted = cipher.decrypt(encodebytes) text_decrypted = self.unpad(text_decrypted) text_decrypted = text_decrypted.decode('utf8') else: text_decrypted = "error" return text_decrypted
PypiClean