def sort_recursive(dictionary): """ Recursively sorts nested dictionaries. Should not be applied if the structures are nested too deeply and/or there is even the remote possibility that the nesting of the passed dictionary contains a cyclic structure. Args: dictionary (dict): A python dictionary Returns: A recursively sorted dictionary Example: >>> dict = { 'a': '2', 'c': 3, 'b': { 'e': 4, 'd': 1 }, 'f': 5} >>> sort_recursive(dict) OrderedDict([('a', '2'), ('b', OrderedDict([('d', 1), ('e', 4)])), ('c', 3), ('f', 5)]) """ sorted_list = OrderedDict(sorted(dictionary.items(), key = lambda x: x[0])) # TODO test for cyclic structures. for key, value in sorted_list.items(): if type(value) is dict: sorted_list[key] = sort_recursive(value) return sorted_list
class Node(object): def __init__(self, name): self.name = name self.attributes = OrderedDict() self.children = [] self.parent = None def __eq__(self, other): return (type(other) == type(self) and self.name == other.name and dict(self.attributes) == dict(other.attributes) and self.children == other.children) def __ne__(self, other): return not self == other __gt__ = __lt__ = __ge__ = __le__ = not_implemented __hash__ = None def to_string(self): attribute_string = "".join(' %s="%s"' % (key, value) for key, value in self.attributes.items()) name = self.name if not self.children: return '<%s />' % (name + attribute_string) children_string = "".join(node.to_string() for node in self.children) return '<%s>%s</%s>' % (name + attribute_string, children_string, self.name) # Hmmm... __repr__ = to_string
def sort_recursive(dictionary): """ Recursively sorts nested dictionaries. Should not be applied if the structures are nested too deeply and/or there is even the remote possibility that the nesting of the passed dictionary contains a cyclic structure. Args: dictionary (dict): A python dictionary Returns: A recursively sorted dictionary Example: >>> dict = { 'a': '2', 'c': 3, 'b': { 'e': 4, 'd': 1 }, 'f': 5} >>> sort_recursive(dict) OrderedDict([('a', '2'), ('b', OrderedDict([('d', 1), ('e', 4)])), ('c', 3), ('f', 5)]) """ sorted_list = OrderedDict(sorted(dictionary.items(), key=lambda x: x[0])) # TODO test for cyclic structures. for key, value in sorted_list.items(): if type(value) is dict: sorted_list[key] = sort_recursive(value) return sorted_list
def startElement(self, name, attrs): self.path.append((name, attrs or None)) if len(self.path) > self.item_depth: self.stack.append((self.item, self.data)) attrs = OrderedDict((self.attr_prefix+key, yaml_eval(value)) for (key, value) in attrs.items()) self.item = self.xml_attribs and attrs or None self.data = None
def merge_hists(hists_d, merge_groups, order=PhysicsProcess.desired_plot_order): """ Merges the dictionary of input histograms according to the merge rules, which are specified as a key-value dictionary, where the key is the target and value a list of (regular) expressions to merge under the key. For example, { "WJets": ["W[1-4]Jets_.*"], "tchan": ["T_t_ToLeptons", "Tbar_t_ToLeptons"], } will perform the corresponding merges. The values of the merge dict are the keys of the input histogram dict. returns - a dictionary with the merged histograms. Optionally you can specify a list with the desired order of the keys. """ for v in hists_d.values(): if not isinstance(v, Hist) and not isinstance(v, ROOT.TH1I) and not isinstance(v, ROOT.TH1F) and not isinstance(v, Hist2D) and not isinstance(v, ROOT.TH2I) and not isinstance(v, ROOT.TH2F): raise ValueError("First argument(hists_d) must be a dict of Histograms, but found %s" % v) out_d = OrderedDict() logger.debug("merge_hists: input histograms %s" % str(hists_d)) for merge_name, items in merge_groups.items(): logger.debug("Merging %s to %s" % (items, merge_name)) matching_keys = [] for item in items: t = filter(lambda x: re.match(item + "$", x), hists_d.keys()) matching_keys += t logger.debug("Matched %s to %s" % (str(t), item)) if len(matching_keys)==0: continue logger.debug("Merging matched %s" % str(matching_keys)) hist = hists_d[matching_keys[0]].Clone() for item in matching_keys[1:]: hist.Add(hists_d[item]) out_d[merge_name] = hist out_d[merge_name].SetTitle(merge_name) out_d[merge_name].SetName(merge_name) out_d_ordered = OrderedDict() for elem in order: try: out_d_ordered[elem] = out_d.pop(elem) if hasattr(PhysicsProcess, merge_name): if type(getattr(PhysicsProcess, merge_name)) is dict: #take nominal name if multiple options out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name)["nominal"].pretty_name) else: #regular out_d_ordered[elem].SetTitle(getattr(PhysicsProcess, merge_name).pretty_name) except KeyError: #We don't care if there was an element in the order which was not present in the merge output pass #Put anything that was not in the order list simply to the end for k, v in out_d.items(): out_d_ordered[k] = v return out_d_ordered
def paramToDict_t(place, parameters=None): """ Split the parameters into names and values, check if these parameters are within the testable parameters and return in a dictionary. """ testableParameters = OrderedDict() parameters = re.sub( r"&(\w{1,4});", r"%s\g<1>%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), parameters) if place == PLACE.COOKIE: splitParams = parameters.split(DEFAULT_COOKIE_DELIMITER) else: splitParams = parameters.split(DEFAULT_GET_POST_DELIMITER) for element in splitParams: element = re.sub( r"%s(.+?)%s" % (PARAMETER_AMP_MARKER, PARAMETER_SEMICOLON_MARKER), r"&\g<1>;", element) parts = element.split("=") if len(parts) >= 2: parameter = urldecode(parts[0].replace(" ", "")) if not parameter: continue testableParameters[parameter] = "=".join(parts[1:]) if testableParameters: for parameter, value in testableParameters.items(): if value and not value.isdigit(): for encoding in ("hex", "base64"): try: decoded = value.decode(encoding) if len(decoded) > MIN_ENCODED_LEN_CHECK and all( _ in string.printable for _ in decoded): warnMsg = "provided parameter '%s' " % parameter warnMsg += "seems to be '%s' encoded" % encoding logger.warn(warnMsg) break except: pass return testableParameters
class Dialog(wx.Dialog): # def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): # def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): style = wx.RESIZE_BORDER wx.Dialog.__init__(self, parent=parent, title=title, pos=pos, size=size, style=style) # self.Bind(wx.EVT_INIT_DIALOG, self.DefaultHandler) self.SetName('Dialog_' + title) self.CustomHandler = None self.Results = {} self.Tips = {} self.Sizers = [] self.Controls = OrderedDict() self.Sizers.append(wx.BoxSizer(wx.VERTICAL)) self.band = 0 self.Sizers[0].Add(wx.Size(1, VERTICAL_DIVIDER_PAD)) self.AddBand() # super(self, '__init__') # wx.Dialog.__init__(self, parent=parent, id=id, title=title, pos=pos, size=size, style=style) # end def def AddBand(self): if self.band > 0: self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) iFlags = wx.GROW self.Sizers[0].Add(self.Sizers[self.band], 1, iFlags) self.Sizers[0].Add(wx.Size(1, VERTICAL_RELATED_PAD)) self.Sizers.append(wx.BoxSizer(wx.HORIZONTAL)) self.band += 1 self.Sizers[self.band].Add(wx.Size(HORIZONTAL_DIVIDER_PAD, 1)) # end def def AddButtonBand(self, buttons=[], index=0, handler=None): self.CustomHandler = handler self.AddBand() for i in range(len(buttons)): sButton = buttons[i] btn = self.AddButton(label=sButton) if index != None and index != -1 and i == index: btn.SetDefault() #print 'handler', handler # # self.Bind(wx.EVT_BUTTON, self.DefaultHandler, id=btn.GetId()) # end for # end def def AddButton(self, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel == 'OK': iID = wx.ID_OK # end if elif label == 'Cancel': iID = wx.ID_CANCEL # end elif elif label == 'Close': iID = wx.ID_CANCEL # iID = wx.ID_CLOSE # iID = 2 # end elif else: iID = wx.ID_ANY if sLabel.find('&') == -1: sLabel = '&' + sLabel # end else sName = name if len(sName) == 0: sName = 'Button_' + FixName(label) btn = wx.Button(parent=self, id=iID, label=sLabel, pos=pos, size=size, style=style, name=sName) self.Sizers[self.band].Add(btn, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_BUTTON, self.DefaultHandler, id=btn.GetId()) self.Controls[sName] = btn # print sName, iID return btn # end def def AddCheckBox(self, id=wx.ID_ANY, label='', value=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel.find('&') == -1: sLabel = '&' + sLabel sName = name if len(sName) == 0: sName = 'CheckBox_' + FixName(label) chk = wx.CheckBox(parent=self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) chk.SetValue(value) self.Sizers[self.band].Add(chk, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_CHECKBOX, self.DefaultHandler, id=chk.GetId()) self.Controls[sName] = chk return chk # end def def AddListBox(self, id=wx.ID_ANY, label='', names=[], values=[], sort=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.LB_HSCROLL, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'ListBox_' + FixName(label) iStyle = style if sort: iStyle |= wx.LB_SORT lst = wx.ListBox(parent=self, id=id, pos=pos, size=size, style=iStyle, name=sName) for i in range(len(names)): lst.Append(item=names[i], clientData=i) # end for if lst.GetCount(): lst.SetSelection(0) self.Sizers[self.band].Add(lst, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_LISTBOX, self.DefaultHandler, id=lst.GetId()) self.Controls[sName] = lst return lst # end def def AddMemo(self, id=wx.ID_ANY, label='', value='', readonly=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.TE_MULTILINE | wx.TE_PROCESS_ENTER, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'Memo_' + FixName(label) iStyle = style if readonly: iStyle |= wx.TE_READONLY txt = wx.TextCtrl(parent=self, id=id, pos=pos, size=size, style=iStyle, name=sName) txt.SetValue(value) self.Sizers[self.band].Add(txt, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Controls[sName] = txt # self.Bind(wx.EVT_SET_FOCUS, self.DefaultHandler, id=txt.GetId()) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler, id=txt.GetId()) return txt # end def def AddRadioButton(self, id=wx.ID_ANY, label='', value=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel.find('&') == -1: sLabel = '&' + sLabel iStyle = style if len(self.Controls) > 0 and not self.Controls[-1].startswith('RadioButton_'): iStyle = wx.RB_GROUP sName = name if len(sName) == 0: sName = 'RadioButton_' + FixName(label) rdn = wx.RadioButton(parent=self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) rdn.SetValue(value) self.Sizers[self.band].Add(rdn, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_RADIOBUTTON, self.DefaultHandler, id=rbn.GetId()) self.Controls[sName] = rdn return rdn # end def def AddRichEdit(self, id=wx.ID_ANY, label='', value='', readonly=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.TE_MULTILINE | wx.TE_PROCESS_ENTER | wx.TE_RICH2, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'RichEdit_' + FixName(label) iStyle = style if readonly: iStyle |= wxTE_READONLY aSize = size if aSize == wx.DefaultSize: aSize = (300, 300) rtb = wx.TextCtrl(parent=self, id=id, pos=pos, size=aSize, style=iStyle, name=sName) rtb.SetMaxLength(0) rtb.SetValue(value) self.Sizers[self.band].Add(rtb, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_RADIOBUTTON, self.DefaultHandler, id=rtb.GetId()) self.Controls[sName] = rtb return rtb # end def def AddStaticText(self, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sName = name if len(sName) == 0: sName = 'StaticText_' + FixName(label) sLabel = FixLabel(label) lbl = wx.StaticText(self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) self.Sizers[self.band].Add(lbl, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) self.Controls[sName] = lbl return lbl # end def def AddTextCtrl(self, id=wx.ID_ANY, label='', value='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'TextCtrl_' + FixName(label) iStyle = style if sName == 'TextCtrl_Password': iStyle |= wx.TE_PASSWORD aSize = size if aSize == wx.DefaultSize: aSize = (300, 21) txt = wx.TextCtrl(parent=self, id=id, pos=pos, size=aSize, style=iStyle, name=sName) txt.SetMaxLength(0) txt.SetValue(value) # sValue = unicode(value) # txt.SetValue(sValue) #txt.SetSize((2 * (txt.GetSize()[0]), txt.GetSize()[1])) # print txt.GetSize() self.Sizers[self.band].Add(txt, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_TEXT, self.DefaultHandler, id=txt.GetId()) self.Bind(wx.EVT_TEXT_MAXLEN, self.DefaultHandler, id=txt.GetId()) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler, id=txt.GetId()) self.Controls[sName] = txt return txt # end def def DefaultHandler(self, event): # print 'event', str(event), 'id', event.GetId(), 'type', event.GetEventType() iEventID = event.GetId() iEventType = event.GetEventType() oWindow = event.GetEventObject() iID = oWindow.GetId() #print 'event', event, 'eventID', iEventID, 'eventType', iEventType, 'windowID', iID oParent = oWindow.GetParent() # for control in self.Controls.keys(): # window = self.FindWindowByName(control) for control, window in self.Controls.items(): try: result = window.GetValue() except: try: result = window.GetSelection() except: try: result = window.GetLabel() except: try: result = window.GetSelections() except: result = None self.Results[control] = result sName = event.GetEventObject().GetName() if self.ini and IsFocusEvent(event): sSection = self.GetTitle() sIni = self.ini sValue = win32api.GetProfileVal(sSection, sName, '', sIni) i = sValue.find(',') # if i >= 0: sValue = sValue[i + 1:].strip() # print sIni, sSection, sName, sValue self.SetStatus(sValue) if self.CustomHandler: return self.CustomHandler(self, event, sName) # self.Close() # if self.IsModal() and IsCloseEvent(event): self.EndModal(iID) if self.IsModal() and not IsFocusEvent(event) and sName.startswith('Button_'): self.EndModal(iID) # end def def Complete(self, buttons = ['OK', 'Cancel'], index=0, handler=None, statusbar=True, ini=GetIni(), idle=False): if len(buttons) > 0: self.AddButtonBand(buttons=buttons, index=index, handler=handler) else: self.CustomHandler = handler # self.Bind(wx.EVT_INIT_DIALOG, Activator) self.Bind(wx.EVT_INIT_DIALOG, self.DefaultHandler) self.Bind(wx.EVT_SHOW, self.DefaultHandler) self.Bind(wx.EVT_MENU, self.DefaultHandler) self.Bind(wx.EVT_CONTEXT_MENU, self.DefaultHandler) self.Bind(wx.EVT_CLOSE, self.DefaultHandler) # self.Bind(wx.EVT_CHAR, self.DefaultHandler) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler) # self.Bind(wx.EVT_SET_FOCUS, self.DefaultHandler) # at = wx.AcceleratorTable([(0, wx.WXK_ESCAPE, wx.ID_CANCEL)]) # self.SetAcceleratorTable(at) # self.SetEscapeId(wx.ID_CANCEL) # self.Bind(wx.EVT_COMMAND_SET_FOCUS, self.DefaultHandler) self.Bind(wx.EVT_CHILD_FOCUS, self.DefaultHandler) if idle: self.Bind(wx.EVT_IDLE, self.DefaultHandler) # self.Bind(wx.EVT_CHAR, self.DefaultHandler) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler) self.ini = ini if statusbar: self.AddBand() self.AddStaticText(label='', name='StaticText_Status') self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) iFlags = wx.GROW | wx.ALIGN_CENTER iFlags = wx.ALIGN_RIGHT iFlags = wx.ALIGN_CENTER self.Sizers[0].Add(self.Sizers[self.band], 1, iFlags) self.Sizers[0].Add(wx.Size(1, VERTICAL_DIVIDER_PAD)) self.SetSizerAndFit(self.Sizers[0]) self.Center() iID = self.ShowModal() # iID = self.Show() # wx.GetApp().MainLoop() # self.Close() return iID # end def def SetStatus(self, text=''): sb = self.Controls['StaticText_Status'] sb.SetLabel(text) def GetStatus(self): sb = self.Controls['StaticText_Status'] return sb.GetLabel()
class WidgetInChain(Widget): def __init__(self, id, parent, sub_widget_type, previous_widgets, args, kargs): Widget.__init__(self, id, parent) self._add_widget('expander', Expander) self._add_widget('sub_widget', sub_widget_type, *args, **kargs) self._add_widget('delete_button', ApplyButton) self._add_widget('new_widget_select', Select) self._add_widget('apply_new_widget', ApplyButton) self._add_widget('input_panel', MiniExpander, False) self._add_widget('input_apply', ApplyButton) if self.widgets.sub_widget.has_method('get_inputs'): inputs = self.widgets.sub_widget.get_inputs() if not type(inputs) in (list, tuple): raise Exception( 'get_inputs expected to return a list or a tuple') else: inputs = ['tables'] self.input_to_select = OrderedDict() for i, input in enumerate(inputs): w = self._add_widget('input_select_%d' % i, Select) self.input_to_select[input] = w w.values.choices = self.get_default_input(input, previous_widgets) def on_load(self): self.outputs_from_run = None if not 'new_widget_select' in self.widgets: self._add_widget('new_widget_select', Select) if not 'apply_new_widget' in self.widgets: self._add_widget('apply_new_widget', ApplyButton) def get_default_input(self, input, previous_widgets): for i in xrange(len(previous_widgets) - 1, -1, -1): if input in previous_widgets[i].get_outputs(): return ['%d,%s' % (i, input)] return [] def get_outputs(self): #if self.outputs_from_run == None: # raise Exception('Outputs can be queried only after run was called') #return self.outputs_from_run if self.widgets.sub_widget.has_method('get_outputs'): outputs = self.widgets.sub_widget.get_outputs() if not type(outputs) in (list, tuple): raise Exception( 'get_outputs expected to return a list or a tuple') else: outputs = ['tables'] return outputs def get_idx_outputs(self, input): ret = [] for input_choice in self.input_to_select[input].values.choices: idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] ret.append((idx, out)) return ret def update_input_after_delete(self, input, deleted_index): choices_to_delete = [] for i, input_choice in enumerate( self.input_to_select[input].values.choices): idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] if idx == deleted_index: choices_to_delete.append(input_choice) if idx > deleted_index: self.input_to_select[input].values.choices[i] = '%s,%s' % ( idx - 1, out) for choice in choices_to_delete: self.input_to_select[input].values.choices.remove(choice) def update_input_after_add(self, input, add_index): for i, input_choice in enumerate( self.input_to_select[input].values.choices): idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] if idx >= add_index: self.input_to_select[input].values.choices[i] = '%s,%s' % ( idx + 1, out) def create_input_map(self, data): input_map = {} for input in self.input_to_select: connected_outputs = self.get_idx_outputs(input) connected_outputs = [ data[idx][out] for idx, out in connected_outputs ] if connected_outputs: input_map[input] = sum(connected_outputs[1:], connected_outputs[0]) else: input_map[input] = None return input_map def run(self, data): self.outputs_from_run = [] if self.widgets.sub_widget.has_method('run'): if 'pre_run' in dir(self.widgets.sub_widget): self.widgets.sub_widget.pre_run() ret = self.widgets.sub_widget.run(**self.create_input_map(data)) #self.outputs_from_run = ret.keys() return ret def title(self, place_in_chain, short=False): if self.widgets.sub_widget.has_method('title'): ret = self.widgets.sub_widget.title(short) else: ret = widget_type_to_name(type(self.widgets.sub_widget)) if short: return '[%d] %s' % (place_in_chain + 1, ret) else: return '%d. %s' % (place_in_chain + 1, ret) def view(self, data, place_in_chain, possible_inputs): def create_inputs_summary(): summary = [] for input in self.input_to_select: choices = self.input_to_select[input].values.choices choice_texts = [ p[1] for p in possible_inputs if p[0] in choices ] #summary.append('%s: %s' % (input, choice_text)) summary.append('|'.join(choice_texts)) ret = ', '.join(summary) if ret: return 'Inputs: %s ' % ret else: if self.input_to_select: return 'Inputs' else: return '' #input_summary = View(self, '%sOutputs: %s' % ( # create_inputs_summary(), # ', '.join(self.get_outputs()))) input_summary = View(self, create_inputs_summary()) input_content_views = [] for k, v in self.input_to_select.items(): input_content_views.append( v.view(k, self.widgets.input_apply, possible_inputs, multiple=True)) input_content_views.append(self.widgets.input_apply.view()) input_content = view.stack_lines(*input_content_views) try: sub_widget_view = self.widgets.sub_widget.view( **self.create_input_map(data)) except Exception as e: logging.exception('Exception in view') sub_widget_view = View(self, str(e)) global CHAINABLE_WIDGETS widget_control_view = stack_left( self.widgets.new_widget_select.view('', self.widgets.apply_new_widget, zip(*CHAINABLE_WIDGETS)[0], False), self.widgets.apply_new_widget.view('Add before'), self.widgets.delete_button.view('Delete')) widget_control_view.main_html = '<div style="position:absolute; top:0; right:0;">%s</div>' % widget_control_view.main_html sub_view = view.stack_lines( widget_control_view, self.widgets.input_panel.view(input_summary, input_content), view.vertical_seperator(), sub_widget_view) #sub_view = self.widgets.sub_widget.view(data) #title_view = view.left_right( # View(self, self.title(place_in_chain)), # self.widgets.delete_button.view('Delete')) title_view = View(self, self.title(place_in_chain)) return self.widgets.expander.view(title_view, sub_view)
class WidgetInChain(Widget): def __init__(self, id, parent, sub_widget_type, previous_widgets, args, kargs): Widget.__init__(self, id, parent) self._add_widget('expander', Expander) self._add_widget('sub_widget', sub_widget_type, *args, **kargs) self._add_widget('delete_button', ApplyButton) self._add_widget('new_widget_select', Select) self._add_widget('apply_new_widget', ApplyButton) self._add_widget('input_panel', MiniExpander, False) self._add_widget('input_apply', ApplyButton) if self.widgets.sub_widget.has_method('get_inputs'): inputs = self.widgets.sub_widget.get_inputs() if not type(inputs) in (list, tuple): raise Exception('get_inputs expected to return a list or a tuple') else: inputs = ['tables'] self.input_to_select = OrderedDict() for i, input in enumerate(inputs): w = self._add_widget('input_select_%d' % i, Select) self.input_to_select[input] = w w.values.choices = self.get_default_input(input, previous_widgets) def on_load(self): self.outputs_from_run = None if not 'new_widget_select' in self.widgets: self._add_widget('new_widget_select', Select) if not 'apply_new_widget' in self.widgets: self._add_widget('apply_new_widget', ApplyButton) def get_default_input(self, input, previous_widgets): for i in xrange(len(previous_widgets)-1, -1, -1): if input in previous_widgets[i].get_outputs(): return ['%d,%s' % (i, input)] return [] def get_outputs(self): #if self.outputs_from_run == None: # raise Exception('Outputs can be queried only after run was called') #return self.outputs_from_run if self.widgets.sub_widget.has_method('get_outputs'): outputs = self.widgets.sub_widget.get_outputs() if not type(outputs) in (list, tuple): raise Exception('get_outputs expected to return a list or a tuple') else: outputs = ['tables'] return outputs def get_idx_outputs(self, input): ret = [] for input_choice in self.input_to_select[input].values.choices: idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] ret.append((idx, out)) return ret def update_input_after_delete(self, input, deleted_index): choices_to_delete = [] for i, input_choice in enumerate(self.input_to_select[input].values.choices): idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] if idx == deleted_index: choices_to_delete.append(input_choice) if idx > deleted_index: self.input_to_select[input].values.choices[i] = '%s,%s' % (idx - 1, out) for choice in choices_to_delete: self.input_to_select[input].values.choices.remove(choice) def update_input_after_add(self, input, add_index): for i, input_choice in enumerate(self.input_to_select[input].values.choices): idx = int(input_choice.split(',')[0]) out = input_choice.split(',')[1] if idx >= add_index: self.input_to_select[input].values.choices[i] = '%s,%s' % (idx + 1, out) def create_input_map(self, data): input_map = {} for input in self.input_to_select: connected_outputs = self.get_idx_outputs(input) connected_outputs = [data[idx][out] for idx,out in connected_outputs] if connected_outputs: input_map[input] = sum(connected_outputs[1:], connected_outputs[0]) else: input_map[input] = None return input_map def run(self, data): self.outputs_from_run = [] if self.widgets.sub_widget.has_method('run'): if 'pre_run' in dir(self.widgets.sub_widget): self.widgets.sub_widget.pre_run() ret = self.widgets.sub_widget.run(**self.create_input_map(data)) #self.outputs_from_run = ret.keys() return ret def title(self, place_in_chain, short=False): if self.widgets.sub_widget.has_method('title'): ret = self.widgets.sub_widget.title(short) else: ret = widget_type_to_name(type(self.widgets.sub_widget)) if short: return '[%d] %s' % (place_in_chain + 1, ret) else: return '%d. %s' % (place_in_chain + 1, ret) def view(self, data, place_in_chain, possible_inputs): def create_inputs_summary(): summary = [] for input in self.input_to_select: choices = self.input_to_select[input].values.choices choice_texts = [p[1] for p in possible_inputs if p[0] in choices] #summary.append('%s: %s' % (input, choice_text)) summary.append('|'.join(choice_texts)) ret = ', '.join(summary) if ret: return 'Inputs: %s ' % ret else: if self.input_to_select: return 'Inputs' else: return '' #input_summary = View(self, '%sOutputs: %s' % ( # create_inputs_summary(), # ', '.join(self.get_outputs()))) input_summary = View(self, create_inputs_summary()) input_content_views = [] for k,v in self.input_to_select.items(): input_content_views.append(v.view( k, self.widgets.input_apply, possible_inputs, multiple=True)) input_content_views.append(self.widgets.input_apply.view()) input_content = view.stack_lines(*input_content_views) try: sub_widget_view = self.widgets.sub_widget.view(**self.create_input_map(data)) except Exception as e: logging.exception('Exception in view') sub_widget_view = View(self, str(e)) global CHAINABLE_WIDGETS widget_control_view = stack_left( self.widgets.new_widget_select.view('', self.widgets.apply_new_widget, zip(*CHAINABLE_WIDGETS)[0], False), self.widgets.apply_new_widget.view('Add before'), self.widgets.delete_button.view('Delete')) widget_control_view.main_html = '<div style="position:absolute; top:0; right:0;">%s</div>' % widget_control_view.main_html sub_view = view.stack_lines( widget_control_view, self.widgets.input_panel.view(input_summary, input_content), view.vertical_seperator(), sub_widget_view) #sub_view = self.widgets.sub_widget.view(data) #title_view = view.left_right( # View(self, self.title(place_in_chain)), # self.widgets.delete_button.view('Delete')) title_view = View(self, self.title(place_in_chain)) return self.widgets.expander.view(title_view, sub_view)
class Dialog(wx.Dialog): # def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): # def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE): def __init__(self, parent=None, title='Dialog', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE): style = wx.RESIZE_BORDER wx.Dialog.__init__(self, parent=parent, title=title, pos=pos, size=size, style=style) # self.Bind(wx.EVT_INIT_DIALOG, self.DefaultHandler) self.SetName('Dialog_' + title) self.CustomHandler = None self.Results = {} self.Tips = {} self.Sizers = [] self.Controls = OrderedDict() self.Sizers.append(wx.BoxSizer(wx.VERTICAL)) self.band = 0 self.Sizers[0].Add(wx.Size(1, VERTICAL_DIVIDER_PAD)) self.AddBand() # super(self, '__init__') # wx.Dialog.__init__(self, parent=parent, id=id, title=title, pos=pos, size=size, style=style) # end def def AddBand(self): if self.band > 0: self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) iFlags = wx.GROW self.Sizers[0].Add(self.Sizers[self.band], 1, iFlags) self.Sizers[0].Add(wx.Size(1, VERTICAL_RELATED_PAD)) self.Sizers.append(wx.BoxSizer(wx.HORIZONTAL)) self.band += 1 self.Sizers[self.band].Add(wx.Size(HORIZONTAL_DIVIDER_PAD, 1)) # end def def AddButtonBand(self, buttons=[], index=0, handler=None): self.CustomHandler = handler self.AddBand() for i in range(len(buttons)): sButton = buttons[i] btn = self.AddButton(label=sButton) if index != None and index != -1 and i == index: btn.SetDefault() #print 'handler', handler # # self.Bind(wx.EVT_BUTTON, self.DefaultHandler, id=btn.GetId()) # end for # end def def AddButton(self, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel == 'OK': iID = wx.ID_OK # end if elif label == 'Cancel': iID = wx.ID_CANCEL # end elif elif label == 'Close': iID = wx.ID_CANCEL # iID = wx.ID_CLOSE # iID = 2 # end elif else: iID = wx.ID_ANY if sLabel.find('&') == -1: sLabel = '&' + sLabel # end else sName = name if len(sName) == 0: sName = 'Button_' + FixName(label) btn = wx.Button(parent=self, id=iID, label=sLabel, pos=pos, size=size, style=style, name=sName) self.Sizers[self.band].Add(btn, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_BUTTON, self.DefaultHandler, id=btn.GetId()) self.Controls[sName] = btn # print sName, iID return btn # end def def AddCheckBox(self, id=wx.ID_ANY, label='', value=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel.find('&') == -1: sLabel = '&' + sLabel sName = name if len(sName) == 0: sName = 'CheckBox_' + FixName(label) chk = wx.CheckBox(parent=self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) chk.SetValue(value) self.Sizers[self.band].Add(chk, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_CHECKBOX, self.DefaultHandler, id=chk.GetId()) self.Controls[sName] = chk return chk # end def def AddListBox(self, id=wx.ID_ANY, label='', names=[], values=[], sort=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.LB_HSCROLL, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'ListBox_' + FixName(label) iStyle = style if sort: iStyle |= wx.LB_SORT lst = wx.ListBox(parent=self, id=id, pos=pos, size=size, style=iStyle, name=sName) for i in range(len(names)): lst.Append(item=names[i], clientData=i) # end for if lst.GetCount(): lst.SetSelection(0) self.Sizers[self.band].Add(lst, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_LISTBOX, self.DefaultHandler, id=lst.GetId()) self.Controls[sName] = lst return lst # end def def AddMemo(self, id=wx.ID_ANY, label='', value='', readonly=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.TE_MULTILINE | wx.TE_PROCESS_ENTER, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'Memo_' + FixName(label) iStyle = style if readonly: iStyle |= wx.TE_READONLY txt = wx.TextCtrl(parent=self, id=id, pos=pos, size=size, style=iStyle, name=sName) txt.SetValue(value) self.Sizers[self.band].Add(txt, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Controls[sName] = txt # self.Bind(wx.EVT_SET_FOCUS, self.DefaultHandler, id=txt.GetId()) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler, id=txt.GetId()) return txt # end def def AddRadioButton(self, id=wx.ID_ANY, label='', value=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sLabel = label if sLabel.find('&') == -1: sLabel = '&' + sLabel iStyle = style if len(self.Controls) > 0 and not self.Controls[-1].startswith('RadioButton_'): iStyle = wx.RB_GROUP sName = name if len(sName) == 0: sName = 'RadioButton_' + FixName(label) rdn = wx.RadioButton(parent=self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) rdn.SetValue(value) self.Sizers[self.band].Add(rdn, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_RADIOBUTTON, self.DefaultHandler, id=rbn.GetId()) self.Controls[sName] = rdn return rdn # end def def AddRichEdit(self, id=wx.ID_ANY, label='', value='', readonly=False, pos=wx.DefaultPosition, size=wx.DefaultSize, style= wx.TE_MULTILINE | wx.TE_PROCESS_ENTER | wx.TE_RICH2, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'RichEdit_' + FixName(label) iStyle = style if readonly: iStyle |= wxTE_READONLY aSize = size if aSize == wx.DefaultSize: aSize = (300, 300) rtb = wx.TextCtrl(parent=self, id=id, pos=pos, size=aSize, style=iStyle, name=sName) rtb.SetMaxLength(0) rtb.SetValue(value) self.Sizers[self.band].Add(rtb, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.GROW) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_RADIOBUTTON, self.DefaultHandler, id=rtb.GetId()) self.Controls[sName] = rtb return rtb # end def def AddStaticText(self, id=wx.ID_ANY, label='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): sName = name if len(sName) == 0: sName = 'StaticText_' + FixName(label) sLabel = FixLabel(label) lbl = wx.StaticText(self, id=id, label=sLabel, pos=pos, size=size, style=style, name=sName) self.Sizers[self.band].Add(lbl, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) self.Controls[sName] = lbl return lbl # end def def AddTextCtrl(self, id=wx.ID_ANY, label='', value='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=DEFAULT_STYLE, name=''): if len(label) > 0: self.AddStaticText(label=label) sName = name if len(sName) == 0: sName = 'TextCtrl_' + FixName(label) iStyle = style if sName == 'TextCtrl_Password': iStyle |= wx.TE_PASSWORD aSize = size if aSize == wx.DefaultSize: aSize = (300, 21) txt = wx.TextCtrl(parent=self, id=id, pos=pos, size=aSize, style=iStyle, name=sName) txt.SetMaxLength(0) txt.SetValue(value) # sValue = unicode(value) # txt.SetValue(sValue) #txt.SetSize((2 * (txt.GetSize()[0]), txt.GetSize()[1])) # print txt.GetSize() self.Sizers[self.band].Add(txt, 1, wx.ALIGN_LEFT | wx.ALIGN_TOP) self.Sizers[self.band].Add(wx.Size(HORIZONTAL_RELATED_PAD, 1)) self.Bind(wx.EVT_TEXT, self.DefaultHandler, id=txt.GetId()) self.Bind(wx.EVT_TEXT_MAXLEN, self.DefaultHandler, id=txt.GetId()) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler, id=txt.GetId()) self.Controls[sName] = txt return txt # end def def DefaultHandler(self, event): # print 'event', str(event), 'id', event.GetId(), 'type', event.GetEventType() iEventID = event.GetId() iEventType = event.GetEventType() oWindow = event.GetEventObject() iID = oWindow.GetId() #print 'event', event, 'eventID', iEventID, 'eventType', iEventType, 'windowID', iID oParent = oWindow.GetParent() # for control in self.Controls.keys(): # window = self.FindWindowByName(control) for control, window in self.Controls.items(): try: result = window.GetValue() except: try: result = window.GetSelection() except: try: result = window.GetLabel() except: try: result = window.GetSelections() except: result = None self.Results[control] = result sName = event.GetEventObject().GetName() if self.ini and IsFocusEvent(event): sSection = self.GetTitle() sIni = self.ini sValue = win32api.GetProfileVal(sSection, sName, '', sIni) i = sValue.find(',') # if i >= 0: sValue = sValue[i + 1:].strip() # print sIni, sSection, sName, sValue self.SetStatus(sValue) if self.CustomHandler: return self.CustomHandler(self, event, sName) # self.Close() # if self.IsModal() and IsCloseEvent(event): self.EndModal(iID) if self.IsModal() and not IsFocusEvent(event) and sName.startswith('Button_'): self.EndModal(iID) # end def def Complete(self, buttons = ['OK', 'Cancel'], index=0, handler=None, statusbar=True, ini=GetIni(), idle=False): if len(buttons) > 0: self.AddButtonBand(buttons=buttons, index=index, handler=handler) else: self.CustomHandler = handler # self.Bind(wx.EVT_INIT_DIALOG, Activator) self.Bind(wx.EVT_INIT_DIALOG, self.DefaultHandler) self.Bind(wx.EVT_SHOW, self.DefaultHandler) self.Bind(wx.EVT_MENU, self.DefaultHandler) self.Bind(wx.EVT_CONTEXT_MENU, self.DefaultHandler) self.Bind(wx.EVT_CLOSE, self.DefaultHandler) # self.Bind(wx.EVT_CHAR, self.DefaultHandler) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler) # self.Bind(wx.EVT_SET_FOCUS, self.DefaultHandler) # at = wx.AcceleratorTable([(0, wx.WXK_ESCAPE, wx.ID_CANCEL)]) # self.SetAcceleratorTable(at) # self.SetEscapeId(wx.ID_CANCEL) # self.Bind(wx.EVT_COMMAND_SET_FOCUS, self.DefaultHandler) self.Bind(wx.EVT_CHILD_FOCUS, self.DefaultHandler) if idle: self.Bind(wx.EVT_IDLE, self.DefaultHandler) # self.Bind(wx.EVT_CHAR, self.DefaultHandler) # self.Bind(wx.EVT_KEY_DOWN, self.DefaultHandler) self.ini = ini if statusbar: self.AddBand() self.AddStaticText(label='', name='StaticText_Status') self.Sizers[self.band].Add(wx.Size(HORIZONTAL_LABEL_PAD, 1)) iFlags = wx.GROW | wx.ALIGN_CENTER iFlags = wx.ALIGN_RIGHT iFlags = wx.ALIGN_CENTER self.Sizers[0].Add(self.Sizers[self.band], 1, iFlags) self.Sizers[0].Add(wx.Size(1, VERTICAL_DIVIDER_PAD)) self.SetSizerAndFit(self.Sizers[0]) self.Center() iID = self.ShowModal() # iID = self.Show() # wx.GetApp().MainLoop() # self.Close() return iID # end def def SetStatus(self, text=''): sb = self.Controls['StaticText_Status'] sb.SetLabel(text) def GetStatus(self): sb = self.Controls['StaticText_Status'] return sb.GetLabel()
class Open: kind = 'open' number = 1 def __init__(self, bgpid, asnum, holdtime=180, version=4): self.version = version self.holdtime = holdtime self.asnum = asnum self.bgpid = bgpid self.caps = OD() self.params = OD() def from_bytes(cls, bytes): self = cls(None, None) assert len(bytes) >= 10, "open message must have 10 bytes" self.version, self.asnum, self.holdtime, bgpid, paramlen = struct.unpack_from('!BHH4sB', bytes) self.bgpid = socket.inet_ntoa(bgpid) assert len(bytes) == 10 + paramlen, "message too short?" offset = 10 while offset < len(bytes): type, plen = struct.unpack_from('BB', bytes, offset) offset += 2 value = bytes[offset:offset+plen] offset += plen if type==2: # capabilities idx = 0 while idx < len(value): kind, clen = struct.unpack_from('BB', value, idx) idx += 2 cap = value[idx:idx+clen] idx += clen if kind==1: kind = 'mbgp' iidx = 0 afi, reserved, safi = struct.unpack_from('!HBB', cap) cap = dict(afi=afi, safi=safi) elif kind==2: kind = 'refresh' elif kind==64: kind = 'graceful-restart' elif kind==65: kind = '4byteas' cap, = struct.unpack('!I', cap) if kind in self.caps: self.caps[kind].append(cap) else: self.caps[kind] = [cap] else: self.params[type] = value return self from_bytes = classmethod(from_bytes) def encode(self): params = '' for k,v in self.params.items(): params += struct.pack('BB', k, len(v)) params += v for c,vv in self.caps.items(): if c=='mbgp': c = 1 elif c=='refresh': c = 2 elif c=='graceful-restart': c = 64 elif c=='4byteas': c = 65 for v in vv: if c==1: v = struct.pack('!HH', v['afi'], v['safi']) elif c==65: v = struct.pack('!I', v) cap = struct.pack('BB', c, len(v)) + v params += struct.pack('BB', 2, len(cap)) + cap bgpid = socket.inet_aton(self.bgpid) return struct.pack('!BHH4sB', self.version, self.asnum, self.holdtime, bgpid, len(params)) + params def __str__(self): s = 'Open message ver=%s as#=%s hold=%s peer=%s' % ( self.version, self.asnum, self.holdtime, self.bgpid, ) for p,v in self.params.items(): s += ' param %s=%r' % (p,v) for c,v in self.caps.items(): s += ' cap %s=%r' % (c,v) return s
class Update: kind = 'update' number = 2 def __init__(self, *pathattr, **kw): self.nlri = [] self.withdraw = [] self.pathattr = OD() for n in kw.pop('nlri', []): if isinstance(n, str): n = nlri.ipv4(n) self.nlri.append(n) for w in kw.pop('withdraw', []): if isinstance(w, str): w = nlri.ipv4(w) self.withdraw.append(w) self.pathattr = OD() for p in pathattr: self.pathattr[p.type] = p def from_bytes(cls, bytes): self = cls() d = {} idx = 0 for kind in ('withdraw', 'pathattr'): plen, = struct.unpack_from('!H', bytes, idx) idx += 2 d[kind] = bytes[idx:idx+plen] idx += plen self.nlri = nlri.parse(bytes[idx:]) self.withdraw = nlri.parse(d['withdraw']) self.pathattr = OD() idx = 0 bytes = d['pathattr'] while idx < len(bytes): used, pattr = pathattr.decode(bytes, idx) idx += used self.pathattr[pattr.type] = pattr return self from_bytes = classmethod(from_bytes) def __repr__(self): s = '<Update message withdraw=%r' % (self.withdraw,) for type,p in self.pathattr.items(): s += '\n path attr %s' % (p,) if type=='mp-reach-nlri': for n in p.value['nlri']: s += '\n nlri=%s' % (n,) for n in self.nlri: s += '\n nlri %s' % (n,) s += '>' return s def __cmp__(self, other): if isinstance(other, Update): return cmp( (self.pathattr, self.withdraw, self.nlri), (other.pathattr, other.withdraw, other.nlri), ) return -1 def encode(self): v = '' w = '' for n in self.withdraw: w += n.encode() v += struct.pack('!H', len(w)) v += w p = '' for kind, attr in self.pathattr.items(): p += attr.encode() v += struct.pack('!H', len(p)) v += p for n in self.nlri: v += n.encode() return v