Python types.IntType() Examples

The following are 30 code examples for showing how to use types.IntType(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module types , or try the search function .

Example 1
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 2
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 3
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: IPy.py    License: MIT License 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 4
Project: nightmare   Author: joxeankoret   File: __init__.py    License: GNU General Public License v2.0 6 votes vote down vote up
def addTrace(self, proc):
        """
        Add a new tracer to this group the "proc" argument
        may be either an long() for a pid (which we will attach
        to) or an already attached (and broken) tracer object.
        """

        if (type(proc) == types.IntType or
            type(proc) == types.LongType):
            trace = getTrace()
            self.initTrace(trace)
            self.traces[proc] = trace
            try:
                trace.attach(proc)
            except:
                self.delTrace(proc)
                raise

        else: # Hopefully a tracer object... if not.. you're dumb.
            trace = proc
            self.initTrace(trace)
            self.traces[trace.getPid()] = trace

        return trace 
Example 5
Project: pizza   Author: lammps   File: vec.py    License: GNU General Public License v2.0 6 votes vote down vote up
def write(self,filename,*keys):
    if len(keys):
      map = []
      for key in keys:
        if type(key) == types.IntType: map.append(key-1)
        elif self.ptr.has_key(key): map.append(self.ptr[key])
        else:
          count = 0
          for i in range(self.nvec):
	    if self.names[i].find(key) == 0:
	      count += 1
	      index = i
          if count == 1:
            map.append(index)
          else:
            raise StandardError, "unique vector %s not found" % key
    else:
      map = range(self.nvec)

    f = open(filename,"w")
    for i in xrange(self.nlen):
      for j in xrange(len(map)):
        print >>f,self.data[i][map[j]],
      print >>f
    f.close() 
Example 6
Project: encompass   Author: mazaclub   File: transaction.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = { }
        reverseLookup = { }
        i = 0
        uniqueNames = [ ]
        uniqueValues = [ ]
        for x in enumList:
            if type(x) == types.TupleType:
                x, i = x
            if type(x) != types.StringType:
                raise EnumException, "enum name is not a string: " + x
            if type(i) != types.IntType:
                raise EnumException, "enum value is not an integer: " + i
            if x in uniqueNames:
                raise EnumException, "enum name is not unique: " + x
            if i in uniqueValues:
                raise EnumException, "enum value is not unique for " + x
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 7
Project: aqua-monitor   Author: Deltares   File: _version200.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 8
Project: aqua-monitor   Author: Deltares   File: _version200.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 9
Project: aqua-monitor   Author: Deltares   File: _version200.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 10
Project: p2ptv-pi   Author: alesnav   File: NatCheckMsgHandler.py    License: MIT License 6 votes vote down vote up
def validNatCheckReplyMsg(self, ncr_data):
        if not type(ncr_data) == ListType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. It must be a list of parameters.'
            return False
        if not type(ncr_data[0]) == StringType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The first element in the list must be a string.'
            return False
        if not type(ncr_data[1]) == IntType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The second element in the list must be an integer.'
            return False
        if not type(ncr_data[2]) == IntType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The third element in the list must be an integer.'
            return False
        if not type(ncr_data[3]) == StringType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The forth element in the list must be a string.'
            return False
        if not type(ncr_data[4]) == IntType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The fifth element in the list must be an integer.'
            return False
        if not type(ncr_data[5]) == StringType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The sixth element in the list must be a string.'
            return False
        if not type(ncr_data[6]) == IntType:
            raise RuntimeError, 'NatCheckMsgHandler: received data is not valid. The seventh element in the list must be an integer.'
            return False 
Example 11
Project: p2ptv-pi   Author: alesnav   File: TorrentDef.py    License: MIT License 6 votes vote down vote up
def set_dht_nodes(self, nodes):
        if self.readonly:
            raise OperationNotPossibleAtRuntimeException()
        if type(nodes) != ListType:
            raise ValueError('nodes not a list')
        else:
            for node in nodes:
                if type(node) != ListType and len(node) != 2:
                    raise ValueError('node in nodes not a 2-item list: ' + `node`)
                if type(node[0]) != StringType:
                    raise ValueError('host in node is not string:' + `node`)
                if type(node[1]) != IntType:
                    raise ValueError('port in node is not int:' + `node`)

        self.input['nodes'] = nodes
        self.metainfo_valid = False 
Example 12
Project: baidupan_shell   Author: deadblue   File: _version133.py    License: GNU General Public License v2.0 6 votes vote down vote up
def int2bytes(number):
    """Converts a number to a string of bytes
    
    >>> bytes2int(int2bytes(123456789))
    123456789
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 13
Project: baidupan_shell   Author: deadblue   File: _version200.py    License: GNU General Public License v2.0 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 14
Project: NoobSec-Toolkit   Author: krintoxi   File: IPy.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 15
Project: NoobSec-Toolkit   Author: krintoxi   File: IPy.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __getitem__(self, key):
        """Called to implement evaluation of self[key].

        >>> ip=IP('127.0.0.0/30')
        >>> for x in ip:
        ...  print hex(x.int())
        ...
        0x7F000000L
        0x7F000001L
        0x7F000002L
        0x7F000003L
        >>> hex(ip[2].int())
        '0x7F000002L'
        >>> hex(ip[-1].int())
        '0x7F000003L'
        """

        if not isinstance(key, types.IntType) and not isinstance(key, types.LongType):
            raise TypeError
        if abs(key) >= self.len():
            raise IndexError
        if key < 0:
            key = self.len() - abs(key)

        return self.ip + long(key) 
Example 16
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    License: MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 17
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    License: MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 18
Project: bash-lambda-layer   Author: gkrizek   File: _version200.py    License: MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 19
Project: code   Author: ActiveState   File: recipe-473818.py    License: MIT License 6 votes vote down vote up
def new_looper(a, arg=None):
    """Helper function for nest()
    determines what sort of looper to make given a's type"""
    if isinstance(a,types.TupleType):
        if len(a) == 2:
            return RangeLooper(a[0],a[1])
        elif len(a) == 3:
            return RangeLooper(a[0],a[1],a[2])
    elif isinstance(a, types.BooleanType):
        return BooleanLooper(a)
    elif isinstance(a,types.IntType) or isinstance(a, types.LongType):
        return RangeLooper(a)
    elif isinstance(a, types.StringType) or isinstance(a, types.ListType):
        return ListLooper(a)
    elif isinstance(a, Looper):
        return a
    elif isinstance(a, types.LambdaType):
        return CalcField(a, arg) 
Example 20
Project: xbmc-addons-chinese   Author: taxigps   File: _version200.py    License: GNU General Public License v2.0 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 21
Project: xbmc-addons-chinese   Author: taxigps   File: _version200.py    License: GNU General Public License v2.0 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 22
Project: xbmc-addons-chinese   Author: taxigps   File: _version200.py    License: GNU General Public License v2.0 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 23
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 24
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 25
Project: ironpython2   Author: IronLanguages   File: test_optparse.py    License: Apache License 2.0 5 votes vote down vote up
def test_old_type_object(self):
        self.parser.add_option("-s", type=types.StringType)
        self.assertEqual(self.parser.get_option("-s").type, "string")
        self.parser.add_option("-x", type=types.IntType)
        self.assertEqual(self.parser.get_option("-x").type, "int")


# Custom type for testing processing of default values. 
Example 26
Project: web2board   Author: bq   File: Conftest.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _Have(context, key, have, comment = None):
    """
    Store result of a test in context.havedict and context.headerfilename.
    "key" is a "HAVE_abc" name.  It is turned into all CAPITALS and non-
    alphanumerics are replaced by an underscore.
    The value of "have" can be:
    1      - Feature is defined, add "#define key".
    0      - Feature is not defined, add "/* #undef key */".
             Adding "undef" is what autoconf does.  Not useful for the
             compiler, but it shows that the test was done.
    number - Feature is defined to this number "#define key have".
             Doesn't work for 0 or 1, use a string then.
    string - Feature is defined to this string "#define key have".
             Give "have" as is should appear in the header file, include quotes
             when desired and escape special characters!
    """
    key_up = key.upper()
    key_up = re.sub('[^A-Z0-9_]', '_', key_up)
    context.havedict[key_up] = have
    if have == 1:
        line = "#define %s 1\n" % key_up
    elif have == 0:
        line = "/* #undef %s */\n" % key_up
    elif isinstance(have, IntType):
        line = "#define %s %d\n" % (key_up, have)
    else:
        line = "#define %s %s\n" % (key_up, str(have))
    
    if comment is not None:
        lines = "\n/* %s */\n" % comment + line
    else:
        lines = "\n" + line

    if context.headerfilename:
        f = open(context.headerfilename, "a")
        f.write(lines)
        f.close()
    elif hasattr(context,'config_h'):
        context.config_h = context.config_h + lines 
Example 27
Project: BinderFilter   Author: dxwu   File: test_optparse.py    License: MIT License 5 votes vote down vote up
def test_old_type_object(self):
        self.parser.add_option("-s", type=types.StringType)
        self.assertEqual(self.parser.get_option("-s").type, "string")
        self.parser.add_option("-x", type=types.IntType)
        self.assertEqual(self.parser.get_option("-x").type, "int")


# Custom type for testing processing of default values. 
Example 28
Project: Computable   Author: ktraunmueller   File: c_spec.py    License: MIT License 5 votes vote down vote up
def init_info(self):
        scalar_converter.init_info(self)
        self.type_name = 'int'
        self.check_func = 'PyInt_Check'
        self.c_type = 'int'
        self.return_type = 'int'
        self.to_c_return = "(int) PyInt_AsLong(py_obj)"
        self.matching_types = [types.IntType] 
Example 29
Project: oss-ftp   Author: aliyun   File: test_optparse.py    License: MIT License 5 votes vote down vote up
def test_old_type_object(self):
        self.parser.add_option("-s", type=types.StringType)
        self.assertEqual(self.parser.get_option("-s").type, "string")
        self.parser.add_option("-x", type=types.IntType)
        self.assertEqual(self.parser.get_option("-x").type, "int")


# Custom type for testing processing of default values. 
Example 30
Project: txTrader   Author: rstms   File: tws.py    License: MIT License 5 votes vote down vote up
def query_bars(self, symbol, period, bar_start, bar_end, callback):
        id = self.next_id()
        self.output('bardata request id=%s' % id)
        # 30 second timeout for bar data
        cb = TWS_Callback(self, id, 'bardata', callback, 30)
        contract = self.create_contract(symbol, 'STK', 'SMART', 'SMART', 'USD')
        if type(bar_start) != types.IntType:
            bar_start = datetime.datetime.strptime(bar_start, '%Y-%m-%d %H:%M:%S')
        if type(bar_end) != types.IntType:
            bar_end = datetime.datetime.strptime(bar_end, '%Y-%m-%d %H:%M:%S')
        # try:
        if 1 == 1:
            endDateTime = bar_end.strftime('%Y%m%d %H:%M:%S')
            durationStr = '%s S' % (bar_end - bar_start).seconds
            barSizeSetting = {'1': '1 min', '5': '5 mins'}[
                str(period)]  # legal period values are '1' and '5'
            whatToShow = 'TRADES'
            useRTH = 0
            formatDate = 1
            self.bardata_callbacks.append(cb)
            self.output('edt:%s ds:%s bss:%s' %
                        (endDateTime, durationStr, barSizeSetting))
            self.tws_conn.reqHistoricalData(
                id, contract, endDateTime, durationStr, barSizeSetting, whatToShow, useRTH, formatDate)
        # except:
        if 1 == 2:
            cb.complete(['Error', 'query_bars(%s) failed!' % repr(
                (bar_symbol, bar_period, bar_start, bar_end)), 'Count: 0'])