예제 #1
0
def update_all_server_patch(zone_id,system_type):
	root_path = "/hf/hf"+zone_id;
	#关闭进程
	dirpath = "/hf/hf"+zone_id+"/bin"
	os.chdir(dirpath)
	os.system("sh "+"./stop_release.sh");
	os.chdir("/root");
	
	update_file_path = os.path.join(root_path,"server_patch")
	update_file_path = os.path.join(update_file_path,"new_server_patch_packet")
	patch_file_name = choose_server_patch(zone_id,system_type)	
	while(patch_file_name.strip()):
		print "this time patch_file_name "+patch_file_name
		start_copy(root_path,update_file_path,patch_file_name,system_type,zone_id)	
		
		update_patch_list_file = os.path.join(update_file_path, "update_patch_list")	
		handle_update_file = open(update_patch_list_file, 'w')
		list_split_underline = patch_file_name.split('_')  #server_full_2013-03-05-4897.tar.gz
		#print list_split_underline   ['server', 'full', '2013-03-05-4897.tar.gz']
		list_split_dot = list_split_underline[-1].split('.')
		#print list_split_dot					['2013-03-05-4897', 'tar', 'gz']	
		list_split_midline = list_split_dot[0].split('-')
		#patch_version = string.atol(list_split_midline[-1])
		patch_version = string.atol(list_split_midline[-1])+string.atol(list_split_midline[-2])*100000+string.atol(list_split_midline[1])*10000000+string.atol(list_split_midline[0])*1000000000
		handle_update_file.write("%d"%patch_version)	
		handle_update_file.close()
		patch_file_name = choose_server_patch(zone_id,system_type)
	else:
		print "no patch need do"		
예제 #2
0
    def __init__(self, possible_uuid=None):
        """
        Initialize to first valid UUID in argument (if a string),
        or to null UUID if none found or argument is not supplied.

        If the argument is a UUID, the constructed object will be a copy of it.
        """
        self._bits = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
        if possible_uuid is None:
            return

        if isinstance(possible_uuid, type(self)):
            self.set(possible_uuid)
            return

        uuid_match = UUID.uuid_regex.search(possible_uuid)
        if uuid_match:
            uuid_string = uuid_match.group()
            s = string.replace(uuid_string, "-", "")
            self._bits = (
                _int2binstr(string.atol(s[:8], 16), 4)
                + _int2binstr(string.atol(s[8:16], 16), 4)
                + _int2binstr(string.atol(s[16:24], 16), 4)
                + _int2binstr(string.atol(s[24:], 16), 4)
            )
예제 #3
0
    def get_queue_attributes(self, req, resp):
        #check parameter
        GetQueueAttrValidator.validate(req)

        #make request internal
        req_inter = RequestInternal(req.method, "/%s" % req.queue_name)
        self.build_header(req, req_inter)

        #send request
        resp_inter = self.mHttp.send_request(req_inter)

        #handle result, make response
        resp.status = resp_inter.status
        resp.header = resp_inter.header
        self.check_status(SET_QUEUE_ATTRIBUTES_STATUS, resp_inter, resp)
        if resp.error_data == "":
            queue_attr = GetQueueAttrDecoder.decode(resp_inter.data)
            resp.active_messages = string.atol(queue_attr["ActiveMessages"])
            resp.create_time = string.atol(queue_attr["CreateTime"])
            resp.delay_messages = string.atol(queue_attr["DelayMessages"])
            resp.delay_seconds = string.atol(queue_attr["DelaySeconds"])
            resp.inactive_messages = string.atol(queue_attr["InactiveMessages"])
            resp.last_modify_time = string.atol(queue_attr["LastModifyTime"])
            resp.maximum_message_size = string.atol(queue_attr["MaximumMessageSize"])
            resp.message_retention_period = string.atol(queue_attr["MessageRetentionPeriod"])
            resp.queue_name = queue_attr["QueueName"]
            resp.visibility_timeout = string.atol(queue_attr["VisibilityTimeout"])
            resp.polling_wait_seconds = string.atol(queue_attr["PollingWaitSeconds"])
예제 #4
0
def add_tweet_type():
    global stored_array;
    infile = file('checkin_sources.txt');
    lines = infile.readlines();
    tweet_map = {};
    for line in lines:
        item = line.split('\t');
        key = string.atol(item[0]);
        tweet_map[key]=item[1];
    infile.close();

    outfile = file('ordered_tweet_type.txt', 'w');
    outfile.close();
    outfile = file('ordered_tweet_type.txt', 'a');
    for line in stored_array:
        item = line.split('\t');
        if len(item) > 2:
            tweet_id = string.atol(item[1]);
            type = tweet_map.get(tweet_id);
            if type != None:
                outfile.write(item[1]+'\t'+type);
            #type = 'forsquare\n';
            #if type != None:
            #    line = line[0:(len(line)-1)] + '\t' + type[0:(len(type)-1)];
    outfile.close();        
예제 #5
0
def Loop():
    audio = [0]*300
    video = [0]*300
    diff = [0]*300
    reobj = re.compile(r"Audio PTS = ([\d]*), Video PTS = ([\d]*)")
    cnt = 0 # recv counter
    plt.hold(False)# Hold Off
    while True:
        # Receive Data form Socket
        print 1
        data, addr = s.recvfrom(2048)
        print 1
        cnt += 1
        # Parse the Data
        match = reobj.search(data)
        if match:
            curAudio = string.atol(match.group(1))
            curVideo = string.atol(match.group(2))
            audio += [curAudio]
            video += [curVideo]
            diff += [curAudio - curVideo]
        # Plot the figure every 15 packets received if we plot too frequently, it will block the new packet
        if(0 == cnt%15):
            iStart = len(diff) - SHOW_DURATION
            if iStart < 0:
                iStart = 0
            # plot the data
            plt.plot(x[iStart:-1],diff[iStart:-1])
            # To set the limit of y, ylim() should be called after plot, or it will lose efficacy
            plt.ylim(Y_MIN, Y_MAX)
            # to refresh the figure by force
            plt.draw()
예제 #6
0
def integervalidator(text):
    if text in ('', '-', '+'):
        return PARTIAL
    try:
        string.atol(text)
        return OK
    except ValueError:
        return ERROR
예제 #7
0
def hexadecimalvalidator(text):
    if text in ('', '0x', '0X', '+', '+0x', '+0X', '-', '-0x', '-0X'):
        return PARTIAL
    try:
        string.atol(text, 16)
        return OK
    except ValueError:
        return ERROR
예제 #8
0
 def make_peekresp(self, data, resp):
     resp.dequeue_count = string.atol(data["DequeueCount"])
     resp.enqueue_time = string.atol(data["EnqueueTime"])
     resp.first_dequeue_time = string.atol(data["FirstDequeueTime"])
     resp.message_body = data["MessageBody"]
     resp.message_id = data["MessageId"]
     resp.message_body_md5 = data["MessageBodyMD5"]
     resp.priority = string.atol(data["Priority"])
예제 #9
0
def main():
  import sys
  import string
  stream = sys.stdin
  # stream = open("tests/official/input29.txt")
  line = stream.readline()
  line = line.rstrip("\n")
  args = line.split(" ")
  args = [string.atol(x) for x in args]
  N = int(args[0])
  line = stream.readline()
  line = line.rstrip("\n")
  args = line.split(" ")
  args = [string.atol(x) for x in args]
  radii = [int(x) for x in args]
  sorted_radii = sorted(radii)
  line = stream.readline()
  line = line.rstrip("\n")
  args = line.split(" ")
  args = [string.atol(x) for x in args]
  M = int(args[0])
  endpoint_pairs = []
  for i in range(M):
    line = stream.readline()
    line = line.rstrip("\n")
    args = line.split(" ")
    args = [string.atol(x) for x in args]
    x1 = int(args[0])
    y1 = int(args[1])
    x2 = int(args[2])
    y2 = int(args[3])
    endpoint1 = (x1, y1)
    endpoint2 = (x2, y2)
    endpoint_pair = (endpoint1, endpoint2)
    endpoint_pairs.append(endpoint_pair)
  num_qs = 0
  for endpoint_pair in endpoint_pairs:
    endpoint1, endpoint2 = endpoint_pair
    distance1 = getSquaredDistance((0, 0), endpoint1)
    distance2 = getSquaredDistance((0, 0), endpoint2)
    candidate_distances = [distance1, distance2]
    min_distance = min(candidate_distances)
    max_distance = max(candidate_distances)
    closer_endpoint = None
    farther_endpoint = None
    if (min_distance == distance1):
      closer_endpoint = endpoint1
      farther_endpoint = endpoint2
    else:
      closer_endpoint = endpoint2
      farther_endpoint = endpoint1
    x1, y1 = closer_endpoint
    x2, y2 = farther_endpoint
    curr_num_qs = countingRangeQuery(sorted_radii, x1, y1, x2, y2)
    num_qs = num_qs + curr_num_qs
  print(num_qs, end = '')
예제 #10
0
 def make_recvresp(self, data, resp):
     resp.dequeue_count = string.atol(data["DequeueCount"])
     resp.enqueue_time = string.atol(data["EnqueueTime"])
     resp.first_dequeue_time = string.atol(data["FirstDequeueTime"])
     resp.message_body = data["MessageBody"]
     resp.message_id = data["MessageId"]
     resp.message_body_md5 = data["MessageBodyMD5"]
     resp.next_visible_time = string.atol(data["NextVisibleTime"])
     resp.receipt_handle = data["ReceiptHandle"]
     resp.priority = string.atol(data["Priority"])
예제 #11
0
    def __init__(self, f):
        self.fpi=f
        for sentence in self.read_instance(self.fpi):
	    WordsList= sentence.split()
	    if WordsList[1]=="WORDTAG" :
               self.diction[WordsList[3]]={"O":0,"I-GENE":0}
	       if WordsList[2]=="O" :
                  self.TagType["counttag_O"]+=string.atol(WordsList[0])
	       else :
	          self.TagType["counttag_I-GENE"]+=string.atol(WordsList[0])
예제 #12
0
    def __init__(self):
	fpi.seek(0)
        for sentence in self.read_instance(self.fpi):
	    WordsList= sentence.split()
	    if WordsList[1]=="2-GRAM" :
               temp=(WordsList[2],WordsList[3])
	       self.CountBigram[temp]=string.atol(WordsList[0])
	    elif WordsList[1]=="3-GRAM":
	       temp=(WordsList[2],WordsList[3],WordsList[4])
	       self.CountTrigram[temp]=string.atol(WordsList[0])
예제 #13
0
def read_pairs(filename):
    pairs = []
    fd = open(filename, 'r')
    for line in fd: 
        pair = line.strip().split()
        if len(pair) != 2: continue
        pair[0] = step_to_mm(string.atol(pair[0], 16))
        pair[1] = adc10_to_mm(string.atol(pair[1], 16))
        pairs.append(pair)
    fd.close();
    return pairs
예제 #14
0
 def setFromString(self, uuid_string):
     """
     Given a string version of a uuid, set self bits
     appropriately. Returns self.
     """
     s = string.replace(uuid_string, '-', '')
     self._bits = _int2binstr(string.atol(s[:8],16),4) + \
                  _int2binstr(string.atol(s[8:16],16),4) + \
                  _int2binstr(string.atol(s[16:24],16),4) + \
                  _int2binstr(string.atol(s[24:],16),4) 
     return self
예제 #15
0
 def parse_netstat(self):
     '''
     Gets the number of received and transmitted bytes on Mac OS X
     - iface: the interface, e.g., en0
     '''
     # mac os 10.6
     output = subprocess.check_output(['netstat', '-b', '-I', self.iface], stderr=subprocess.STDOUT)
     tmp = string.split(output, '\n')
     res = shlex.split(tmp[1], comments=False) # 2nd line
     r, t = atol(res[6]), atol(res[9])
     return r, t
예제 #16
0
    def _update_transport_position(self, state):
        connection_manager = self.server.connection_manager_server
        av_transport = self.server.av_transport_server
        conn_id = connection_manager.lookup_avt_id(self.current_connection_id)

        position = self.player.query_position()
        #print position

        for view in self.view:
            view.status(self.status(position))

        if position.has_key(u'raw'):

            if self.duration == None and 'duration' in position[u'raw']:
                self.duration = int(position[u'raw'][u'duration'])
                if self.metadata != None and len(self.metadata)>0:
                    # FIXME: duration breaks client parsing MetaData?
                    elt = DIDLLite.DIDLElement.fromString(self.metadata)
                    for item in elt:
                        for res in item.findall('res'):
                            formatted_duration = self._format_time(self.duration)
                            res.attrib['duration'] = formatted_duration

                    self.metadata = elt.toString()
                    #print self.metadata
                    if self.server != None:
                        av_transport.set_variable(conn_id,
                                                  'AVTransportURIMetaData',
                                                  self.metadata)
                        av_transport.set_variable(conn_id,
                                                  'CurrentTrackMetaData',
                                                  self.metadata)


            self.info("%s %d/%d/%d - %d%%/%d%% - %s/%s/%s", state,
                      string.atol(position[u'raw'][u'position'])/1000000000,
                      string.atol(position[u'raw'][u'remaining'])/1000000000,
                      string.atol(position[u'raw'][u'duration'])/1000000000,
                      position[u'percent'][u'position'],
                      position[u'percent'][u'remaining'],
                      position[u'human'][u'position'],
                      position[u'human'][u'remaining'],
                      position[u'human'][u'duration'])

            duration = string.atol(position[u'raw'][u'duration'])
            formatted = self._format_time(duration)
            av_transport.set_variable(conn_id, 'CurrentTrackDuration', formatted)
            av_transport.set_variable(conn_id, 'CurrentMediaDuration', formatted)

            position = string.atol(position[u'raw'][u'position'])
            formatted = self._format_time(position)
            av_transport.set_variable(conn_id, 'RelativeTimePosition', formatted)
            av_transport.set_variable(conn_id, 'AbsoluteTimePosition', formatted)
예제 #17
0
	def _iphexatodec(self, iphexa) :
		ipdec=""

		for i in range(0, 8, 2) :
			ipdec = "%d" % string.atol(iphexa[i:i+2], 16) + "." + ipdec
		
		if(iphexa[9:] == "0000") :
			ipdec = ipdec[:-1] + ":" + "*"
		else :
			ipdec = ipdec[:-1] + ":" + "%d" % string.atol(iphexa[9:], 16)
		
		
		return ipdec
예제 #18
0
 def parse_proc_net_dev(self):
     '''
     Gets the number of received and transmitted bytes on Linux
     - iface: the interface, e.g., eth0
     '''
     f = open('/proc/net/dev')
     r = 0
     t = 0
     for l in f:
         if l.find("%s:" % self.iface) == -1: continue
         spl = l.split()
         r, t = atol(spl[1]), atol(spl[9])
     f.close()
     return r, t
예제 #19
0
파일: lluuid.py 프로젝트: Boy/netbook
 def __init__(self, string_with_uuid=None):
     """
     Initialize to first valid UUID in string argument,
     or to null UUID if none found or string is not supplied.
     """
     self._bits = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
     if string_with_uuid:
         uuid_match = UUID.uuid_regex.search(string_with_uuid)
         if uuid_match:
             uuid_string = uuid_match.group()
             s = string.replace(uuid_string, '-', '')
             self._bits = _int2binstr(string.atol(s[:8],16),4) + \
                          _int2binstr(string.atol(s[8:16],16),4) + \
                          _int2binstr(string.atol(s[16:24],16),4) + \
                          _int2binstr(string.atol(s[24:],16),4) 
예제 #20
0
def readInput(stream):
  line = stream.readline()
  line = line.rstrip("\n")
  args = line.split()
  args = [string.atol(x) for x in args]
  N = int(args[0])
  M = int(args[1])
  X_train = []
  y_train = []
  train_id_list = []
  X_test = []
  test_id_list = []
  for i in xrange(N):
    line = stream.readline()
    line = line.rstrip("\n")
    args = line.split()
    id_str = args[0]
    label = int(args[1])
    feature_pairs = args[2 : ]
    feature_vector = []
    for feature_pair in feature_pairs:
      feature_pair_str_list = feature_pair.split(":")
      feature_index = int(feature_pair_str_list[0])
      feature_value = float(feature_pair_str_list[1])
      feature_vector.append(feature_value)
    X_train.append(feature_vector)
    y_train.append(label)
    train_id_list.append(id_str)
  line = stream.readline()
  line = line.rstrip("\n")
  args = line.split()
  args = [string.atol(x) for x in args]
  q = int(args[0])
  for i in xrange(q):
    line = stream.readline()
    line = line.rstrip("\n")
    args = line.split()
    id_str = args[0]
    feature_pairs = args[1 : ]
    feature_vector = []
    for feature_pair in feature_pairs:
      feature_pair_str_list = feature_pair.split(":")
      feature_index = int(feature_pair_str_list[0])
      feature_value = float(feature_pair_str_list[1])
      feature_vector.append(feature_value)
    X_test.append(feature_vector)
    test_id_list.append(id_str)
  return (X_train, y_train, train_id_list), (X_test, test_id_list)
예제 #21
0
	def checkFingerprints(self, fd) :
		syscalls_hijack = []
		end = 0
		self.getSyscalls()
		self.getOpcodes()
			
		i = fd.readline()
		liste = i.split()
		while(liste != [] and end == 0):
			if(liste[0] != '#') :
				self.syscalls_fingerprints.map_syscalls[int(liste[0])] = [string.atol(liste[1], 16), liste[3] + " " + liste[4]]
			else :
				if(len(liste) > 1) :
					if(liste[1] == "END"):
						end = -1

			i = fd.readline()
			liste = i.split()

		print "++ Checking Syscalls Fingerprints !!!"
		for i in self.lists_syscalls:
			if((self.syscalls_fingerprints.map_syscalls[i[0]][0] != self.syscalls_mem.map_syscalls[i[0]][0]) or (self.syscalls_fingerprints.map_syscalls[i[0]][1] != self.syscalls_mem.map_syscalls[i[0]][1])):
				syscalls_hijack.append([i[0], i[1]])
	
		if(syscalls_hijack != []):
			print "\t** LISTS OF SYSCALLS HIJACK !!"
			for i in syscalls_hijack:
				print "\t\t** %d\t %-15s" %(i[0], i[1])

			print "\n\t** PLEASE REINSTALL YOUR SYSTEM NOW !!!"

		else:
			print "\t** NO SYSCALLS HIJACK"
예제 #22
0
파일: frame.py 프로젝트: Wurldtech/beepy
    def _bufferToFrame(self, data):
        """
        Converts a bytestring data buffer to a frame object.
        
        @param data: a bytestring containing a raw frame
        @type data: string

        @return: SEQFrame

        @raise SEQFrameException: if format of frame is invalid
        """
        # Now split the frame into bits
        headerbits = string.split(data)

        # Check for valid format
        if len(headerbits) != 4:
            raise SEQFrameException('Format Invalid')

        try:
            self.channelnum = string.atoi(headerbits[1])
            self.ackno = string.atoi(headerbits[2])
            self.window = string.atol(headerbits[3])

        except Exception, e:
            raise SEQFrameException('unknown error in _bufferToFrame')
def strToNum(n):
    val = 0
    col = long(1)
    if n[:1] == "x":
        n = "0" + n
    if n[:2] == "0x":
        # hex
        n = string.lower(n[2:])
        while len(n) > 0:
            l = n[len(n) - 1]
            val = val + string.hexdigits.index(l) * col
            col = col * 16
            n = n[: len(n) - 1]
    elif n[0] == "\\":
        # octal
        n = n[1:]
        while len(n) > 0:
            l = n[len(n) - 1]
            if ord(l) < 48 or ord(l) > 57:
                break
            val = val + int(l) * col
            col = col * 8
            n = n[: len(n) - 1]
    else:
        val = string.atol(n)
    return val
예제 #24
0
            def handleLineEditChange(new_text):
                ix = self.inputFields.index(inputBox)
                thisType = self.inputFieldTypes[ix]

                try:
                    if thisType in (str, unicode):
                        self.data[ix] = unicode(new_text)
                    elif thisType == tuple:
                        jtext = "[" + unicode(new_text) + "]"
                        self.data[ix] = json.loads(jtext)[0]
                    elif thisType == list:
                        jtext = "[" + unicode(new_text) + "]"
                        self.data[ix] = json.loads(jtext)[0]
                    elif thisType == float:
                        self.data[ix] = string.atof(str(new_text))
                    elif thisType == int:
                        self.data[ix] = string.atoi(str(new_text))
                    elif thisType == long:
                        self.data[ix] = string.atol(str(new_text))
                    elif thisType == dict:
                        jtext = "[" + unicode(new_text) + "]"
                        self.data[ix] = json.loads(jtext)[0]
                    elif thisType == np.ndarray:
                        self.data[ix] = np.array(
                            json.loads("[" + unicode(new_text) + "]")[0])
                    else:
                        self.data[ix] = new_text

                except Exception as e:
                    self.data[ix] = unicode(new_text)
예제 #25
0
파일: dbf.py 프로젝트: xivk/crab-tools
	def decodeValue(self, rawval):
		'''system: answer .dbt block number
		jjk  02/18/98'''
		try:
			return(string.atoi(string.strip(rawval)))
		except ValueError:
			return(string.atol(string.strip(rawval)))
예제 #26
0
    def __convert_properties(self, properties):

        # Attempt to normalize the UUID.
        if properties.has_key(PropertyType.UUID):
            uuid = properties[PropertyType.UUID]
            if uuid:
                uuid_as_number = string.atol(uuid, 16)

                if uuid_as_number == 0:
                    # If the UUID is a bunch of null bytes, we will convert it 
                    # to None.  This will allow us to interact with the 
                    # database properly, since the database assumes a null UUID
                    # when the system is a host.
                    properties[PropertyType.UUID] = None
                else:
                    # Normalize the UUID.  We don't know how it will appear 
                    # when it comes from the client, so we'll convert it to a 
                    # normal form.
                    # if UUID had leading 0, we must pad 0 again #429192
                    properties[PropertyType.UUID] = "%032x" % uuid_as_number

        # The server only cares about certain types of states.
        if properties.has_key(PropertyType.STATE):
            state = properties[PropertyType.STATE]
            properties[PropertyType.STATE] = CLIENT_SERVER_STATE_MAP[state]

        # We must send the memory across as a string because XMLRPC can only
        # handle up to 32 bit numbers.  RAM can easily exceed that limit these
        # days.
        if properties.has_key(PropertyType.MEMORY):
            memory = properties[PropertyType.MEMORY]
            properties[PropertyType.MEMORY] = long(memory)
예제 #27
0
def handle_file(filename):
    fp_i = open(filename+".in", "r")
    fp_o = open(filename+".out", "w")

    line = fp_i.readline().split()
    C = string.atoi(line[0])

    for c in range(C):
        line = fp_i.readline().split()
        N = string.atoi(line.pop(0))
        line = [string.atol(line[j]) for j in range(N)]
        line2 = [0 for i in range(N-1)]
        # sort the array from big to small
        line.sort(None, None, True)

        # line2[] stores the diff value between immediate elements in line[]
        for i in range(N-1):
            line2[i] = line[i] - line[i+1]

        T = gcd_all(line2)

        if (line[0]%T):
            y = (line[0]/T+1)*T-line[0]
        else:
            y = 0
            
        result = "Case #%d: %ld\n"%(c+1, y)
        print result, T
        fp_o.write(result)
       
    fp_i.close()
    fp_o.close()
예제 #28
0
def needsEnterpriseKernel():
    rc = 0

    try:
        f = open("/proc/e820info", "r")
    except IOError:
        return 0
    for l in f.readlines():
        l = string.split(l)
        if l[3] == '(reserved)': continue

        regionEnd = (string.atol(l[0], 16) - 1) + string.atol(l[2], 16)
        if regionEnd > 0xffffffffL:
            rc = 1

    return rc
예제 #29
0
def doHistNode(stampStr,histNode):
	# msg/hist/data/sensor(0)/../[h|d]???
	# for all data nodes
	# find first sensor child, only handle sensor0
	#  handle all it's (h|d|m)XXX siblings
	for dataNode in histNode.getElementsByTagName('data'):
		sensor = string.atol(dataNode.getElementsByTagName('sensor')[0].childNodes[0].nodeValue)
		#print "Found sensor: %d" % sensor
		if (sensor==0):
			#print "Handling sensor: %d" % sensor
			for hdm in dataNode.childNodes:
				#print "tag: %s" % hdm.tagName
				if ("sensor"==hdm.tagName):
					continue
				scopePrefix=hdm.tagName[:1]             # h|d|m
				scopeIndex=string.atoi(hdm.tagName[1:]) # 4 in h004 or 2 in m002
				scopeValue=string.atof(hdm.childNodes[0].nodeValue);
				if ("h"==scopePrefix):
					#print "%s Hour  %05d %10.5f" % ( stampStr, scopeIndex, scopeValue )
					accumulateHours(stampStr, scopeIndex, scopeValue )
				if ("d"==scopePrefix):
					#print "%s Day  %05d %10.5f" % ( stampStr, scopeIndex, scopeValue )
					accumulateDays(stampStr, scopeIndex, scopeValue )
				if ("m"==scopePrefix):
					print "%s Month  %05d %10.5f" % ( stampStr, scopeIndex, scopeValue )
예제 #30
0
    def read_keymap(self, path, name):
        keys = {}
        km = open(os.path.join(path, name), 'r')
        for line in km.xreadlines():
            if '#' == line[0] or '\n' == line[0]:
                continue

            line = line.strip()

            if "include " == line[:8]:
                keys.update(self.read_keymap(path, line[8:].strip()))
                continue
            elif "map " == line[:4]:
                self.map = string.atol(line[4:], 16)
                continue

            elif "enable_compose" == line[:15]:
                self.enable_compose = 1
                continue
            else:
                mo = self.mapfind.search(line)
                (key, code, rest) = mo.groups()

                keys[string.atoi(code, 16)] = "%s / %s" % (key, rest)

        return keys
예제 #31
0
def setrambase(dir, address):
	global rambase
	rambase = string.atol(address,0)
예제 #32
0
        "wget --passive-ftp -c ftp://ftp.unicode.org/Public/UNIDATA/EastAsianWidth.txt"
    )
    unidata = open("EastAsianWidth.txt", "r")
out = open("uniwidths", "w")
ranges = []
specifics = []
rangere = re.compile("^([0123456789ABCDEF]+)\.\.([0123456789ABCDEF]+);A")
specificre = re.compile("^([0123456789ABCDEF]+);A")
for line in unidata.readlines():
    match = re.match(specificre, line)
    if match:
        if match.groups().__len__() > 0:
            specifics.append(match.groups()[0])
    match = re.match(rangere, line)
    if match:
        if match.groups().__len__() > 1:
            ranges.append((match.groups()[0], match.groups()[1]))

print >> out, "static const struct {"
print >> out, "\tgunichar start, end;"
print >> out, "} _vte_iso2022_ambiguous_ranges[] = {"
for range in ranges:
    print >> out, "\t{0x%x, 0x%x}," % (string.atol(
        range[0], 16), string.atol(range[1], 16))
print >> out, "};"

print >> out, "static const gunichar _vte_iso2022_ambiguous_chars[] = {"
for specific in specifics:
    print >> out, "\t0x%x," % (string.atol(specific, 16))
print >> out, "};"
예제 #33
0
 def BuildTime(self, utc_time):
     _time = time.strftime('%H%M%S', time.localtime(utc_time))
     _milli = self.BuildMilliSecond(utc_time)
     return (string.atol("{0}{1}".format(_time, _milli)) +
             self.GetTimetag()) & 0x00000000FFFFFFFF
예제 #34
0
def getJokes(page, mongo):
    url = "http://www.qiushibaike.com/text/page/" + page
    result = ""
    strId = ""
    numId = -1
    text = ""
    comment = ""
    '''data={
    "joke_id" : "119048549",
    "joke_content" : "小时候,一听到布谷鸟叫,就知道该吃桑葚了。记得第一次吃桑葚,楼主吃的是满嘴黑……老妈看着楼主,突然笑着问:闺女,你知道布谷鸟在说什么吗?老妈见楼主一脸懵圈,哈哈一笑说:布谷鸟在说‘布谷~布谷~吃我桑葚的黑 屁 股’……楼主:…… ",
    "comment" : {
        "comment_id" : "1",
        "comment_time" : "20170520",
        "comment_content" : "funny"
    }
    }
    mongo.db.jokes.insert_one(data)'''
    jokes = mongo.db.jokes
    try:
        response = requests.get(url)
        html = response.content
        soup = BeautifulSoup(html, "html.parser")
        #print soup.prettify()
        #print soup.head
        i = 1
        for item in soup.find_all("div", class_='article block untagged mb15'):
            a = item.find("a", class_='contentHerf')
            #将href属性中的数字提取出来,提取结果编码为unicode,需转为utf-8
            strId = re.sub("\D", "", a.attrs['href']).encode('utf-8')
            #将strId转换为数字型的numId
            numId = string.atol(strId)
            text = a.text.strip()

            res = jokes.find_one({"joke_id": strId})
            if (res == None):
                data = {'joke_id': strId, 'joke_content': text, 'comment': []}
                jokes.insert_one(data)
                comment = "<div>comment area</div>"
            else:
                comment = "<div>comment area"
                index = 0
                for it in res['comment']:
                    index = index + 1
                    comment = comment + "<div>" + str(
                        index) + "." + it['comment_content'] + "</div>" + "\n"
                comment = comment + "</div>"
            formatdiv = '<form action="" method="post" class="basic-grey-jokes"><div id="' + strId + '">' + str(
                i
            ) + "." + strId + "<input type='hidden' name='page_id' value='" + page + "'/>" + "<input type='hidden' name='joke_id' value='" + strId + "'></input>" + "\n<br/>" + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + text + "\n" + "<br/><br/></div>" + "<div class='basic-grey'>" + comment + "</div>" + '<label><span>comment:</span>' + '<textarea id="message" name="message" placeholder="Your Message to Us"></textarea></label>' + '<label><span>&nbsp;</span>' + '<input type="submit" class="button" value="Send" /></label></form>'
            #result = result+str(i)+"."+ strId +"\n<br/>"+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+ text +"\n"+"<br/><br/>"
            result = result + formatdiv
            i = i + 1
        '''
        for item in soup.find_all("div",class_='content'):
            result=result+"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+(str)(i)+"."+item.span.text+"<br/><br/>"
            #file.write((str)(i)+":"+item.span.text.encode("utf-8")+"\n")
            i=i+1
        #file.close()
        #return page
        '''
        return result
    except urllib2.URLError, e:
        if (hasattr(e, "code")):
            print e.code
        if (hasattr(e, "reason")):
            print e.reason
        return result
예제 #35
0
def _toLong(s, base):
    try:
        return long(s, base)
    except TypeError:
        return string.atol(s, base)
예제 #36
0
 elif arguments[0] == 'run':
     if options.serverscript:
         jobId = s.runServerScript(options.serverscript,options.server)
         print "JobID: %s" % jobId
     else:
         print "Please provide --serverscript=<SA Server script> with run action"
 elif arguments[0] == 'attach':
     if options.spolicy:
         print "%s" % options.spolicy
     else:
         print "--spolicy=<spolicy id or path and name> needs to be used with attach."
 elif arguments[0] == 'history':
     if options.days:
         for i in s.getServerRefs(options.server):
             print "Server Name: %s" % i.name
             for j in s.getServerHistorybyDays(i,string.atol(options.days)):
                 print "%s" % re.sub('[{}]','',"%s" % j)
         print "%s" % options.days
     elif options.weeks:
         print "%s" % options.weeks
     else:
         option_usage("With --server=<%s> [--days=<num of days> --weeks=<num of weeks]" % \
                                                     object_list['server'][2],'')
 elif arguments[0] == 'update':
     if options.customfield:
         if not options.value:
             print "No value option given will clear this Customfield value, previous value is: %s" % \
                                     s.getCustomField(options.server,options.customfield)
         s.updateCustomField(options.server,options.customfield,options.value)
     else:
         print "Must provide --customfield and --value option."
예제 #37
0
import string
hexstr = '0123456789abcdef'
s = ''
for i in range(0, 16, 2):
    s = s + chr(string.atol(hexstr[i:i + 2], 16))
f = open('data', 'w')
f.write(s)
f.close()
예제 #38
0
파일: meta.py 프로젝트: nukamu/mogami
                                       created)

    def release(self, fd, fsize):
        """release handler.

        @param fd file discripter
        @param writelen size of data to be written
        """
        os.lseek(fd, 0, os.SEEK_SET)
        try:
            buf = os.read(fd, conf.bufsize)
        except os.error, e:
            print "OSError in release (%s)" % (e)
        l = buf.rsplit(',')

        size = string.atol(l[2])
        if size != fsize:
            try:
                buf = l[0] + ',' + l[1] + ',' + str(fsize)
                MogamiLog.debug("write to meta file %s" % buf)

                os.ftruncate(fd, len(buf))
                os.lseek(fd, 0, os.SEEK_SET)
                os.write(fd, buf)
                os.fsync(fd)
            except os.error, e:
                print "OSError in release (%s)" % (e)

        os.close(fd)
        ans = 0
        self.c_channel.release_answer(ans)
예제 #39
0
from test_support import verify, verbose, TestFailed, fcmp
예제 #40
0
 def load_long(self):
     self.append(string.atol(self.readline()[:-1], 0))
예제 #41
0
    iptable[linecount] = re.split(',',readline)
    readline = IPDBf.readline()
    linecount= linecount+1
IPDBf.close()

oldcnt = 0
ipcount = 0
readline = listf.readline()
while readline:
    readline = readline.replace('\n','')
    ipcol = re.split('\.',readline)
    ipvalue = string.atoi(ipcol[0])*16777216 + string.atoi(ipcol[1])*65536 + string.atoi(ipcol[2])*256 + string.atoi(ipcol[3])

    c_str = ' , '
    if ipcount >= linecount-1:
        ipcount = oldcnt
    while  ipcount < linecount:
        startip = string.atol(iptable[ipcount][2])
        endip = string.atol(iptable[ipcount][3])
        if ipvalue >= startip and ipvalue <= endip:
            c_str = iptable[ipcount][4]+','+iptable[ipcount][5]
            oldcnt = ipcount
            break
        ipcount = ipcount + 1
#===end while linecount>=0:
    resultf.write(readline+','+c_str+'\n')
    readline = listf.readline()
listf.close()
resultf.close()

print "All done.."
예제 #42
0
def dj_telnet_connect(Host, username, password, commands, handler):

    enter = '\n'
    serialNum = ""
    serialNum_ori = ""
    randomNum = ""
    randomNum_orig = ""

    t = telnetlib.Telnet(Host)

    t.read_until("login: "******"Password: "******"Congratulations,telnet is OK,start to rescue."

    for command in commands:

        if command.find("testsysinfo -g STB_BBCB_SN_RANDNUMBER") != -1:
            #print "Meet get SN statement" + enter
            t.write('%s\n' % command)
            sleep(2)
            res = t.read_very_eager()
            #print "djstava:" + res
            ret = res.find("vlaue is")
            if ret != -1:
                serialNum = res[ret + 9:ret + 20]
                randomNum_orig = (res[ret + 21:ret + 32]).replace('-', '')
                print "Serial Number is : " + serialNum
                print "OOOOOOOOOOOOOOOOOOOrig random number is:" + randomNum_orig + ",MAC is: " + dj_getMacAddr(
                    Host) + ",IP is: " + Host

                if string.atol(randomNum_orig, 16) != 0:
                    #print "No need to rescue."
                    handler.write(Host + "  MAC: " + dj_getMacAddr(Host) +
                                  " ,No need to rescue." + enter)
                    break
                else:
                    serialNum_ori = serialNum.replace('-', '')

                    randomNum = dj_getRandomNubFromSqlite3(
                        serialNum_ori.upper())
                    print "Random Number in DB is : " + randomNum
                    setRNCommand = "./testsysinfo -s STB_BBCB_SN_RANDNUMBER" + ' "' + serialNum + '-' + randomNum[
                        0:2] + '-' + randomNum[2:4] + '-' + randomNum[
                            4:6] + '-' + randomNum[6:8] + '"' + enter

                    #print setRNCommand
                    t.write(setRNCommand.encode("ascii"))
                    handler.write(Host + "  MAC: " + dj_getMacAddr(Host) +
                                  " ,has been rescued." + enter)

            else:
                print "Get SN wrong."
        else:
            t.write('%s\n' % command)

    global itemCount
    itemCount += 1

    if itemCount % 5 == 0:
        handler.write(enter)

    t.close()
예제 #43
0
파일: mutils.py 프로젝트: flyawaytang/pyrt
def str2id(str):

    quads = string.split(str, '.')
    ret   = (string.atol(quads[0]) << 24) + (string.atol(quads[1]) << 16) + \
            (string.atol(quads[2]) <<  8) + (string.atol(quads[3]) <<  0)
    return ret
예제 #44
0
 def test_atol(self):
     self.assertEqual(string.atol("  1  "), 1L)
     self.assertRaises(ValueError, string.atol, "  1x ")
     self.assertRaises(ValueError, string.atol, "  x1 ")
예제 #45
0
    return True


# pydbgpyemu.py calc.exe 0x001001AF3
if len(sys.argv) < 3:
    print "Usage: %s <process name> <emulator start address>" % sys.argv[0]

    sys.exit(-1)

procname = sys.argv[1]
emuaddress = sys.argv[2]

if len(sys.argv) == 4:
    myinstruction = sys.argv[3]
else:
    myinstruction = None

dbg = pydbg()
dbg.procname = procname
dbg.emuaddress = string.atol(emuaddress, 16)
dbg.myinstruction = myinstruction
dbg.emucontext = None

dbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)
dbg.set_callback(EXCEPTION_SINGLE_STEP, handler_ss)
if not attach_target_proc(dbg, procname):
    print "[!] Couldnt load/attach to %s" % procname

    sys.exit(-1)

dbg.debug_event_loop()
예제 #46
0
# Print Packet Response
print "Received Handshake Response"

# Check its MQ
check_mq(data,verbose)

# Get the queue manager name 
queue_manager = check_status(data,verbose)

if queue_manager == 0:
    check_return_code(queue_manager, outgoing, "", 1)
    sys.exit(0)

# Set the flags, message size and heartbeat for the next communication
flags = string.atoi(str(binascii.hexlify(data[33:34])),16)
heartbeat = string.atol(str(binascii.hexlify(data[124:128])),16)
message_size = string.atol(str(binascii.hexlify(data[44:48])),16)

# Send the second handshake string
send_string = mq.get_handshake2(channel, flags, message_size, heartbeat)

# Send the second handshake string
outgoing.send(send_string)

# Print Packet Response
print "Received 2nd Handshake Response"

# Receive the response
data = read_data(outgoing,ssl)

flags = check_handshake(data)
예제 #47
0
HOST = '127.0.0.1'  #localhost
PORT = 8001
MAXCONN = 50


def usage():
    print """
    -h --help             print the help
    -l --list             Maximum number of connections
    -p --port             To monitor the port number 
	"""


for op, value in opts:
    if op in ("-l", "--list"):
        MAXCONN = string.atol(value)
    elif op in ("-p", "--port"):
        PORT = string.atol(value)
    elif op in ("-h"):
        usage()
        sys.exit()

if __name__ == '__main__':
    while 1:
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((HOST, PORT))
            message = raw_input("input: ")
            s.sendall(message)
            if not message or message == "q":
                break
            return ERROR
        return PARTIAL

def datevalidator(text, format = 'ymd', separator = '/'):
    try:
        Pmw.datestringtojdn(text, format, separator)
        return OK
    except ValueError:
        if re.search('[^0-9' + separator + ']', text) is not None:
            return ERROR
        return PARTIAL

_standardValidators = {
    'numeric'      : (numericvalidator,      string.atol),
    'integer'      : (integervalidator,      string.atol),
    'hexadecimal'  : (hexadecimalvalidator,  lambda s: string.atol(s, 16)),
    'real'         : (realvalidator,         Pmw.stringtoreal),
    'alphabetic'   : (alphabeticvalidator,   len),
    'alphanumeric' : (alphanumericvalidator, len),
    'time'         : (timevalidator,         Pmw.timestringtoseconds),
    'date'         : (datevalidator,         Pmw.datestringtojdn),
}

_entryCache = {}

def _registerEntryField(entry, entryField):
    # Register an EntryField widget for an Entry widget

    _entryCache[entry] = entryField

def _deregisterEntryField(entry):
예제 #49
0
 def BuildDate(self, utc_time):
     return string.atol(time.strftime('%Y%m%d', time.localtime(utc_time)))
예제 #50
0
파일: jci.py 프로젝트: wudixy/jobctl
 def __formatARTime(self, tmstr):
     '''AR返回的时间是unix时间戳,需要格式化处理'''
     a = str(tmstr)
     a = a[:len(a) - 6]
     a = string.atol(a)
     return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(a))
예제 #51
0
# each line that follows has USD -> euro rate, euro -> GBP rate, GBP -> USD rate

# for each rate line, output profit for changing $100,000 to euros, then to GBP, then to dollars;
# return zero if no profit resulted

# print values in dollars truncated to whole dollars

import sys
import string
stream = sys.stdin
# stream = open("tests/input0.txt")
line = stream.readline()
line = line.rstrip("\n")
args = line.split(" ")
args = [string.atol(x) for x in args]
N = int(args[0])
# print N
quote_tuple_list = []
for i in xrange(N):
    line = stream.readline()
    line = line.rstrip("\n")
    args = line.split(" ")
    args = [string.atof(x) for x in args]
    # print args
    quote_tuple = tuple(args)
    quote_tuple_list.append(quote_tuple)


def trunc(num, digits):
    sp = str(num).split('.')
예제 #52
0
          print d.instruction
  """

    asmStack = I386Stack()
    #try:
    for d in ldata:
        if not d.isAssembler:
            continue
        if len(d.args) == 0:
            continue
        if len(d.args) == 2 and d.args[0] != "esp":
            continue

        if d.instruction == "push":
            asmStack.push(d.args[0])
        elif d.instruction == "pop":
            asmStack.pop()
        elif d.instruction == "add":
            asmStack.add(string.atol(d.args[1], 16))
        elif d.instruction == "sub":
            asmStack.sub(string.atol(d.args[1], 16))
        else:
            continue
        print d.full_text,
        print asmStack
    #except Exception, message:
    #     print message
    #     print d.full_text
    #     sys.exit (1)
    #print asmStack
예제 #53
0
    joinedStrig =''
    for i in strList:
        if joinedStrig == '':
            joinedStrig = str(i)
        else:
            joinedStrig = joinedStrig+joinLetter + str(i)
    return joinedStrig

print join(['1','2','ba','cc'],' ')

# int(),float(),long()
s = '18'
print int(s)
print string.atoi('011',8)
print string.atoi('0X11',16)
print string.atol('11')
print string.atof('1.2333333')

# ord()把字母转换为对应的ASCII,chr()把十进制的数字转换为字符

# s.encode([encodeing--编码类型],[errors--])编码函数,s.decode()解码

str = 'this is a string'
s1 = str.encode('base64','strict')#ignore--出现异常不会崩溃,会继续往下走
print s1
print 'decode:',s1.decode('base64','strict')




예제 #54
0
            usage()

        elif x in ('-q', '--quiet'):
            VERBOSE = 0

        elif x in ('-v', '--verbose'):
            VERBOSE = 2

        elif x in ('-f', '--file'):
            OUTPUT_F = y

        elif x in ('-s', '--start-time'):
            START_T = time.mktime(time.strptime(y))

        elif x in ('-i', '--interval'):
            INTERVAL = string.atol(y) * MINS_TO_SECS

        elif x in ('-t', '--table'):
            TABLE_F = y

        else:
            usage()

    filenames = args
    if not filenames:
        usage()

    #---------------------------------------------------------------------------

    NEXT_DUMP = START_T + INTERVAL
예제 #55
0
            data, addr = s.recvfrom(2048)
            logger.info("received: %s , from %s " % (data, addr[0]))
    except Exception, e:
        print e
    s.close()


if __name__ == '__main__':
    # Setup opts & args
    list = 50
    port = 30000
    opts, args = getopt.getopt(sys.argv[1:], "hp:l:",
                               ["help", "port=", "list="])
    for op, value in opts:
        if op in ("-l", "--list"):
            list = string.atol(value)
        elif op in ("-p", "--port"):
            port = string.atol(value)
        elif op in ("-h"):
            usage()
            sys.exit()

    logger.info('start udp server...')

    try:
        main(port)
    except KeyboardInterrupt:
        print 'Ctrl+C pressed... Shutting Down'
    except Exception, err:
        print 'Exception caught: %s\nClosing...' % err
예제 #56
0
 def getCommitOutFilePath(self,path,commit,date):
     return os.path.join(self.getFlatOutFilePath(path),time.strftime("%Y-%m-%d %X",time.localtime(string.atol(date))).replace(" ","_").replace(":","_")+"_"+commit[-5:]);
예제 #57
0
def scanFile(file, filename, funcs, typeMap, typeIncludes):
    text = file.read()
    protos = pat_func.findall(text)
    for proto in protos:
        name = pat_name.search(proto).group(1)
        r = pat_return.search(proto).group(1)
        argStr = pat_func_before_args.sub('', proto)
        argStr = pat_suffix.sub('', argStr)[:-1]
        argStr = pat_comment.sub(r'\1', argStr)
        argStr = pat_hint.sub('', argStr)
        matches = pat_args.findall(argStr)
        args = []
        for a in matches:
            func_ptr = a[4]
            if func_ptr:
                args.append((pat_func_ptr.sub(r'\3', func_ptr), pat_func_ptr.search(func_ptr).group(3)))
            else:
                args.append((fix_type(pat_hint.sub('', a[1])), a[2]))
        suffix = pat_suffix.search(proto)
        if suffix:
            suffix = suffix.group(0)
        else:
            suffix = ''
        ext = 'CL_EXT' in suffix
        deprecated = '_DEPRECATED' in suffix
        # 1.1 functions such as clCreateImage2D are marked CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED
        # but we should still export them
        core = deprecated or not ext
        funcs.append([proto, name, r, args, core, ext])

    type_name = None
    for line in string.split(text, '\n'):
        m = pat_struct.search(line)
        if m:
            v = m.group(1)
            if v in gen_format_struct_map:
                typeMap[v] = ''
        if type_name:
            m = pat_define.search(line)
            if not m:
                m = pat_bitfield.search(line)
            if m:
                v = (m.group(1), m.group(2))
                append_type_map(typeMap, type_name, v)
                if v[0] == 'CL_CONTEXT_PLATFORM':
                    # special case: belongs to cl_context_info and cl_context_properties on Mac
                    append_type_map(typeMap, 'cl_context_properties', v)
                if v[1][:2] == '0x' and string.atol(v[1], 16) >= 0x1000:
                    append_type_map(typeMap, 'token', v)
            elif not pat_c_cpp_comment.search(line):
                # end of type defines
                type_name = None
        else:
            m = pat_type_comment.search(line)
            if not m:
                m = pat_type_cpp_comment.search(line)
            if m and 'cl_mem flag - bitfield' in line:
                type_name = 'cl_mem_flags'
            elif m and not 'extension' in line:
                type_name = fix_type_name(m.group(2))
            elif '/* command execution status */' in line:
                type_name = 'execution_status'
            else:
                m = pat_err.search(line)
                if m:
                    v = (m.group(1), m.group(2))
                    if v[0] == 'CL_SUCCESS' or v[1][0] == '-':
                        append_type_map(typeMap, 'error', v)
                        continue
                m = pat_define.search(line)
                if m:
                    v = (m.group(1), m.group(2))
                    if v[1][:2] == '0x':
                        if 'CL_DEVICE' in v[0]:
                            append_type_map(typeMap, 'cl_device_info', v)
                        elif 'CL_IMAGE' in v[0]:
                            append_type_map(typeMap, 'cl_image_info', v)
                        elif 'CL_CGL' in v[0]:
                            append_type_map(typeMap, 'cl_gl_platform_info', v)
                        elif 'CL_COMMAND' in v[0]:
                            append_type_map(typeMap, 'cl_command_type', v)
                        elif 'CL_CONTEXT_PROPERTY' in v[0]:
                            append_type_map(typeMap, 'cl_context_properties', v)
                        elif 'CL_PROGRAM' in v[0]:
                            append_type_map(typeMap, 'cl_program_info', v)
                        elif 'CL_AFFINITY_DOMAIN' in v[0]:
                            append_type_map(typeMap, 'cl_device_affinity_domain', v)
                        elif v[0] in ('CL_CONTEXT_MEMORY_INITIALIZE_KHR',
                                      'CL_CONTEXT_TERMINATE_KHR'):
                            append_type_map(typeMap, 'cl_context_properties', v)
                        elif v[0] in ('CL_1RGB_APPLE', 'CL_BGR1_APPLE', 'CL_ABGR_APPLE'):
                            append_type_map(typeMap, 'cl_channel_order', v)
                        elif v[0] in (
                        'CL_YCbYCr_APPLE', 'CL_CbYCrY_APPLE', 'CL_SFIXED14_APPLE', 'CL_BIASED_HALF_APPLE'):
                            append_type_map(typeMap, 'cl_channel_type', v)
                        elif 'CL_CONTEXT_OFFLINE_DEVICES_AMD' == v[0]:
                            append_type_map(typeMap, 'cl_context_info', v)
                        elif v[0].startswith('CL_QUEUE') and v[0].endswith('_APPLE'):
                            append_type_map(typeMap, 'cl_queue_properties_APPLE', v)
                        elif v[0] in ('CL_OBJECT_NAME_APPLE'):
                            append_type_map(typeMap, 'cl_queue_properties_APPLE', v)
                        else:
                            sys.stderr.write('Ungrouped #define %s %s\n' % (m.group(1), m.group(2)))
                            continue
                        append_type_map(typeMap, 'token', v)
                m = pat_bitfield.search(line)
                if m:
                    v = (m.group(1), m.group(2))
                    if 'CL_MEM_USE' in v[0]:
                        append_type_map(typeMap, 'cl_mem_flags', v)
                    else:
                        sys.stderr.write('Ungrouped bitfield %s %s\n' % (m.group(1), m.group(2)))
            includeName = os.path.basename(filename)
            if type_name and includeName != 'cl.h' and not includeName in typeIncludes:
                typeIncludes.append(includeName)
예제 #58
0
    def doProcess(self, path, commits, isnew):
        for c in commits:
            isMerge = True;

            #get diff file content
            filestatus = self.gitOperation.getFileStatus(path, c[0]);
            if filestatus:
                if self.logonly:
                    for fs in filestatus:
                        if fs[0] == 'M':
                            isMerge = False;
                        elif fs[0] == 'C':
                            pass
                        elif fs[0] == 'R':
                            pass
                        elif fs[0] == 'A':
                            isMerge = False;
                        elif fs[0] == 'D':
                            isMerge = False;
                        else:
                            pass;
                else:
                    outpath = self.getCommitOutFilePath(path,c[0],c[1]);
                    oldpath = os.path.join(outpath,"old");
                    newpath = os.path.join(outpath,"new");

                    for fs in filestatus:
                        newfiledata="";
                        oldfiledata="";

                        if fs[0] == 'M':
                            #modify
                            newfiledata = self.gitOperation.getFileContent(path, c[0], fs[1]);
                            oldfiledata = self.gitOperation.getFileContent(path, c[0]+"^", fs[1]);
                        elif fs[0] == 'C':
                            print "C: path="+path+ " file="+fs[1]+" commit="+c[0]
                        elif fs[0] == 'R':
                            print "R: path="+path+ " file="+fs[1]+" commit="+c[0]
                        elif fs[0] == 'A':
                            #print "get file:"+fs[1] +" for "+c[0]
                            newfiledata = self.gitOperation.getFileContent(path, c[0], fs[1]);
                            #print "end of get file:"+fs[1];

                        elif fs[0] == 'D':
                            #print "get file:"+fs[1] +" for "+c[0]
                            oldfiledata = self.gitOperation.getFileContent(path, c[0]+"^", fs[1]);
                            #print "end of get file:"+fs[1];

                        else:
                            pass;

                        self.saveFile(outpath,"commit_info.txt","commit: "+c[0]+"\ndate: "+ time.strftime("%Y-%m-%d %X",time.localtime(string.atol(c[1]))) +"\nsubject: "+c[2]+"\nauthor: "+c[3]+"\n")
                        if newfiledata:
                            isMerge = False;
                            self.saveFile(newpath,fs[1],newfiledata);
                        if oldfiledata:
                            isMerge = False;
                            self.saveFile(oldpath,fs[1],oldfiledata);
            else:
                pass;


            #save commit log
            loginfo = c[2].replace("\"","@");
            author = c[3].replace("\"","@");
            try:
                loginfo = loginfo.encode("gb2312", "ignore")
            except Exception,e:
                try:
                    loginfo = loginfo.decode("ISO-8859-1","ignore").encode("gb2312", "ignore")
                except Exception,e:
                    loginfo = "??????????????????"
예제 #59
0
파일: app.py 프로젝트: hhy5861/dory-server

def usage():
    print """
    -h --help             print the help
    -l --list             Maximum number of connections
    -p --port             To monitor the port number  
    -s --socket-path      dory run socket path
    -t --topic            kafka create broker name
    -a --address          host connetion address
    """


for op, value in opts:
    if op in ("-l", "--list"):
        list = string.atol(value)
    elif op in ("-p", "--port"):
        port = string.atol(value)
    elif op in ("-a", "--address"):
        host = string.atol(value)
    elif op in ("-s", "--socket-path"):
        socketPath = string.atol(value)
    elif op in ("-t", "--topic"):
        topic = string.atol(value)
    elif op in ("-h", "-help"):
        usage()
        sys.exit()

dory = send.SendToDory()

예제 #60
0
                loginfo = loginfo.encode("gb2312", "ignore")
            except Exception,e:
                try:
                    loginfo = loginfo.decode("ISO-8859-1","ignore").encode("gb2312", "ignore")
                except Exception,e:
                    loginfo = "??????????????????"

            try:
                author = author.encode("gb2312", "ignore")
            except Exception,e:
                try:
                    author = author.decode("ISO-8859-1","ignore").encode("gb2312", "ignore")
                except Exception,e:
                    author = "??????"
            try:
                self.csv_fp.write(path+","+c[0]+",\""+time.strftime("%Y-%m-%d %X",time.localtime(string.atol(c[1])))+"\",\""+loginfo+"\""+",\""+author+"\"");
            except Exception,e:
                self.csv_fp.write(path+","+c[0]+",\""+time.strftime("%Y-%m-%d %X",time.localtime(string.atol(c[1])))+"\",\""+"??????????????????"+"\""+",\""+"??????"+"\"");
            

            if isMerge:
                self.csv_fp.write(",Yes");
            else:
                self.csv_fp.write(",No");

            if isnew:
                self.csv_fp.write(",Yes\n");
            else:
                self.csv_fp.write(",No\n");

class RepoPatch(RepoDiffBase):