示例#1
0
def addRow(request):
    email = request.COOKIES.get('user')
    d = dict()
    try:
        d['user'] = User.objects.get(email=email)
    except:
        d['message'] = 'Unknown user.'
        d['redirect'] = "/"  # redirect to main page
        return getDbData(request)
    if request.method == 'POST':
        projname = request.POST['projname']
        tablename = request.POST['tablename']
        # rowdata is a list of data: ["prvni sloupec","druhy sloupec",...]
        # je treba to tu nejak poskladat, musi to byt seznam kvuli poradi zaznamu...
        #rowdata = ["0","pepa"]      # temporary data
        rowdata = json.loads(request.POST['rowdata'])

        rowdata[0] = XML.GenerateID(enc(d['user'].pk, projname), tablename)

        try:
            XML.AddRow(enc(d['user'].pk, projname), tablename, rowdata)
        except XML.DoesNotExistError:
            d['message'] = 'Database or table does not exist.'
        except XML.IncompatibleRowDataError:
            d['message'] = 'Row data incompatible.'
        except XML.TableNotFoundError:
            d['message'] = 'Table was not found.'
        #print(d['message'])
        return getDbData(request)
示例#2
0
	def test_countChildren_multipleChildren(self):
		s = "<xml><THU><Team><ACRush></ACRush><Jelly></Jelly><Cooly></Cooly></Team><JiaJia><Team><Ahyangyi></Ahyangyi><Dragon></Dragon><Cooly><Amber></Amber></Cooly></Team></JiaJia></THU><Team><Cooly></Cooly><Jelly></Jelly></Team></xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		patternChildren = 0
		patternChildren = XML.countChildren(pattern)
		self.assertTrue(patternChildren == 2)
示例#3
0
def main():

    # part1:
    #-------------------------------------------------------------------
    Part1.Part1()
    #-------------------------------------------------------------------


    # part2:
    #-------------------------------------------------------------------
    # set last parameter to true to enable export of shots
    stitched_shots, all_shots, outstitched_shots = Part2.Part2(False)
    #-------------------------------------------------------------------


    #html stuff:
    #-------------------------------------------------------------------
    HTML.html_stuff(stitched_shots, all_shots, outstitched_shots, 'Oberstdorf16-shots.csv',
               './html_input/index_part1.txt', './html_input/index_part2.txt', './html_output/index.html')
    #-------------------------------------------------------------------


    #xml stuff:
    #-------------------------------------------------------------------
    XML.create_XML('caffe_output.txt')
示例#4
0
 def dumb_loop(self, ip='localhost', port=49494, dest_ip='localhost', dest_port=8000):
     #print("in dumb loop")
     #ping the game server
     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     #sock.bind((ip, port))
     sock.connect((dest_ip, dest_port))
     #sock.listen(1)
     while True:
         #connection, client_addr = sock.accept()
         data = XML.add_spaces(sock.recv(8192))
         #print(data)
         msg_type = data.split()[0][1:-1]
         if msg_type == 'start-game':
             #print("SPlayer::dumb_loop: got a start-game")
             sg_d = xmltodict.parse(data)
             name = self.startGame(sg_d['start-game'])
             sock.sendall(XML.encode_name(name))
         elif msg_type == 'do-move':
             #print("SPlayer::dumb_loop: got a do-move")
             board, dice = XML.decode_do_move(xmltodict.parse(data)['do-move'])
             moves = self.doMove(board, dice)
             encoded_moves = XML.encode_moves(moves)
             #print("sending these moves back: "+encoded_moves)
             #print("")
             sock.sendall(encoded_moves)
         elif msg_type == 'doubles-penalty':
             #print("SPlayer::dumb_loop: got a doubles-penalty")
             self.doublesPenalty()
             sock.sendall(XML.encode_void())
示例#5
0
文件: Message.py 项目: SkyFire/cia-vc
    def preprocess(self):
        message = XML.dig(self.xml, "message")
        if not message:
            raise XML.XMLValidityError("A Message's root node must be named 'message'")

        # Stamp it with the current time if it has no timestamp yet
        if not XML.dig(message, "timestamp"):
            XML.addElement(message, "timestamp", "%d" % time.time())
示例#6
0
文件: Ruleset.py 项目: Kays/cia-vc
 def dbIter(self):
     if os.path.isfile(self.path):
         dom = XML.parseStream(open(self.path))
         for element in XML.getChildElements(dom.documentElement):
             if element.nodeName == "ruleset":
                 yield element
     else:
         log.msg("The file %r does not exist, loading no rulesets" % self.path)
示例#7
0
文件: Message.py 项目: SkyFire/cia-vc
 def textComponent(self, element, args, *path):
     """A convenience function for defining components that just look for a node
        in the message and return its shallowText.
        """
     element = XML.dig(args.message.xml, *path)
     if element:
         return [XML.shallowText(element)]
     else:
         return [MarkAsHidden()]
示例#8
0
 def textComponent(self, element, args, *path):
     """A convenience function for defining components that just look for a node
        in the message and return its shallowText.
        """
     element = XML.dig(args.message.xml, *path)
     if element:
         return [XML.shallowText(element)]
     else:
         return [MarkAsHidden()]
示例#9
0
	def test_findMatches_guaranteed_match(self):
		s = "<xml><THU><Team></Team></THU><THU></THU></xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		patternChildren = 0
		patternChildren = XML.countChildren(pattern)
		XML.matches = 0
		XML.findMatches(a, pattern, patternChildren)
		self.assertTrue(XML.matches == 0)
示例#10
0
	def test_count_breadth(self):
		s = "<xml><THU><Team></Team><ACRush></ACRush><Jelly></Jelly><Cooly></Cooly><JiaJia></JiaJia><Ahyangyi></Ahyangyi><Dragon></Dragon></THU></xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		patternChildren = 0
		patternChildren = XML.countChildren(pattern)
		XML.numElements = 0
		XML.numElements = XML.count(a, pattern, patternChildren)
		self.assertTrue(XML.numElements == 8)
示例#11
0
	def test_findMatches(self):
		s = "<xml><THU><Team><ACRush></ACRush><Jelly></Jelly><Cooly></Cooly></Team><JiaJia><Team><Ahyangyi></Ahyangyi><Dragon></Dragon><Cooly><Amber></Amber></Cooly></Team></JiaJia></THU><Team><Cooly></Cooly></Team></xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		patternChildren = 0
		patternChildren = XML.countChildren(pattern)
		XML.locations = []
		XML.locations = XML.findMatches(a, pattern, patternChildren)
		self.assertTrue(XML.locations == []) #function only works in conjunction with the count function
示例#12
0
	def test_count(self):
		s = "<xml><THU>\n\t<Team>\n\t\t<ACRush></ACRush>\n\t\t<Jelly></Jelly>\n\t\t<Cooly></Cooly>\n\t</Team>\n\t<JiaJia>\n\t\t<Team>\n\t\t\t<Ahyangyi></Ahyangyi>\n\t\t\t<Dragon></Dragon>\n\t\t\t<Cooly><Amber></Amber></Cooly>\n\t\t</Team>\n\t</JiaJia>\n</THU>\n<Team><Cooly></Cooly></Team>\n</xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		patternChildren = 0
		patternChildren = XML.countChildren(pattern)
		XML.numElements = 0
		XML.numElements = XML.count(a, pattern, patternChildren)
		self.assertTrue(XML.numElements == 13)
示例#13
0
    def preprocess(self):
        message = XML.dig(self.xml, "message")
        if not message:
            raise XML.XMLValidityError(
                "A Message's root node must be named 'message'")

        # Stamp it with the current time if it has no timestamp yet
        if not XML.dig(message, "timestamp"):
            XML.addElement(message, "timestamp", "%d" % time.time())
示例#14
0
 def dbIter(self):
     if os.path.isfile(self.path):
         dom = XML.parseStream(open(self.path))
         for element in XML.getChildElements(dom.documentElement):
             if element.nodeName == "ruleset":
                 yield element
     else:
         log.msg("The file %r does not exist, loading no rulesets" %
                 self.path)
示例#15
0
def __getPublicPrefs():
    #
    # Return an XML description of all exposed preferences
    #
    global __publicPrefs
    pp = XML.Element("PluginPreferences")
    for key in __publicPrefs:
        e = XML.ElementWithText(key, Get(key))
        e.set("description", __publicPrefs[key])
        pp.append(e)
    return XML.ElementToString(pp)
示例#16
0
 def getXMLMailHeaders(self, document):
     """Return a <mailHeaders> tag representing a subset of the headers
        for this message. This is placed in the <generator> tag of any
        message passing through this module, to document and log the
        message's true source.
        """
     node = document.createElementNS(None, "mailHeaders")
     for name, value in self.message.items():
         if name in interestingHeaders:
             XML.addElement(node, "header", content=str(value)).setAttributeNS(None, 'name', name)
     return node
示例#17
0
def main():
    # Creating the banner:
    print(create_banner())

    # Asking the user in which mode the program needs to be run:
    mode = ask_mode()

    # If the program is ran in mode 2, ask the IP-address and present results form SQLite database:
    if mode == '2':
        ip_address = ask_ip_address()
        SQL.show_results(ip_address)
        sys.exit()

    # Asking for user input needed to execute the portscan:
    scan_type = ask_scantype()
    target = ask_host()
    first_port = ask_first_port()
    last_port = ask_last_port(first_port)
    save_output = ask_output()

    # Creating the dictionary to store scan results:
    portscan = create_dict(target, scan_type)

    # Check which scan to conduct and execute scan (while using threading to speed up the scan):
    if scan_type == "TCP-Connect Scan":
        print(70 * "-" + "\n*** Starting TCP-Connect Scan ***")
        threader(portscans.TCP_connect_scan, target, first_port, last_port, portscan)
    elif scan_type == "UDP Scan":
        print(70 * "-" + "\n*** Starting UDP Scan ***")
        # Executing UDP scan without threading, because this creates false positives,
        # possibly because packets are sent faster then the router can respond with an ICMP type 3 code 3 packet:
        portscans.UDP_scan(target, first_port, last_port, portscan)
    elif scan_type == "TCP-SYN Scan":
        print(70 * "-" + "\n*** Starting TCP-SYN Scan ***")
        threader(portscans.TCP_SYN_scan, target, first_port, last_port, portscan)
    elif scan_type == "TCP-XMAS Scan":
        print(70 * "-" + "\n*** Starting TCP-XMAS Scan ***")
        threader(portscans.XMAS_scan, target, first_port, last_port, portscan)

    # Sorting the lists within the portscan dictionary:
    sort_dict(portscan)

    # Writing the scan results to a XML or JSON file, if specified:
    if save_output:
        if save_output in ['xml', 'XML']:
            XML.writeToXML(portscan)
        elif save_output in ['json', 'JSON']:
            writeToJSON(portscan)

    # Writing the scan results to a SQLite database file:
    SQL.writeToSQLite(portscan)

    # Printing finished line:
    print("*** Portscan finished ***")
示例#18
0
 def getXMLMailHeaders(self, document):
     """Return a <mailHeaders> tag representing a subset of the headers
        for this message. This is placed in the <generator> tag of any
        message passing through this module, to document and log the
        message's true source.
        """
     node = document.createElementNS(None, "mailHeaders")
     for name, value in self.message.items():
         if name in interestingHeaders:
             XML.addElement(node, "header",
                            content=str(value)).setAttributeNS(
                                None, 'name', name)
     return node
示例#19
0
    def pathMatchTag(self, element, function, textExtractor=XML.shallowText):
        """Implements the logic common to all tags that test the text matched by
           an XPath against the text inside our element. The given function is used
           to determine if the text matches. This implements the properties common to
           several elements:

             - The caseSensitive attribute defaults to 1, but can be set to zero
               to force both strings to lowercase.

             - Each XPath match is tested separately, with 'or' semantics:
               if any of the XPath matches cause the provided function to match,
               this returns True

             - If there are no XPath matches, returns False
           """
        path = element.getAttributeNS(None, 'path')
        xp = XML.XPath(XML.pathShortcuts.get(path, path))

        # Are we doing a case sensitive match? Default is no.
        caseSensitive = element.getAttributeNS(None, 'caseSensitive')
        if caseSensitive:
            caseSensitive = int(caseSensitive)
        else:
            caseSensitive = 0

        text = XML.shallowText(element).strip()
        if not caseSensitive:
            text = text.lower()

        def filterMatch(msg):
            # Use queryobject then str() so that matched
            # nodes without any text still give us at least
            # the empty string. This is important so that <find>
            # with an empty search string can be used to test
            # for the existence of an XPath match.
            nodes = xp.queryObject(msg)
            if nodes:
                matchStrings = map(textExtractor, nodes)

                # Any of the XPath matches can make our match true
                for matchString in matchStrings:
                    matchString = matchString.strip()
                    if not caseSensitive:
                        matchString = matchString.lower()
                    if function(matchString, text):
                        return True
            return False

        return filterMatch
示例#20
0
 def caps_store(self, path, xml):
     """Generate a list of acceptable capabilities to grant access to 'store'.
        In addition to the usual ones, allow ('ruleset.uri', x) where x is the
        ruleset's URI.
        """
     uri = XML.parseString(xml).documentElement.getAttributeNS(None, 'uri')
     return self.makeDefaultCaps(path) + [('ruleset.uri', uri)]
示例#21
0
文件: __init__.py 项目: dhutty/bcfg2
    def run_probes(self):
        """ run probes and upload probe data """
        try:
            probes = XML.XML(str(self.proxy.GetProbes()))
        except (Proxy.ProxyError,
                Proxy.CertificateError,
                socket.gaierror,
                socket.error):
            err = sys.exc_info()[1]
            self.fatal_error("Failed to download probes from bcfg2: %s" % err)
        except XML.ParseError:
            err = sys.exc_info()[1]
            self.fatal_error("Server returned invalid probe requests: %s" %
                             err)

        self.times['probe_download'] = time.time()

        # execute probes
        probedata = XML.Element("ProbeData")
        for probe in probes.findall(".//probe"):
            probedata.append(self.run_probe(probe))

        if len(probes.findall(".//probe")) > 0:
            try:
                # upload probe responses
                self.proxy.RecvProbeData(
                    XML.tostring(probedata,
                                 xml_declaration=False).decode('utf-8'))
            except Proxy.ProxyError:
                err = sys.exc_info()[1]
                self.fatal_error("Failed to upload probe data: %s" % err)

        self.times['probe_upload'] = time.time()
示例#22
0
 def element_match(self, element):
     """Compare a given variable exactly to the element's content, not including
        leading and trailing whitespace.
        """
     return "(%s = %s)" % (
         self.varLookup(element.getAttributeNS(None, 'var')),
         quote(XML.shallowText(element).strip(), 'varchar'))
示例#23
0
文件: Ruleset.py 项目: Kays/cia-vc
 def rulesetReturn(msg):
     nodes = xp.queryObject(msg)
     if nodes:
         self.result = XML.allText(nodes[0]).strip()
     else:
         self.result = None
     raise RulesetReturnException()
示例#24
0
def renamepage(request):
    d = dict()
    email = request.COOKIES.get('user')
    try:
        d['user'] = User.objects.get(email=email)
    except:
        d['message'] = 'Unknown user.'
        d['redirect'] = "/"  # redirect to main page
        return redirect("/")
    else:
        if request.method == 'POST':
            oldproject = request.POST['projname']
            newproject = request.POST['newprojname']
            try:
                XML.RenameProject(enc(d['user'].pk, oldproject),
                                  enc(d['user'].pk, newproject))
            except XML.AlreadyExistsError:
                d['message'] = 'New project already exists.'
                return redirect('dashboard')
            except XML.AlreadyExistsError:
                d['message'] = 'Old project does not exist.'
                return redirect('dashboard')
            # nejsem si jistý nasledujicima dvema radkama !!!
            w = models.Webpage.objects.get(name=oldproject, user=d['user'].pk)
            w.name = str(newproject)
            w.save()

    return redirect('dashboard')
示例#25
0
def createFile(request):
    email = request.COOKIES.get('user')
    d = dict()
    try:
        d['user'] = User.objects.get(email=email)
    except:
        d['message'] = 'Unknown user.'
        d['redirect'] = "/"  # redirect to main page
        return getDirData(request)
    if request.method == 'POST':
        projname = request.POST['projname']
        path = json.loads(request.POST['requestpath'])
        name = request.POST['name']
        size = request.POST['size']
        try:
            XML.AddToFiletree(enc(d['user'].pk, projname), path, name, 'f',
                              "unknown", size)
        except XML.NameContainsWrongCharError:
            d['message'] = 'File/dir name contains unacceptable characters (only [a-zA-Z0-9_.]).'
        except XML.DoesNotExistError:
            d['message'] = 'Path or directory does not exist.'
        except XML.WrongTypeError:
            d['message'] = 'You cannot put things into file.'
        except XML.AlreadyExistsError:
            d['message'] = 'File/dir with the same name already exists.'
        return getDirData(request)
示例#26
0
 def element_like(self, element):
     """Compare a given variable to the element's content using SQL's 'LIKE' operator,
        not including leading and trailing whitespace. This is case-insensitive, and includes
        the '%' wildcard which may be placed at the beginning or end of the string.
        """
     return "(%s LIKE %s)" % (self.varLookup(element.getAttributeNS(None, 'var')),
                              quote(XML.shallowText(element).strip(), 'varchar'))
示例#27
0
    def component_text(self, element, args):
        """This is a generic version of textComponent, in which 'path' can
           be specified by users. Any textComponent can be rewritten as a
           <text> component.
           """
        path = element.getAttributeNS(None, 'path')
        if not path:
            raise XML.XMLValidityError(
                "The 'path' attribute on <text> is required.")
        xp = XML.XPath(XML.pathShortcuts.get(path, path))

        nodes = xp.queryObject(args.message)
        if nodes:
            return [XML.shallowText(nodes[0])]
        else:
            return [MarkAsHidden()]
示例#28
0
    def __init__(self, src="", id="", loglevel=0, debug=0):

        self.ckin = 0
        self._owner = 0
        self.verbose = 1
        fname = os.path.basename(src)
        ff = os.path.splitext(fname)

        if src:
            root = XML.XML_Node(name='doc', src=src, preprocess=1, debug=debug)

        if id:
            s = root.child(id=id)

        else:
            s = root.child(name="phase")

        self._name = s['id']

        # initialize the equation of state
        ThermoPhase.__init__(self, xml_phase=s)

        # initialize the kinetics model
        ph = [self]
        Kinetics.__init__(self, xml_phase=s, phases=ph)

        # initialize the transport model
        Transport.__init__(self,
                           xml_phase=s,
                           phase=self,
                           model='',
                           loglevel=loglevel)
示例#29
0
    def evalComponent(self, node, args):
        """Given a DOM node for a component, evaluate it and return the result
           list. An empty list always indicates that the component ran but
           had nothing to format- we return None if the node is ignored.

           Text nodes return a list with only their data. Newline characters
           in a text node are converted to spaces, so newlines and tabs can be used
           to prettify the XML without it affecting the final output- this combined with
           the redundant whitespace elimination in joinComponents() gives HTML-like
           semantics. Literal linebreaks can be obtained with the <br/> component.

           Elements invoke the corresponding component_* handler, which must
           return a sequence.
           """
        if node.nodeType == node.TEXT_NODE:
            return [node.data.replace("\n", " ")]

        elif node.nodeType == node.ELEMENT_NODE:
            f = getattr(self, "component_" + node.nodeName, None)
            if f:
                return f(node, args)
            else:
                raise XML.XMLValidityError(
                    "Unknown component name in %s: %r" %
                    (self.__class__.__name__, node.nodeName))
示例#30
0
 def _reportUnusedParameters(self, unused):
     if unused:
         l = ['"%s"' % el for el in unused]
         l.sort()
         raise XML.XMLValidityError(
             "Some formatter parameters were not recognized: " +
             ", ".join(l))
示例#31
0
    def element_return(self, element):
        """Set the current result and exit the ruleset immediately"""
        if element.hasAttributeNS(None, 'path'):
            path = element.getAttributeNS(None, 'path')
            xp = XML.XPath(XML.pathShortcuts.get(path, path))

            # Define a rulesetReturn function that returns the value of the XPath
            def rulesetReturn(msg):
                nodes = xp.queryObject(msg)
                if nodes:
                    self.result = XML.allText(nodes[0]).strip()
                else:
                    self.result = None
                raise RulesetReturnException()

            return rulesetReturn

        else:
            # No path, define a rulesetReturn function that returns this element's string value
            def rulesetReturn(msg):
                self.result = XML.shallowText(element)
                if not self.result:
                    self.result = None
                raise RulesetReturnException()

            return rulesetReturn
示例#32
0
def update_login_token():
    xml_string = Data.Load(LOGIN_QUEUE_TOKEN_NAME)
    tree = XML.ElementFromString(xml_string)
    Dict['expiration'] = tree.findtext('token-expires-at')
    Dict['usertoken'] = tree.findtext('token')
    Dict['planid'] = tree.findtext('plid')
    Dict['userid'] = tree.findtext('id')
示例#33
0
 def ToXML(self):
     """
   Serialize the item as XML.
   
   @return: string
 """
     return XML.ElementToString(self.root)
示例#34
0
 def rulesetReturn(msg):
     nodes = xp.queryObject(msg)
     if nodes:
         self.result = XML.allText(nodes[0]).strip()
     else:
         self.result = None
     raise RulesetReturnException()
示例#35
0
    def element_ruleset(self, element):
        """<ruleset> for the most part works just like <rule>, but since
           it's the root node it's responsible for initializing and returning
           the ruleset's result.
           """
        if element is not self.xml.documentElement:
            raise XML.XMLValidityError(
                "The <ruleset> element must only occur at the document " +
                "root. Use <rule> to create nested rules.")

        # Go ahead and store the URI attribute if we have one.
        # If not, this will be None.
        self.uri = element.getAttributeNS(None, 'uri') or None

        # URIs are always encoded if necessary, since just about everywhere we'd need to
        # use a URI we can't support Unicode yet. Specific examples are IRC servers/channels
        # and as dict keys in an XML-RPC response.
        if type(self.uri) is unicode:
            self.uri = self.uri.encode()

        # Create a function to evaluate this element as a <rule> would be evaluated
        ruleFunc = self.element_rule(element)

        # Now wrap this function in one that performs our initialization and such
        def rulesetRoot(msg):
            self.result = None
            try:
                ruleFunc(msg)
            except RulesetReturnException:
                pass
            result = self.result
            del self.result
            return result

        return rulesetRoot
示例#36
0
文件: Project1.py 项目: zexe/ma
def main():


    #html stuff:
    #-------------------------------------------------------------------
    #HTML.html_stuff('./html_input/index_part1.txt', './html_input/index_part2.txt', './html_output/index.html')
    #-------------------------------------------------------------------


    #convert groundtruth from 0.5secs intervall (manual input) to usable intervals (1,2,3,4,5secs)
    #data = FileIO.read_groundtruth('groundtruth_1001_05secs.csv')
    #FileIO.convert_groundtruth(data, 'groundtruth_1001_2secs.csv', 4)


    #xml stuff:
    #-------------------------------------------------------------------
    XML.create_XML('caffe_output_2secs_p_c_3.txt', 'groundtruth_1001_2secs.csv', '1001_77_2secs_p_c.csv')
示例#37
0
 def matches(self, msg):
     match = self.projectPath.queryObject(msg)
     if match:
         for node in match:
             project = XML.shallowText(node)
             if (project.strip().lower() in self.projects):
                 return True
     return False
示例#38
0
 def element_like(self, element):
     """Compare a given variable to the element's content using SQL's 'LIKE' operator,
        not including leading and trailing whitespace. This is case-insensitive, and includes
        the '%' wildcard which may be placed at the beginning or end of the string.
        """
     return "(%s LIKE %s)" % (
         self.varLookup(element.getAttributeNS(None, 'var')),
         quote(XML.shallowText(element).strip(), 'varchar'))
示例#39
0
def Cloth_Rigger_ReadXML(prop, filename=None):
    if not filename:
        filename = Cloth_Rigger_GetXMLFile(prop)

    cloth = prop.Parent3DObject
    cloth_op = cloth.ActivePrimitive.ConstructionHistory.Find('syCloth')
    if cloth_op:
        XML.ReadSyflexXMLPreset(filename, cloth_op)
示例#40
0
文件: Ruleset.py 项目: Kays/cia-vc
 def matches(self, msg):
     match = self.projectPath.queryObject(msg)
     if match:
         for node in match:
             project = XML.shallowText(node)
             if (project.strip().lower() in self.projects):
                 return True
     return False
示例#41
0
def loadGames():
    try:
        f = open("./xml/packlist.chess", "r")
    except FileNotFoundError:
        return

    saves = f.readlines()

    for save in saves:
        save = save.rstrip()
        gameID = save[:save.find(":")]
        lastNum = save[save.find(":")+1:]

        g = Game()
        g.id = int(gameID)
        xmlPath = "./xml/"+gameID+"/"+lastNum+".xml"

        try:
            m = XML.parse_meta(xmlPath)
            g.password = m["password"]

            g.board.whoseTurn = WHITE if m["turn"] == "white" else BLACK
            g.board.xSize = int(m["sizeX"])
            g.board.ySize = int(m["sizeY"])
            g.movesmade = int(m["movesmade"])
            g.board.setup_fields()
        except KeyError:
            continue

        figures = XML.parse_figures(xmlPath)
        for figure in figures:
            g.board.getFieldByCords(figure.posx, figure.posy).figure = figure

        g.board.postMoveUpdate()

        if g.password is None:
            g.password = ""

        if g.movesmade > 3:
            glist.append(g)
            print("Loaded Game:", g.id)
        else:
            removeLine("./xml/packlist.chess", str(g.id)+":"+str(g.movesmade)+"\n")
            rmdir("./xml/"+str(g.id))
            print("Removed SaveGame:", g.id)
示例#42
0
 def __init__(self, tag="MediaItem"):
     """
   Creates a custom MediaItem with the given tag
   
   @param tag: The tag for the MediaItem
   @type tag: string
   @return: MediaItem
 """
     self.root = XML.Element(tag)
示例#43
0
def Set(key, value):
    """
    Sets the preference for the given key to the given value.
    
    @param key: The key of the preference
    @type key: string
    @param value: The value to set
    @type value: string
  """
    el = Plugin.__prefs.find(key)
    if el is None:
        el = XML.Element(key)
        el.text = value
        Plugin.__prefs.append(el)
    else:
        el.text = value
    XML.ElementToFile(Plugin.__prefs, Plugin.__prefsPath)
    Log.Add("(Framework) Set preference '%s' to '%s'", (key, value))
示例#44
0
def Get(key):
    """
    Gets the preference value for the given key.
    
    @param key: The key of the preference
    @type key: string
    @return: key
  """
    return XML.TextFromElement(Plugin.__prefs.find(key))
示例#45
0
 def _insertRuleset(self, none, result, ruleset):
     """Callback used by store() to insert a new or modified ruleset into the SQL database"""
     import Database
     d = Database.pool.runOperation(
         "INSERT INTO rulesets (uri, xml) values(%s, %s)" %
         (Database.quote(ruleset.uri, 'text'),
          Database.quote(XML.toString(ruleset.xml), 'text')))
     d.addCallback(result.callback)
     d.addErrback(result.errback)
示例#46
0
def run():
    dossiers = os.listdir('./../')

    if 'zip' not in dossiers:
        os.mkdir('./../zip')
    if 'xml' not in dossiers:
        os.mkdir('./../xml')
    if 'wordOut' not in dossiers:
        os.mkdir('./../wordOut')

    # Fichier source à modifier à choisir.
    file = raw_input("entrer le nom du fichier word sans l'extension :\n>>>")
    # Changement de l'extension du fichier pour une archive.
    ext.changeExt(file, 'docx', 'zip', './../word/', './../zip/')
    print('zipage done')

    # Extraction du fichier 'document.xml' de l'archive.
    zip.extract('./../zip/' + file + '.zip')
    print('extract done')

    # Mets en forme le document xml pour créer un arbre propre.
    xml.xml('./../word/document.xml', file)
    print('xml done')

    # Extrait tout les fichiers de l'archive pour modifier les fichiers html
    zip.extractAll('./../zip/' + file + '.zip')
    print('extractAll done')

    # Suppression des espaces des fichiers HTML
    # html.run()
    # print('rewrite html done')

    # zip.addFile(file)
    # print('create new zip done')

    # Création de la noouvelle archive et ajout des fichiers modifiés
    zip.zipdir('./../tmp', file)
    ext.changeExt(file, 'zip', 'docx', './../wordOut/', './../wordOut/')

    rmtree('./../zip')
    rmtree('./../xml')
    # rmtree('./../tmp')
    os.remove('./../wordOut/' + file + '.zip')
示例#47
0
文件: Ruleset.py 项目: Kays/cia-vc
 def caps_store(self, path, xml):
     """Generate a list of acceptable capabilities to grant access to 'store'.
        In addition to the usual ones, allow ('ruleset.uri', x) where x is the
        ruleset's URI.
        """
     if (xml.startswith('[')):
         uri = xml.split('\n')[0][2:]
     else:
         uri = XML.parseString(xml).documentElement.getAttributeNS(None, 'uri')
     return self.makeDefaultCaps(path) + [('ruleset.uri', uri)]
示例#48
0
    def postprocessMessage(self, xml):
        """Gets a chance to modify all XML messages before they're loaded
           and dispatched to the Hub. This does the following:
             - If there is no <generator> at all, adds a generic one
             - Removes any <mailHeaders> tag that may already exist in <generator>
             - Adds a correct <mailHeaders> tag to the <generator>
           """
        # Create the <generator> tag if it doesn't exist
        if not XML.dig(xml, "message", "generator"):
            xml.documentElement.appendChild(self.getLocalGenerator(xml))
        generator = XML.dig(xml, "message", "generator")

        # Delete an existing <mailHeaders>
        for child in list(XML.getChildElements(generator)):
            if child.nodeName == "mailHeaders":
                generator.removeChild(child)

        # Add a new <mailHeaders>
        generator.appendChild(self.getXMLMailHeaders(xml))
        return xml
示例#49
0
    def command_Announce(self, project):
        """Old-style announcements: Announce <project> in the subject line.
           The body of the email contained the message's text, marked up
           with {color} tags but with no metadata.
           """
        xml = XML.createRootNode()

        # Convert the given project name to a <project> tag inside <source>,
        # after filtering it a bit... in the old CIA project names and IRC channel
        # names weren't particularly distinct, so preceeding "#" characters on
        # projects were ignored. We preserve this behaviour.
        if project[0] == "#":
            project = project[1:]
        XML.buryValue(xml, project, "message", "source", "project")

        # Since old-style commits didn't have any metadata, the best we can do
        # is to represent the log in a <colorText> element
        colorText = ColorTextParser().parse(self.message.get_payload()).documentElement
        XML.bury(xml, "message", "body").appendChild(xml.importNode(colorText, True))
        return xml
示例#50
0
文件: Message.py 项目: SkyFire/cia-vc
    def format(self, args):
        """The formatter entry point. This just finds the current component
           tree and invokes walkComponents and joinComponents on it.
           """
        # Parse the default component tree, caching it per-class
        if self.__class__._defaultTreeOwner is not self.__class__.defaultComponentTree:
            self.__class__._defaultTreeOwner = self.__class__.defaultComponentTree
            self.__class__._cachedDefaultTree = XML.parseString(self.__class__.defaultComponentTree).documentElement

        # This will use the default component tree if it hasn't been overridden in this instance
        tree = self.componentTree or self.__class__._cachedDefaultTree
        return self.joinComponents(self.walkComponents(tree.childNodes, args))
示例#51
0
文件: Message.py 项目: SkyFire/cia-vc
    def component_text(self, element, args):
        """This is a generic version of textComponent, in which 'path' can
           be specified by users. Any textComponent can be rewritten as a
           <text> component.
           """
        path = element.getAttributeNS(None, 'path')
        if not path:
            raise XML.XMLValidityError("The 'path' attribute on <text> is required.")
        xp = XML.XPath(XML.pathShortcuts.get(path, path))

        nodes = xp.queryObject(args.message)
        if nodes:
            return [XML.shallowText(nodes[0])]
        else:
            return [MarkAsHidden()]
示例#52
0
文件: Message.py 项目: SkyFire/cia-vc
    def pathMatchTag(self, element, function, textExtractor=XML.shallowText):
        """Implements the logic common to all tags that test the text matched by
           an XPath against the text inside our element. The given function is used
           to determine if the text matches. This implements the properties common to
           several elements:

             - The caseSensitive attribute defaults to 1, but can be set to zero
               to force both strings to lowercase.

             - Each XPath match is tested separately, with 'or' semantics:
               if any of the XPath matches cause the provided function to match,
               this returns True

             - If there are no XPath matches, returns False
           """
        path = element.getAttributeNS(None, 'path')
        xp = XML.XPath(XML.pathShortcuts.get(path, path))

        # Are we doing a case sensitive match? Default is no.
        caseSensitive = element.getAttributeNS(None, 'caseSensitive')
        if caseSensitive:
            caseSensitive = int(caseSensitive)
        else:
            caseSensitive = 0

        text = XML.shallowText(element).strip()
        if not caseSensitive:
            text = text.lower()

        def filterMatch(msg):
            # Use queryobject then str() so that matched
            # nodes without any text still give us at least
            # the empty string. This is important so that <find>
            # with an empty search string can be used to test
            # for the existence of an XPath match.
            nodes = xp.queryObject(msg)
            if nodes:
                matchStrings = map(textExtractor, nodes)

                # Any of the XPath matches can make our match true
                for matchString in matchStrings:
                    matchString = matchString.strip()
                    if not caseSensitive:
                        matchString = matchString.lower()
                    if function(matchString, text):
                        return True
            return False
        return filterMatch
示例#53
0
    def __init__(self, src="", root=None):

        self.ckin = 0
        self._owner = 0
        self.verbose = 1

        # get the 'phase' element
        s = XML.find_XML(src=src, root=root, name="phase")

        # get the equation of state model
        ThermoPhase.__init__(self, xml_phase=s)

        # get the kinetics model
        Kinetics.__init__(self, xml_phase=s, phases=[self])

        SolidTransport.__init__(self, phase=self)
示例#54
0
文件: Ruleset.py 项目: Kays/cia-vc
    def dbStore(self, ruleset=None):
        """Write all rulesets to disk in one big XML file"""
        doc = XML.parseString("<rulesets>\n"
                              "<!--\n"
                              "This is a ruleset storage for CIA. It tells the CIA server\n"
                              "how to deliver messages. Don't edit it by hand while the server\n"
                              "is running, use tools/ruleset_editor.py\n"
                              "-->\n"
                              "\n"
                              "</rulesets>")
        root = doc.documentElement
        for ruleset in self.flatten():
            root.appendChild(XML.Domlette.ConvertDocument(ruleset.xml).documentElement)
            root.appendChild(doc.createTextNode("\n\n"))

        f = open(self.path, "w")
        XML.Domlette.Print(doc, f)
        f.write("\n")
示例#55
0
文件: Message.py 项目: SkyFire/cia-vc
    def loadParametersFrom(self, xml, unused=None):
        """This is given a <formatter> element possibly containing
           extra parameters for the formatter to process and store.
           Any problems should be signalled with an XML.XMLValidityError.

           By default, this tries to find a param_* handler for each
           element it comes across.

           Returns a set object, containing the names of all unused
           parameters. This allows callers, during validation, to look
           for misspelled or otherwise unused elements.
           """
        unused = set()
        for tag in XML.getChildElements(xml):
            f = getattr(self, 'param_'+tag.nodeName, None)
            if f:
                f(tag)
            else:
                unused.add(tag.nodeName)
        return unused
示例#56
0
	def test_xmlSolve_multipleChildren(self):
		r = StringIO("<THU><Team><ACRush></ACRush><Jelly></Jelly><Cooly></Cooly></Team><JiaJia><Team><Ahyangyi></Ahyangyi><Dragon></Dragon><Cooly><Amber></Amber></Cooly></Team></JiaJia></THU><Team><Cooly></Cooly><Jelly></Jelly></Team>")
		w = StringIO()
		XML.xmlSolve(r,w)
		self.assertTrue(w.getvalue() == "1\n2\n")
示例#57
0
	def test_getPattern(self):
		s = "<xml><THU>\n\t<Team>\n\t\t<ACRush></ACRush>\n\t\t<Jelly></Jelly>\n\t\t<Cooly></Cooly>\n\t</Team>\n\t<JiaJia>\n\t\t<Team>\n\t\t\t<Ahyangyi></Ahyangyi>\n\t\t\t<Dragon></Dragon>\n\t\t\t<Cooly><Amber></Amber></Cooly>\n\t\t</Team>\n\t</JiaJia>\n</THU>\n<Team><Cooly></Cooly></Team>\n</xml>"
		a = fromstring(s)
		pattern = XML.getPattern(a)
		self.assertTrue(type(pattern) is Element)
		self.assertTrue(pattern.tag == "Team")
def main():
    XML.xmlSolve(sys.stdin, sys.stdout)
示例#59
0
	print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
	sys.exit()

class Save(Thread):
	def __init__(self, xml):
		Thread.__init__(self)
		self.xml = xml
	
	def run(self):
		while True:
			time.sleep(300)
			self.xml.write()
			print 'Saved'

# get XML document
xml = XML('/home/pi/Programmes/Python/Projet/Preferences.xml')

# instanciate shift and sooperlooper
shift = Shift()
sooper = SooperLooper()

# animate LEDs
shift.loading('b')

# 
pedals = []

for i in range(0, 5):
	pedal = "/Root/Pedal_" + str(i) + "/"

	pedals.append(Pedal(i, 
示例#60
0
	def test_xmlSolve_noAnswer(self):
		r = StringIO("<THU><Team><ACRush></ACRush><Jelly></Jelly><Cooly></Cooly></Team><JiaJia><Team><Ahyangyi></Ahyangyi><Dragon></Dragon><Cooly><Amber></Amber></Cooly></Team></JiaJia></THU><Jesse></Jesse>")
		w = StringIO()
		XML.xmlSolve(r,w)
		self.assertTrue(w.getvalue() == "0\n")