Пример #1
0
Файл: rec.py Проект: v/school
def next_token():
    global input_string
    global token

    if not input_string:
        token = MutableString('\0')
        return str(token)

    token = MutableString(input_string[0])
    input_string = input_string[1:]
Пример #2
0
 def execute(cls, *args, **kwargs):
     if len(args) == 1 and args[0] == "long":
         temp = MutableString()
         for line in subprocess.check_output(["fortune", "-l"]).split("\n"):
             temp += str(line)
             temp += ' '
         kwargs['client'].msg(kwargs['user'], temp)
     else:
         temp = MutableString()
         for line in subprocess.check_output("fortune").split("\n"):
             temp += str(line)
             temp += ' '
         return temp
Пример #3
0
def reverse_version_mutable_string(string_input):
    new_str = MutableString()
    for i in range(len(string_input) - 1, -1, -1):
        # new_str = "%s%s" % (new_str, string_input[i])
        new_str += string_input[i]

    return new_str
Пример #4
0
 def parseMessageFromBot(self, message, mesFrom):
     jid = mesFrom
     mesText = message.body.strip()
     if mesFrom.lower() == JUICK_BOT.lower() or mesFrom.lower(
     ) == PSTO_BOT.lower() or mesFrom.lower() != PSTO_ANOTHER_BOT.lower(
     ):  # or mesFrom.lower() == BNW_BOT.lower() or mesFrom.lower() == NYA_BOT.lower() :
         # Send it to user.
         mesTo = message.to.split('/')[0]
         user = User.all().filter('local', mesTo.lower().lower()).get()
         if user is None:
             logging.debug("We've got unknown message: " + mesFrom + "->" +
                           mesTo + ">" + mesText)
         else:
             from UserString import MutableString
             mesFooter = MutableString()
             mesFooter += "\nTo reply to this message, start your message with "
             if mesFrom.lower() == JUICK_BOT.lower():
                 mesFooter += "-j"
             else:
                 mesFooter += "-p"
             mesFooter += " modificator.\nIf you fail to do so, your message will be sent to both juick and psto."
             status = xmpp.send_message(
                 user.jid, (mesFrom + "> " + mesText + mesFooter).encode(
                     'utf-8', 'xmlcharrefreplace'))
     else:
         # Logging.
         logging.debug("We've got unknown message: " + mesFrom + "> " +
                       mesText)
Пример #5
0
def method2():
	from UserString import MutableString
	out_str = MutableString()
	for num in xrange(loop_count):
		out_str += `num`
	ps_stats()
	return out_str
Пример #6
0
    def __init__(self):

        # save the linetype
        self.tokentype = "CombinedText"

        # use MutableString for efficiency
        self._text = MutableString()
Пример #7
0
def eliminarIndiceImpar(cadena):
	cad = MutableString(cadena)
	for i in range(len(cadena)):
		if i%2!=0:
			cad[i]=''

	return cad
Пример #8
0
    def toString(self):
        result = MutableString()

        result.append("Process name: %s " % self.myCounterProcess)
        result.append("Counter path: %s " % self.myCounterPath)
        result.append("Counter name: %s " % self.myCounterName)
        result.append("Counter name: %s " % self.myCounterSamplingName)
        result.append("Sampling rate: %s " % self.mySamplingRate)
        result.append("Counter Type: %s " % self.myCounterType)
        result.append("Counter Units: %s " % self.myMeasuredUnits)
        result.append("Counter present per second is: %s " %
                      str(self.myPresentCounterPerSecond))
        result.append("Counter Id: %d " % self.myCounterId)
        result.append("Is rate? %s" % str(self.myIsRate))
        result.append("Counter short description: %s " %
                      self.myCounterShortDescriptionString)
        result.append("Counter short description override flag: %s " %
                      str(self.myCounterDescriptionIsOverride))
        result.append("Counter value variable type: %s " % self.myVariableType)
        result.append("Meta-Counter arithmetic expression: %s " %
                      self.myMetaCounterExpression)
        result.append("Communication method: %s " % self.myCommMethod)
        result.append("RRD min heartbeat: %s " % self.myMinHeartbeat)

        for arch in self.myArchaives:
            result.append(arch.toString())

        for prop in self.myProperties:
            result.append(prop.toString())

        return result.data
Пример #9
0
def trackGARequests(path, remoteAddr, referer=''):
    logging.debug('trackRSSRequests: calling GA GIF service')

    var_utmac = AppConfig.googleAnalyticsKey  # enter the new urchin code
    var_utmhn = AppConfig.appDomain  # enter your domain
    var_utmn = str(random.randint(1000000000, 9999999999))  # random request number
    var_cookie = str(random.randint(10000000, 99999999))  # random cookie number
    var_random = str(random.randint(1000000000, 2147483647))  # number under 2147483647
    var_today = str(int(time.time()))  # today
    var_referer = referer  # referer url
    var_uservar = '-'  # enter your own user defined variable
    var_utmp = '%s/%s' % (path, remoteAddr)  # this example adds a fake page request to the (fake) rss directory (the viewer IP to check for absolute unique RSS readers)
    #build URL
    urchinUrl = MutableString()
    urchinUrl = 'http://www.google-analytics.com/__utm.gif?utmwv=1&utmn=' + var_utmn
    urchinUrl += '&utmsr=-&utmsc=-&utmul=-&utmje=0&utmfl=-&utmdt=-&utmhn='
    urchinUrl += var_utmhn + '&utmr=' + var_referer + '&utmp=' + var_utmp
    urchinUrl += '&utmac=' + var_utmac + '&utmcc=__utma%3D' + var_cookie
    urchinUrl += '.' + var_random + '.' + var_today + '.' + var_today + '.'
    urchinUrl += var_today + '.2%3B%2B__utmb%3D' + var_cookie
    urchinUrl += '%3B%2B__utmc%3D' + var_cookie + '%3B%2B__utmz%3D' + var_cookie
    urchinUrl += '.' + var_today
    urchinUrl += '.2.2.utmccn%3D(direct)%7Cutmcsr%3D(direct)%7Cutmcmd%3D(none)%3B%2B__utmv%3D'
    urchinUrl += var_cookie + '.' + var_uservar + '%3B'

    #async request to GA's GIF service
    rpcGA = None
    try:
        rpcGA = urlfetch.create_rpc()
        urlfetch.make_fetch_call(rpcGA, urchinUrl)
    except Exception, exT:
        logging.error('trackRSSRequests: Errors calling GA GIF service : %s' % exT)
Пример #10
0
    def test_parse_format_changed(self):
        from UserString import MutableString
        header = MutableString('lo')
        format = [('field', 2)]
        test_parser = make_packet_parser(header, format)

        self.do_parse_test(
            test_parser,
            ['lo\x00\x00'],
            [{
                'field': '\x00\x00'
            }],
            ['6C6F 0000'],
        )

        format += [('field2', 2)]
        header.append('l')

        self.do_parse_test(
            test_parser,
            ['lo\x00\x00'],
            [{
                'field': '\x00\x00'
            }],
            ['6C6F 0000'],
        )
Пример #11
0
 def toString(self):
     result = MutableString()
     result.append("Archaive type: %s" % self.myArchaiveType)
     result.append("Archaive errors allowed: %s" % self.myErrorsAllowed)
     result.append("Archaive consolidation span: %d" %
                   self.myConsolidationSpan)
     result.append("Archaive rows to keep: %d" % self.myRowsToKeep)
     return result.data
Пример #12
0
def getNotes(fileUrl):
    note = MutableString()

    note += fileUrl

    logging.debug('note={0}'.format(note))

    return str(note)
Пример #13
0
    def getText(self):

        # use MutableString for efficiency
        comedy_text = MutableString()

        for line in self.lines:
            comedy_text += line.getText() + ' '

        return str(comedy_text)
Пример #14
0
    def getText(self):

        # use MutableString for efficiency
        comedy_text = MutableString()

        for token in self.tokens:
            comedy_text += token.getText()

        return str(comedy_text)
Пример #15
0
 def toString(self):
     result = MutableString()
     result.append("Property name: %s" % self.myName)
     result.append("Property variable type: %s" % self.myVariableType)
     #Get the correct format according to the variable type
     frmt = "Property value: %s" % VariableTypes.FORMAT_BY_NAMES[
         self.myVariableType]
     result.append(frmt % self.myValue)
     return result.data
Пример #16
0
def run_02():
    """# 방법2: MutableString 이용한 방법
    - DEPRECATED : UserString은 더이상 지원않는 클래스
    """
    from UserString import MutableString
    out_str = MutableString()
    for num in range(10):
        out_str += 'num--'
    return out_str
Пример #17
0
    def _getTags(self, results, file):
        tags = MutableString()
        
        # Digital Signature
        # isProbablyPacked
        try:
            if results["Info"] and results["Info"]["file"]:
                tags += results["Info"]["file"]["digitalSignature"]
                tags += ", "
                tags += "isProbablyPacked: " + str(results["Info"]["file"]["isProbablyPacked"])
                tags += ", "
        except KeyError:
            # Key is not present
            pass

        # URL
        if results["Info"] and results["Info"]["url"]:
            tags += results["Info"]["url"]["hostname"]
            tags += ", "
        
        # Packer Ident
        if results.get("PEID", None):
            tags += results["PEID"][0]
            tags += ", "
    
        # VirusTotal
        try:
            if results["VirusTotal"] and results["VirusTotal"]["file"] and results["VirusTotal"]["file"]["positives"]:
                tags += "VirusTotal: "
                tags += results["VirusTotal"]["file"]["positives"]
                tags += "/"
                tags += results["VirusTotal"]["file"]["total"]
                tags += ", "
        except KeyError:
            # Key is not present
            pass
        
        # CountryCode
        try:
            if results["InetSourceAnalysis"] and results["InetSourceAnalysis"]["URLVoid"]:
                tags += results["InetSourceAnalysis"]["URLVoid"]["urlResult"][1]["CountryCode"]
                tags += ", "
        except KeyError:
            # Key is not present
            pass
        
        # FileType
        tags += file.get_type()
        tags += ", "
                
        tags += "ragpicker"
        
        #TODO: Unpacked Tag einfuegen!!! 
        
        log.info("tags=" + tags)
        
        return str(tags)
Пример #18
0
def multiplyChar(char, n):
    retVal = MutableString()
    I = 0
    if n == 0:
        return ""
    elif n < 0:
        return char
    for i in range(n):
        retVal += char
    return retVal
Пример #19
0
    def parseParameters(self, vardict):

        # use MutableString for efficiency
        parameters = MutableString()

        # build a string with html tags: <key>value</key>
        for key, value in vardict.items():
            parameters += "\n            <%s>%s</%s>" % (key, value, key)

        return str(parameters)
Пример #20
0
def check_for_urls_in_files(app, reporter):
    """Check that URLs do not include redirect or requests from external web
    sites.
    """
    # It's a little verbose but with the explicit-ness comes
    # References
    # http://tools.ietf.org/html/rfc3986
    # http://stackoverflow.com/questions/4669692/valid-characters-for-directory-part-of-a-url-for-short-links
    url_regex_pattern = ("(\w*://)+"                  # Captures protocol
                         "([\w\d\-]+\.[\w\d\-\.]+)+"  # Captures hostname
                         "(:\d*)?"                    # Captures port
                         "(\/[^\s\?]*)?"              # Captures path
                         "(\?[^\s]*)?")               # Capture query string
    url_regex_object = re.compile(url_regex_pattern,
                                  re.IGNORECASE)

    excluded_types = [".csv", ".gif", ".jpeg", ".jpg", ".md", ".org", ".pdf",
                      ".png", ".svg", ".txt"]
    excluded_directories = ["samples"]

    url_matches = app.search_for_pattern(url_regex_pattern,
                                         excluded_dirs=excluded_directories,
                                         excluded_types=excluded_types)

    if url_matches:
        # {url_pattern: {filename: [lineno_list]}}
        result_dict = {}

        for (fileref_output, match) in url_matches:
            url_match = match.group()
            filename, line_number = fileref_output.rsplit(":", 1)

            if url_match not in result_dict:
                result_dict[url_match] = {}
            if filename not in result_dict[url_match]:
                result_dict[url_match][filename] = []
            result_dict[url_match][filename].append(str(line_number))

            reporter_output = ("A file was detected that contains that a url."
                               " Match: {}"
                               " File: {}"
                               " Line: {}"
                               ).format(url_match,
                                        filename,
                                        line_number)
            reporter.manual_check(reporter_output, filename, line_number)

        # create some extra manual checks in order to see results in a more convenient way
        for (url_match, file_dict) in result_dict.items():
            reporter_output = MutableString()
            reporter_output.append("A url {} was detected in the following files".format(url_match))
            for (file_name, lineno_list) in file_dict.items():
                reporter_output.append(", (File: {}, Linenolist: [{}])".format(file_name, ', '.join(lineno_list)))
            # don't need filename and line_number here, since it is an aggregated result
            reporter.manual_check(str(reporter_output))
Пример #21
0
def code(question_id, question_title, question_content, question_snippet):
    dr = re.compile(r'<[^>]+>', re.S)
    question_content = dr.sub('', question_content)
    file_name = rename(question_id, question_title.encode('utf-8'))
    sb = MutableString()
    sb.append(constant.JAVA_FILE_PACKAGE)
    sb.append("\n")
    sb.append("/**\n")
    sb.append(question_content
              .replace('&quot;', '')
              .replace('*/', '')
              )
    sb.append("**/\n")
    # pattern = re.compile(r'(class )(.+)( {)')
    # question_snippet = re.sub(pattern, 'class '+file_name+' {', question_snippet)
    match_obj = re.match(r'(class )(.+)( {)', question_snippet, re.M | re.I)
    class_name = ''
    if match_obj:
        class_name = match_obj.group(2)
    if question_snippet.find('class') < 0:
        sb.append('class ')
        sb.append(str(file_name))
        sb.append(' {\n')
        sb.append('//')
        sb.append(question_snippet)
        sb.append('\n')
        sb.append('}')
    else:
        sb.append(question_snippet
                  .replace('Solution', str(file_name))
                  .replace(class_name, str(file_name)))
    file_path = constant.JAVA_FILE_PATH
    if not os.path.exists(file_path):
        print 'folder ', file_path, 'not exist, makedir~'
        os.makedirs(file_path)
    temp = str(file_name+'.java')
    if file_exist(file_path, temp):
        print(file_name, 'already exist')
        return
    with open(file_path + temp, 'wb') as file:
        file.write(str(sb))


# def creator():
#     questions = question_template.questions(constant.QUESTION_LIMIT)
#     for question in questions:
#         code(question[0], question[1], question[4], question[5])


#
# schedule.every(10).second.do(creator())
#
# while True:
#     schedule.run_pending()
Пример #22
0
 def decimal_to_number(cls, number, base):
     converted_num = MutableString()
     is_neg = number < 0
     number = abs(number)
     while number > 0:
         digit = number % base
         converted_num = cls.number_to_alphabet_map.get(
             digit, str(digit)) + converted_num
         number /= base
     if not converted_num:
         return "0"
     return ("-" if is_neg else "") + converted_num
Пример #23
0
def getTags(fileUrl):
    tags = MutableString()

    tags += time.strftime(baseConfig.dateFormat)
    tags += ', '
    tags += urlparse(fileUrl).hostname
    tags += ', '
    tags += 'ph0neutria'

    logging.debug('tags={0}'.format(tags))

    return str(tags)
Пример #24
0
    def getText(self):

        # use MutableString for efficiency
        comedy_text = MutableString()

        # check if the reset tag is needed
        tagAdded = False

        # get the values
        speed = self.speed
        shape = self.shape
        volume = self.volume
        voice = self.voice

        # if it is a punch line
        # set the punch line defauls but not override
        if self.punch:

            if speed is None:
                speed = punch_default_speed

            if shape is None:
                shape = punch_default_shape

            if volume is None:
                volume = punch_default_volume

        # check for voice tags (if not None or default)
        if speed and speed != 100:
            comedy_text += '\\rspd=' + str(speed) + '\\'
            tagAdded = True

        if shape and shape != 100:
            comedy_text += '\\vct=' + str(shape) + '\\'
            tagAdded = True

        if volume and volume != 100:
            comedy_text += '\\vol=' + str(volume) + '\\'
            tagAdded = True

        if voice:
            comedy_text += '\\vce=speaker=' + voice + '\\'
            tagAdded = True

        # add the text
        comedy_text += self.text

        # add the reset at the end
        if tagAdded:
            comedy_text += '\\rst\\'

        return str(comedy_text)
Пример #25
0
def main():
    b1 = 26
    if len(sys.argv) == 2:
        pattern_to_decode = sys.argv[1]
    else:
        number_len = random.randint(1, 6)
        pattern_to_decode = MutableString()
        for _ in range(number_len):
            digit = random.randint(0, 26)
            pattern_to_decode += SpreadsheetEncodingDecoder.number_to_alphabet_map.get(
                digit, str(digit))
    decoded_pattern = SpreadsheetEncodingDecoder.number_to_decimal(
        str(pattern_to_decode), b1)
    print('n = %s decoded n = %s' % (pattern_to_decode, decoded_pattern))
Пример #26
0
        def load(durl, greet):
            def remove_tags(text):
                text = TAG_RE.sub('', text)
                text = re.sub("\n", "", text)
                text = re.sub("\"", "\\\"", text)
                return "".join(filter(lambda x: ord(x) < 128, text))

            content = MutableString()
            content = []
            opener = urllib2.build_opener()
            opener.addheaders = [('User-agent', 'Mozilla/24.0')]
            MEMCACHE_GREETINGS = greet
            data = cache.get(MEMCACHE_GREETINGS)
            time = 1800
            if data is None:
                file = urllib2.urlopen(durl)
                data = file.read()
                file.close()
                cache.add(MEMCACHE_GREETINGS, data, time)
            doc = ET.fromstring(data)
            #                logging.debug("value of  16 my var is %s", str(data))
            gg = doc.findall('channel/item')
            #                logging.debug("value of  1 my var is %s", str(gg))
            for node in gg:
                title = node.find('./title').text
                description = node.find('./description').text
                url = node.find('./link').text
                info = {}
                info['title'] = remove_tags(title)
                info['description'] = remove_tags(description)
                info['url'] = url
                #                    submitterobj = User.objects.get(username='******')
                #                    submitter = submitterobj.username
                info['submitter'] = User.objects.filter(
                    username='******')[0].id
                info['linksource'] = urlparse(url).netloc
                #                    info['submitter'] = User.objects.filter(is_superuser=1)[1].id
                info['votes'] = randrange(20)
                logging.debug(
                    "value of  user my var is %s",
                    str(
                        User.objects.filter(
                            username='******')[0].get_username()))
                #                    info[title] = Wikifetch(title, description, url)

                content.append(info)
#                   logging.debug("value of  1 my var is %s", str(title))
#                    logging.debug("value of  2 my var is %s", str(link))
            return content
Пример #27
0
def getParagraphCommentSiblings(node):
	nodeText = MutableString()
	if (node):
		#get first paragraph
		nodeText = str(node.font)
		nextSib = node.nextSibling
		if (nextSib and "<p>" in str(nextSib)):
			while (nextSib and "<p>" in str(nextSib)):
				tmpStr = str(nextSib)
				if (nodeText):
					nodeText += "__BR__%s" % tmpStr
				else:
					nodeText = tmpStr
				nextSib = nextSib.nextSibling
		return nodeText
Пример #28
0
    def getText(self):

        # use MutableString for efficiency
        comedy_text = MutableString()

        # intro
        comedy_text += self.comedy_intro.getText()

        # sequence
        for item in self.comedy_joke_sequence:
            comedy_text += item.getText()

        # outro
        comedy_text += self.comedy_outro.getText()

        return str(comedy_text)
Пример #29
0
    def __processConfigurationMonitor(self, words):
        #print "entered __processConfigurationMonitor"

        result = MutableString()

        result += '\t\t'
        result += '\n\t\t'

        #if words[1] == '0'
        if len(words[4]) == 0:
            result +=  CONSTANT_CONFIGURATION_MONITOR_HEADER + CONSTANT_NEWLINE + '\t\t\t' + \
                CONSTANT_MONTITOR_METADATA_EMPTY + CONSTANT_NEWLINE + '\t\t' + \
                CONSTANT_CONFIGURATION_MONITOR_FOOTER
        else:
            omittedMonitorFlag = CONSTANT_FALSE_STR
            if words[0].strip() in self.__omittedMonitors:
                omittedMonitorFlag = CONSTANT_TRUE_STR

            imageFile = ""
            if words[4].strip() == "scti_FlashFlood.xbm":
                imageFile = CONSTANT_FLASH_FLOOD
            elif words[4].strip() == "FOGbutton.xbm":
                imageFile = CONSTANT_FOG
            elif words[4].strip() == "SSbutton.xbm":
                imageFile = CONSTANT_SAFE_SEAS
            elif words[4].strip() == "SNOWbutton.xbm":
                imageFile = CONSTANT_SNOW
            elif words[4].strip() == "SCANbutton.xbm":
                imageFile = CONSTANT_SCAN
            #elif words[4].strip() == "scti_SPCguidance.xbm":
            #imageFile =

            result_0 = CONSTANT_CONFIGURATION_MONITOR_HEADER + CONSTANT_NEWLINE
            result_1 = '\t\t\t' + \
                CONSTANT_MONTITOR_METADATA % {"image_file": imageFile, \
                                              "omitted_flag": omittedMonitorFlag, "tcl_script": words[2].strip(), \
                                              "interval": words[3].strip()} + CONSTANT_NEWLINE #

            result_2 = '\t\t' + CONSTANT_CONFIGURATION_MONITOR_FOOTER
            result += result_0 + result_1 + result_2

        result += CONSTANT_NEWLINE

        #print "exiting __processConfigurationMonitor"

        return result
Пример #30
0
def main():
    if len(sys.argv) == 4:
        number_to_convert = sys.argv[1]
        b1 = int(sys.argv[2])
        b2 = int(sys.argv[3])
    else:
        number_len = random.randint(1, 16)
        b1 = random.randint(1, 15)
        b2 = random.randint(1, 15)
        number_to_convert = MutableString()
        for _ in range(number_len):
            digit = random.randint(0, b1 - 1)
            number_to_convert += BaseConverter.number_to_alphabet_map.get(
                digit, str(digit))
    converted_number = BaseConverter.decimal_to_number(
        BaseConverter.number_to_decimal(str(number_to_convert), b1), b2)
    print('n = %s, base = %d converted n = %s, base - %d' %
          (number_to_convert, b1, converted_number, b2))