def su_edit(request, slug): '''SU edit item page.''' if not request.user.is_authenticated(): return redirect('django.contrib.auth.views.login') tree = ET.parse(util.checkBaseline()) c = getSUContext(request, tree) c['upload'], c['dlg_title'], c['dlg_msg'] = handleUpload(request) c['post'] = findContext(c['pages']+c['posts']+c['trash'], slug) c['post']['content'] = loadContent(c['post']) parent_choices = [('0', '0')] if c['post']['type'] == 'page': pages = flattenMenu(getMenu(tree)) if slug in pages: pages.remove(slug) page_choices = [(p, p) for p in pages] parent_choices.extend(page_choices) if request.method == 'POST': c['form'] = EditForm(request.POST, parents=parent_choices) if c['form'].is_valid(): item = formToItem(c['form'], c['post']) if save(c['post']['name'], item): return redirect('su') c['dlg_title'] = "Failed to save %s" % (c['post']['type']) c['dlg_msg'] = "An error occurred while attempting to save. Try again." else: c['form'] = itemToForm(c['post'], parent_choices) if c['post']['trash'] and c['post']['trash'].lower() == 'true': c['readonly'] = True t = util.getTemplate('su_edit.html', isSU=True) return HttpResponse(t.render(c))
def getDetail(request, type, slug, date=None): '''Get the response for a page or post. Args: request: Django HttpRequest object type: The type of response requested. Must be 'page' or 'post'. slug: Name/ID of the item. date: Optional date of item used to reduce searching. Returns: An HttpResponse for the requested item. ''' what = {'post': 'posts', 'page': 'pages'} xml_tree = ET.parse(util.checkBaseline()) wp_tree = wp.loadXML() c = getDefaultContext(request) c['posts'] = getItems(xml_tree, what[type], isVisible) if not date or date.strftime('%Y-%m-%d') <= Config.WP_END_DATE: c['posts'] += wp.getItems(wp_tree, what[type]) c['post'] = findContext(c['posts'], slug) if c['post']: c['post']['content'] = loadContent(c['post']) c['title'] += " - %s" % (c['post']['title']) assembleContext(c, xml_tree, wp_tree) t = util.getTemplate('detail.html') return HttpResponse(t.render(c)) return get404(request, xml_tree, wp_tree)
class Line(Shape): component_xml = util.getTemplate('LINE-PARTS') def injectComponents(self): """ the base Shape class inserts the Geom elements """ Shape.injectComponents(self) #Layout can be inserted as is. It goes before textXFormNode layout = self.components['Layout'] if not layout: raise DomException, "Layout not found in components" textXFormNode = self.selectSingleNode(self.dom, 'Shape/TextXForm') if not textXFormNode: raise DomException("TextXForm not found in Shape") self.doc.insertBefore(layout, textXFormNode) xForm1D = self.components['XForm1D'] if not xForm1D: raise DomException, "XForm1D not found in components" self.doc.insertBefore(xForm1D, layout) # now compute and insert XForm1D # whole-object connections do not need these elements killTags = ['XForm', 'Geom'] # print 'Killing %d tags ...' % len(killTags) for tag in killTags: node = self.selectSingleNode(self.dom, 'Shape/' + tag) if not node: raise Exception, 'could find node to kill: %s' % tag removed = self.doc.removeChild(node) removed.unlink() # print ' - REMOVED', tag def addCustomAttrs(self, opts): """ called in Shape.__init__ just before DOM is updated with values from Shape attrs """ # print 'addCustomAttrs: %s' % opts self.xpaths.update({'EndArrow': 'Shape/Line/EndArrow'}) self.ObjType = 2 self.EndArrow = 1
def get404(request, xml_tree, wp_tree): '''Get a 404 response. Args: request: View request object. xml_tree: Standard XML tree object. wp_tree: WordPress XML tree object. Returns: HttpResponseNotFound object. ''' c = getDefaultContext(request) c['menu'] = getMenu(xml_tree, wp_tree) t = util.getTemplate('404.html') return HttpResponseNotFound(t.render(c))
def getSU(request, err_title_msg=None): '''Get the SU page response Args: request: Django HttpRequest object err_title_msg: Tuple with structure: (error title, error message) Returns: An HttpResponse for the SU page. ''' if not request.user.is_authenticated(): return redirect('django.contrib.auth.views.login') tree = ET.parse(util.checkBaseline()) c = getSUContext(request, tree) if err_title_msg: c['dlg_title'] = err_title_msg[0] c['dlg_msg'] = err_title_msg[1] else: c['upload'], c['dlg_title'], c['dlg_msg'] = handleUpload(request) t = util.getTemplate('su.html', isSU=True) return HttpResponse(t.render(c))
def showList(request, category=None, tag=None): '''Get response for showing a list of posts. Args: request: View request object. category: Show only items containing this category string. tag: Show only items containing this tag string. Returns: A post list response. ''' p = int(request.GET.get('p', 0)) itemsPerPage = Config.POSTS_PER_PAGE xml_tree = ET.parse(util.checkBaseline()) wp_tree = wp.loadXML() c = getDefaultContext(request) filter = isVisible if category: filter = lambda d: category in d['categories'] and isVisible(d) if tag: filter = lambda d: tag in d['tags'] and isVisible(d) all_posts = getItems(xml_tree, 'posts', filter) + \ wp.getItems(wp_tree, 'posts', filter) posts = all_posts[p*itemsPerPage:(p+1)*itemsPerPage] c['prev'] = -1 if p == 0 else p-1 c['next'] = -1 if p >= len(all_posts)/itemsPerPage else p+1 if len(posts) > 0: for p in posts: p['content'] = loadContent(p) assembleContext(c, xml_tree, wp_tree) c['posts'] = posts tfile = 'index.html' if category or tag: tfile = 'cattag.html' c['title'] += " - Tagged %s" % (tag) if tag else " - Category %s" % (category) t = util.getTemplate(tfile) return HttpResponse(t.render(c)) return get404(request, xml_tree, wp_tree)
class VdxRecord(MetaDataRecord): verbose = 0 xpath_delimiter = '/' # default_vdx_template = 'VDX-TEMPLATE.xml' default_vdx_template = util.getTemplate('VDX-TEMPLATE') def __init__(self, template=None): template = template or self.default_vdx_template MetaDataRecord.__init__(self, path=template) self.shapes = UserDict() self.edges = UserDict() self.nodes = UserDict() def getShapeNodes(self): """ return the shape elements from DOM """ return self.selectNodes(self.dom, 'VisioDocument/Pages/Page/Shapes/Shape') def getShapeId(self): return str(len(self.getShapeNodes()) + 1) def _shapeGetter(self, shapeId): return self.getShape(shapeId) def getShapeByName(self, name): # print 'getShapeByName (%s)' % name for node in self.shapes.values(): if node.Name == name: return node def getShape(self, shapeId): """ return the Shape instance for provided shapeId or None if not defined """ return self.shapes.has_key(shapeId) and self.shapes[shapeId] or None def makeEdgeShape(self, source, target, relation, id=None): id = id or self.getShapeId() # return makeConnectorShape(source, target, relation, self.getShapeId()) line_args = { 'name': 'connector', 'label': { 'text': relation }, # 'x' : avg (start[0], end[0]), # 'y' : avg (start[1], end[1]), # 'x' : start[0], # 'y' : start[1], # 'height' : diff (end[1], start[1]) or util.pt2in(2), # 'width' : diff (end[0],start[0]), # 'begin_x' : start[0], # 'begin_y' : start[1], # 'end_x' : end[0], # 'end_y' : end[1] } return Line(id, line_args) def addEdge(self, sourceId, targetId, relation): try: # source = self.getShape(sourceId) #source = self.getShapeByName(sourceId) source = self._shapeGetter(sourceId) if not source: raise Exception, "sourceId '%s'" % sourceId # target = self.getShape(targetId) # target = self.getShapeByName(targetId) target = self._shapeGetter(targetId) if not target: raise Exception, "targetId '%s'" % targetId except Exception, msg: print "addEdge Error: could not find a shape (%s)" % msg # print self print "SHAPE KEYS: %s" % self.shapes.keys() for key in self.shapes.keys(): # print "%s: %s" % (key, self.shapes[key]) print " - ", key print "HALTInG ..." sys.exit() # edge = makeConnectorShape(source, target, relation, self.getShapeId()) edge = self.makeEdgeShape(source, target, relation, self.getShapeId()) # parent = self.selectSingleNode (self.dom, 'VisioDocument/Pages/Page/Shapes') # if not parent: # raise xml.dom.NotFoundErr, 'Shapes node not found' # parent.appendChild(edge.getElement()); self.edges[edge.ID] = edge self.addShapeObj(edge) # add the connect element self.addConnect(edge, source, target) return edge.ID
r = requests.get( f"https://api.github.com/repos/{os.environ['GITHUB_REPOSITORY']}/contributors?per_page={os.getenv('INPUT_MAX_CONTRIBUTORS', '10')}", headers={"cache-control": "no-cache"}, ) contributors = list(filter(lambda x: x["login"] != "actions-user", r.json())) if not showNumbers: def removeNumbers(x: dict): x.pop("contributions") return x contributors = list(map(removeNumbers, contributors)) rendered = getTemplate(contributors) storedContributors = getStoredContributors() # Only update list if # a) the stored contributor list isn't there # b) the user wants to display contribution numbers # c) the list of contributors has been updated since the last push if ((storedContributors is None) or showNumbers or (storedContributors != stripToLogin(contributors))): if storedContributors != stripToLogin(contributors): print( f"Current contributors in README: {json.dumps(storedContributors)}\nActual repo contributors: {json.dumps(stripToLogin(contributors))}" ) setStoredContributors(stripToLogin(contributors))
class Shape(MetaDataRecord): """ generic shape class, to be subclassed to add Geometry """ xpath_delimiter = '/' shape_template = util.getTemplate('SHAPE-TEMPLATE') component_xml = None # subclasses provide xml file # there must be an xpath for every value we will write to DOM xpaths = { 'ID': 'Shape/@ID', 'Name': 'Shape/@Name', 'Type': 'Shape/@Type', 'PinX': 'Shape/XForm/PinX', 'PinY': 'Shape/XForm/PinY', 'Width': 'Shape/XForm/Width', 'Height': 'Shape/XForm/Height', 'ObjType': 'Shape/Misc/ObjType', 'LineWeight': 'Shape/Line/LineWeight', 'LineColor': 'Shape/Line/LineColor', 'CharSize': 'Shape/Char/Size', 'CharColor': 'Shape/Char/Color', 'Text': 'Shape/Text' } # provided shape args override these defaults default_shape_args = { 'name': 'unnamed', 'x': 1, 'y': 1, 'height': 1, 'width': 1, 'line': { 'weight': 1, 'color': '0' }, 'label': { 'text': '', 'size': 12, 'color': '0' } } def __init__(self, id, args=None): MetaDataRecord.__init__(self, path=self.shape_template) # make a copy so we don't stomp default_shape_args opts = copy.deepcopy(self.default_shape_args) if args is not None: util.update(opts, args) # define all attributes to match xpath mapping above. # the xpath mappings determine what attributes are written to DOM. self.ID = id self.Name = opts['name'] self.Type = "Shape" self.PinX = opts['x'] self.PinY = opts['y'] self.Width = opts['width'] self.Height = opts['height'] self.ObjType = 1 self.LineWeight = util.pt2in(opts['line']['weight']) #from px to inch self.LineColor = opts['line']['color'] self.CharSize = util.pt2in(opts['label']['size']) self.CharColor = opts['label']['color'] self.Text = opts['label']['text'] self.addCustomAttrs(opts) # inject components self.components = ComponentRecord(path=self.component_xml) try: # assigns components record as side effect self.injectComponents() except KeyError, msg: raise Exception, "ERROR: cannot inject component: %s" % msg # write element values to DOM for attr in self.xpaths: try: self.set(attr, str(getattr(self, attr))) except Exception, msg: # print 'WARN: set failed for %s' % attr pass
class Circle(SHAPE_BASE_CLASS): component_xml = util.getTemplate('CIRCLE-PARTS')
class Rectangle(SHAPE_BASE_CLASS): component_xml = util.getTemplate('RECTANGLE-PARTS')