Python types.NoneType() Examples

The following are 30 code examples of types.NoneType(). 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 also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: thutil.py    From Depth-Map-Prediction with GNU General Public License v3.0 6 votes vote down vote up
def breakpoint(output, vars=None, cond=lambda v: True, grad=True):
    tb = tuple(traceback.extract_stack()[:-1])
    py_vars = {}
    if type(vars) not in (tuple, list, dict, types.NoneType):
        raise ValueError('vars keyword arg must be None, dict, list or tuple')
    if not isinstance(vars, dict):
        frame_locals = inspect.stack()[1][0].f_locals
        if vars is not None:
            frame_locals = dict((name, val)
                                for (name, val) in frame_locals.iteritems()
                                if name in vars or val in vars)
        vars = frame_locals
    assert isinstance(vars, dict)
    th_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if isinstance(val, _theano_types))
    py_vars = dict((name, val) for (name, val) in vars.iteritems()
                               if name not in th_vars)
    (th_var_names, th_var_vals) = zip(*th_vars.iteritems())
    return Breakpoint(th_var_names, cond, tb, py_vars, grad) \
                     (output, *th_var_vals) 
Example #2
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 6 votes vote down vote up
def getReachedSimulationTime(self):
		''' Read the current simulation time during a simulation
		'''
		sim = None
		rTime = None
		try:
			if not type(self._doc) is types.NoneType:
				sim = self._doc.Application
				sim.Interactive = False
				if self._doc.SolutionState > simReady:
					rTime = self._doc.Lookup('t').LastValue
		except:
			rTime = None
		finally:
			if not type(sim) is types.NoneType:
				sim.Interactive = True

		return rTime 
Example #3
Source File: utils.py    From backend with GNU General Public License v2.0 6 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
  """
  Returns a bytestring version of 's', encoded as specified in 'encoding'.

  If strings_only is True, don't convert (some) non-string-like objects.
  """
  if strings_only and isinstance(s, (types.NoneType, int)):
    return s
  if not isinstance(s, basestring):
    try:
      return str(s)
    except UnicodeEncodeError:
      if isinstance(s, Exception):
        # An Exception subclass containing non-ASCII data that doesn't
        # know how to print itself properly. We shouldn't raise a
        # further exception.
        return ' '.join([smart_str(arg, encoding, strings_only,
                                   errors) for arg in s])
      return unicode(s).encode(encoding, errors)
  elif isinstance(s, unicode):
    return s.encode(encoding, errors)
  elif s and encoding != 'utf-8':
    return s.decode('utf-8', errors).encode(encoding, errors)
  else:
    return s 
Example #4
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 6 votes vote down vote up
def simulate(self):
		''' Run a simulation of a Modelica/SimulationX model
		'''
		sim = None
		try:
			doc = win32com.client.Dispatch(pythoncom.CoUnmarshalInterface(self._marshalled_doc, pythoncom.IID_IDispatch))
			self._marshalled_doc.Seek(0, pythoncom.STREAM_SEEK_SET)
			if not type(doc) is types.NoneType:
				sim = doc.Application
				sim.Interactive = False
				self._simulate_sync(doc)
		except win32com.client.pywintypes.com_error:
			print 'SimulationX: COM error.'
			raise(SimulatorBase.Stopping)
		except:
			print 'SimulationX: Unhandled exception.'
			import traceback
			print traceback.format_exc()
			raise(SimulatorBase.Stopping)
		finally:
			if not type(sim) is types.NoneType:
				sim.Interactive = True 
Example #5
Source File: jsonobject.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def _dump_list(lst):
    nlst = []
    for val in lst:
        if _is_unsupported_type(val):
            raise NoneSupportedTypeError('Cannot dump val: %s, type: %s, list dump: %s' % (val, type(val), lst))
        
        if _is_primitive_types(val):
            nlst.append(val)
        elif isinstance(val, types.DictType):
            nlst.append(val)
        elif isinstance(val, types.ListType):        
            tlst = _dump_list(val)
            nlst.append(tlst)
        elif isinstance(val, types.NoneType):
            pass
        else:
            nmap = _dump(val)
            nlst.append(nmap)
    
    return nlst 
Example #6
Source File: jsonobject.py    From zstack-utility with Apache License 2.0 6 votes vote down vote up
def _dump(obj):
    if _is_primitive_types(obj): return simplejson.dumps(obj, ensure_ascii=True)
    
    ret = {}
    items = obj.iteritems() if isinstance(obj, types.DictionaryType) else obj.__dict__.iteritems()
    #items = inspect.getmembers(obj)
    for key, val in items:
        if key.startswith('_'): continue
        
        if _is_unsupported_type(obj):
            raise NoneSupportedTypeError('cannot dump %s, type:%s, object dict: %s' % (val, type(val), obj.__dict__))
        
        if _is_primitive_types(val):
            ret[key] = val
        elif isinstance(val, types.DictType):
            ret[key] = val
        elif isinstance(val, types.ListType):
            nlst = _dump_list(val)
            ret[key] = nlst
        elif isinstance(val, types.NoneType):
            pass
        else:
            nmap = _dump(val)
            ret[key] = nmap
    return ret 
Example #7
Source File: response.py    From esdc-ce with Apache License 2.0 6 votes vote down vote up
def to_string(x, quote_string=True):
    """Format value so it can be used for task log detail"""
    if isinstance(x, string_types):
        if quote_string:
            return "'%s'" % x
        else:
            return '%s' % x
    elif isinstance(x, bool):
        return str(x).lower()
    elif isinstance(x, (int, float)):
        return str(x)
    elif isinstance(x, NoneType):
        return 'null'
    elif isinstance(x, dict):
        return to_string(','.join('%s:%s' % (to_string(k, quote_string=False), to_string(v, quote_string=False))
                                  for k, v in iteritems(x)))
    elif isinstance(x, (list, tuple)):
        return to_string(','.join(to_string(i, quote_string=False) for i in x))
    return to_string(str(x)) 
Example #8
Source File: http_client.py    From clusterdock with Apache License 2.0 6 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    elif not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([smart_str(arg, encoding, strings_only,
                        errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s 
Example #9
Source File: recipe-68430.py    From code with MIT License 6 votes vote down vote up
def getRow(self, key):
        """Gets or creates the row subdirectory matching key.

        Note that the "rows" returned by this method need not be complete.
        They will contain only the items corresponding to the keys that
        have actually been inserted.  Other items will not be present,
        in particular they will not be represented by None."""
        
        # Get whatever is located at the first key
        thing = self.get(key, None)

        # If thing is a dictionary, return it.
        if isinstance(thing, dictionary):
            row = thing

        # If thing is None, create a new dictionary and return that.
        elif isinstance(thing, types.NoneType):
            row = {}
            self[key] = row

        # If thing is neither a dictionary nor None, then it's an error.
        else:
            row = None
            raise RaggedArrayException, "getRow: thing was not a dictionary."
        return row 
Example #10
Source File: jelly.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "datetime": 1,
                             "time": 1,
                             "date": 1,
                             "timedelta": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {} 
Example #11
Source File: ebs.py    From flocker with Apache License 2.0 6 votes vote down vote up
def __init__(self, requested, discovered):
        """
        :param FilePath requested: The requested device name.
        :param discovered: A ``FilePath`` giving the path of the device which
            was discovered on the system or ``None`` if no new device was
            discovered at all.
        """
        # It would be cool to replace this logic with pyrsistent typed fields
        # but Exception and PClass have incompatible layouts (you can't have an
        # exception that's a PClass).
        if not isinstance(requested, FilePath):
            raise TypeError(
                "requested must be FilePath, not {}".format(type(requested))
            )
        if not isinstance(discovered, (FilePath, NoneType)):
            raise TypeError(
                "discovered must be None or FilePath, not {}".format(
                    type(discovered)
                )
            )

        self.requested = requested
        self.discovered = discovered 
Example #12
Source File: routing.py    From PCR-GLOBWB_model with GNU General Public License v3.0 6 votes vote down vote up
def getRoutingParamAvgDischarge(self, avgDischarge, dist2celllength = None):
        # obtain routing parameters based on average (longterm) discharge
        # output: channel dimensions and 
        #         characteristicDistance (for accuTravelTime input)
        
        yMean = self.eta * pow (avgDischarge, self.nu ) # avgDischarge in m3/s
        wMean = self.tau * pow (avgDischarge, self.phi)
 
        wMean =   pcr.max(wMean,0.01) # average flow width (m) - this could be used as an estimate of channel width (assuming rectangular channels)
        wMean = pcr.cover(wMean,0.01)
        yMean =   pcr.max(yMean,0.01) # average flow depth (m) - this should NOT be used as an estimate of channel depth
        yMean = pcr.cover(yMean,0.01)
        
        # option to use constant channel width (m)
        if not isinstance(self.predefinedChannelWidth,types.NoneType):\
           wMean = pcr.cover(self.predefinedChannelWidth, wMean)
        #
        # minimum channel width (m)
        wMean = pcr.max(self.minChannelWidth, wMean)

        return (yMean, wMean) 
Example #13
Source File: conf.py    From ANALYSE with GNU Affero General Public License v3.0 6 votes vote down vote up
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_unicode, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring,):
        if hasattr(s, '__unicode__'):
            s = unicode(s)
        else:
            s = unicode(str(s), encoding, errors)
    elif not isinstance(s, unicode):
        s = unicode(s, encoding, errors)
    return s 
Example #14
Source File: conf.py    From ANALYSE with GNU Affero General Public License v3.0 6 votes vote down vote up
def force_unicode(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Similar to smart_unicode, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if not isinstance(s, basestring,):
        if hasattr(s, '__unicode__'):
            s = unicode(s)
        else:
            s = unicode(str(s), encoding, errors)
    elif not isinstance(s, unicode):
        s = unicode(s, encoding, errors)
    return s 
Example #15
Source File: util.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str,), "Cache type must be a string."),
        ('enabled', (bool, types.NoneType), "enabled must be true/false "
         "if present."),
        ('expire', (int, types.NoneType), "expire must be an integer representing "
         "how many seconds the cache is valid for"),
        ('regions', (list, tuple, types.NoneType), "Regions must be a "
         "comma seperated list of valid regions"),
        ('key_length', (int, types.NoneType), "key_length must be an integer "
         "which indicates the longest a key can be before hashing"),
    ]
    return verify_rules(params, rules) 
Example #16
Source File: util.py    From malwareHunter with GNU General Public License v2.0 6 votes vote down vote up
def coerce_cache_params(params):
    rules = [
        ('data_dir', (str, types.NoneType), "data_dir must be a string "
         "referring to a directory."),
        ('lock_dir', (str, types.NoneType), "lock_dir must be a string referring to a "
         "directory."),
        ('type', (str,), "Cache type must be a string."),
        ('enabled', (bool, types.NoneType), "enabled must be true/false "
         "if present."),
        ('expire', (int, types.NoneType), "expire must be an integer representing "
         "how many seconds the cache is valid for"),
        ('regions', (list, tuple, types.NoneType), "Regions must be a "
         "comma seperated list of valid regions"),
        ('key_length', (int, types.NoneType), "key_length must be an integer "
         "which indicates the longest a key can be before hashing"),
    ]
    return verify_rules(params, rules) 
Example #17
Source File: newjelly.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        """SecurityOptions()
        Initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        self.allowedModules = {}
        self.allowedClasses = {} 
Example #18
Source File: nmap.py    From WrapMap with GNU General Public License v3.0 5 votes vote down vote up
def wait(self, timeout=None):
        """
        Wait for the current scan process to finish, or timeout
        """

        assert type(timeout) in (types.IntType, types.NoneType), 'Wrong type for [timeout], should be an int or None [was {0}]'.format(type(timeout))

        self._process.join(timeout)
        return 
Example #19
Source File: encoding.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        types.NoneType,
        int, long,
        datetime.datetime, datetime.date, datetime.time,
        float, Decimal)
    ) 
Example #20
Source File: encoding.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def smart_str(s, encoding='utf-8', strings_only=False, errors='strict'):
    """
    Returns a bytestring version of 's', encoded as specified in 'encoding'.

    If strings_only is True, don't convert (some) non-string-like objects.
    """
    if strings_only and isinstance(s, (types.NoneType, int)):
        return s
    if isinstance(s, Promise):
        return unicode(s).encode(encoding, errors)
    elif not isinstance(s, basestring):
        try:
            return str(s)
        except UnicodeEncodeError:
            if isinstance(s, Exception):
                # An Exception subclass containing non-ASCII data that doesn't
                # know how to print itself properly. We shouldn't raise a
                # further exception.
                return ' '.join([smart_str(arg, encoding, strings_only,
                        errors) for arg in s])
            return unicode(s).encode(encoding, errors)
    elif isinstance(s, unicode):
        return s.encode(encoding, errors)
    elif s and encoding != 'utf-8':
        return s.decode('utf-8', errors).encode(encoding, errors)
    else:
        return s 
Example #21
Source File: SimulationXIsx.py    From PySimulator with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getFileInfos(self):
		with zipfile.ZipFile(self._fullFileName, 'r') as model:
			with model.open('docProps/app.xml', 'rU') as app:
				dom = minidom.parseString(app.read())
				nodes = dom.getElementsByTagName('AppVersion')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['SimulationX'] = nodes[0].firstChild.nodeValue
				nodes = dom.getElementsByTagName('Company')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Company'] = nodes[0].firstChild.nodeValue
			with model.open('docProps/core.xml', 'rU') as core:
				dom = minidom.parseString(core.read())
				nodes = dom.getElementsByTagName('dc:title')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Title'] = nodes[0].firstChild.nodeValue
				nodes = dom.getElementsByTagName('dc:subject')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Subject'] = nodes[0].firstChild.nodeValue
				nodes = dom.getElementsByTagName('dc:creator')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Creator'] = nodes[0].firstChild.nodeValue
				nodes = dom.getElementsByTagName('dc:keywords')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Keywords'] = nodes[0].firstChild.nodeValue
				nodes = dom.getElementsByTagName('dc:description')
				if len(nodes) > 0:
					if type(nodes[0].firstChild) is not types.NoneType:
						self._fileInfo['Description'] = nodes[0].firstChild.nodeValue
		return self._fileInfo 
Example #22
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setVariableTree(self):
		''' Generate variable tree
		'''
		sim = None
		try:
			if not type(self._doc) is types.NoneType:
				sim = self._doc.Application
				sim.Interactive = False
				self._fillTree(self._doc, self._doc)
		except win32com.client.pywintypes.com_error:
			print 'SimulationX: COM error.'
		finally:
			if not type(sim) is types.NoneType:
				sim.Interactive = True 
Example #23
Source File: jelly.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        """
        SecurityOptions() initialize.
        """
        # I don't believe any of these types can ever pose a security hazard,
        # except perhaps "reference"...
        self.allowedTypes = {"None": 1,
                             "bool": 1,
                             "boolean": 1,
                             "string": 1,
                             "str": 1,
                             "int": 1,
                             "float": 1,
                             "datetime": 1,
                             "time": 1,
                             "date": 1,
                             "timedelta": 1,
                             "NoneType": 1}
        if hasattr(types, 'UnicodeType'):
            self.allowedTypes['unicode'] = 1
        if decimal is not None:
            self.allowedTypes['decimal'] = 1
        self.allowedTypes['set'] = 1
        self.allowedTypes['frozenset'] = 1
        self.allowedModules = {}
        self.allowedClasses = {} 
Example #24
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _get_jsockaddr2(address_object, family, sock_type, proto, flags):
    # Is this an object that was returned from getaddrinfo? If so, it already contains an InetAddress
    if isinstance(address_object, _ip_address_t):
        return java.net.InetSocketAddress(address_object.jaddress, address_object[1])
    # The user passed an address tuple, not an object returned from getaddrinfo
    # So we must call getaddrinfo, after some translations and checking
    if address_object is None:
        address_object = ("", 0)
    error_message = "Address must be a 2-tuple (ipv4: (host, port)) or a 4-tuple (ipv6: (host, port, flow, scope))"
    if not isinstance(address_object, tuple) or \
       ((family == AF_INET and len(address_object) != 2) or \
        (family == AF_INET6 and len(address_object) not in [2,4] )) or \
       not isinstance(address_object[0], (basestring, NoneType)) or \
       not isinstance(address_object[1], (int, long)):
        raise TypeError(error_message)
    if len(address_object) == 4 and not isinstance(address_object[3], (int, long)):
        raise TypeError(error_message)
    hostname = address_object[0]
    if hostname is not None:
        hostname = hostname.strip()
    port = address_object[1]
    if family == AF_INET and sock_type == SOCK_DGRAM and hostname == "<broadcast>":
        hostname = INADDR_BROADCAST
    if hostname in ["", None]:
        if flags & AI_PASSIVE:
            hostname = {AF_INET: INADDR_ANY, AF_INET6: IN6ADDR_ANY_INIT}[family]
        else:
            hostname = "localhost"
    if isinstance(hostname, unicode):
        hostname = encodings.idna.ToASCII(hostname)
    addresses = getaddrinfo(hostname, port, family, sock_type, proto, flags)
    if len(addresses) == 0:
        raise gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed')
    return java.net.InetSocketAddress(addresses[0][4].jaddress, port) 
Example #25
Source File: encoding.py    From Serverless-Deep-Learning-with-TensorFlow-and-AWS-Lambda with MIT License 5 votes vote down vote up
def is_protected_type(obj):
    """Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    force_unicode(strings_only=True).
    """
    return isinstance(obj, (
        six.integer_types +
        (types.NoneType,
         datetime.datetime, datetime.date, datetime.time,
         float, Decimal))
    ) 
Example #26
Source File: serializers.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def _is_protected_type(obj):
    """
    True if the object is a native data type that does not need to be serialized further.
    """
    return isinstance(obj, six.string_types + six.integer_types + (
        types.NoneType,
        datetime.datetime, datetime.date, datetime.time,
        float, Decimal,
    )) 
Example #27
Source File: _socket.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def _get_jsockaddr2(address_object, family, sock_type, proto, flags):
    # Is this an object that was returned from getaddrinfo? If so, it already contains an InetAddress
    if isinstance(address_object, _ip_address_t):
        return java.net.InetSocketAddress(address_object.jaddress, address_object[1])
    # The user passed an address tuple, not an object returned from getaddrinfo
    # So we must call getaddrinfo, after some translations and checking
    if address_object is None:
        address_object = ("", 0)
    error_message = "Address must be a 2-tuple (ipv4: (host, port)) or a 4-tuple (ipv6: (host, port, flow, scope))"
    if not isinstance(address_object, tuple) or \
       ((family == AF_INET and len(address_object) != 2) or \
        (family == AF_INET6 and len(address_object) not in [2,4] )) or \
       not isinstance(address_object[0], (basestring, NoneType)) or \
       not isinstance(address_object[1], (int, long)):
        raise TypeError(error_message)
    if len(address_object) == 4 and not isinstance(address_object[3], (int, long)):
        raise TypeError(error_message)
    hostname = address_object[0]
    if hostname is not None:
        hostname = hostname.strip()
    port = address_object[1]
    if family == AF_INET and sock_type == SOCK_DGRAM and hostname == "<broadcast>":
        hostname = INADDR_BROADCAST
    if hostname in ["", None]:
        if flags & AI_PASSIVE:
            hostname = {AF_INET: INADDR_ANY, AF_INET6: IN6ADDR_ANY_INIT}[family]
        else:
            hostname = "localhost"
    if isinstance(hostname, unicode):
        hostname = encodings.idna.ToASCII(hostname)
    addresses = getaddrinfo(hostname, port, family, sock_type, proto, flags)
    if len(addresses) == 0:
        raise gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed')
    return java.net.InetSocketAddress(addresses[0][4].jaddress, port) 
Example #28
Source File: nmap.py    From WrapMap with GNU General Public License v3.0 5 votes vote down vote up
def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None):
        """
        Scan given hosts in a separate process and return host by host result using callback function

        PortScannerError exception from standard nmap is catched and you won't know about it

        hosts = string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        ports = string for ports as nmap use it '22,53,110,143-4564'
        arguments = string of arguments for nmap '-sU -sX -sC'
        callback = callback function which takes (host, scan_data) as arguments
        """

        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        assert type(ports) in types.StringTypes+(types.NoneType,), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports))
        assert type(arguments) in types.StringTypes, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments))
        #assert type(callback) in (types.FunctionType, types.NoneType), 'Wrong type for [callback], should be a function or None [was {0}]'.format(type(callback))
        
        def scan_progressive(self, hosts, ports, arguments, callback):
            for host in self._nm.listscan(hosts):
                try:
                    scan_data = self._nm.scan(host, ports, arguments)
                except PortScannerError:
                    print "error"
                    pass
                if callback is not None and callable(callback):
                    callback(host, scan_data)
            return

        self._process = Process(
            target=scan_progressive,
            args=(self, hosts, ports, arguments, callback)
            )
        self._process.daemon = False
        self._process.start()
        return 
Example #29
Source File: _socket.py    From CTFCrackTools with GNU General Public License v3.0 5 votes vote down vote up
def _get_jsockaddr2(address_object, family, sock_type, proto, flags):
    # Is this an object that was returned from getaddrinfo? If so, it already contains an InetAddress
    if isinstance(address_object, _ip_address_t):
        return java.net.InetSocketAddress(address_object.jaddress, address_object[1])
    # The user passed an address tuple, not an object returned from getaddrinfo
    # So we must call getaddrinfo, after some translations and checking
    if address_object is None:
        address_object = ("", 0)
    error_message = "Address must be a 2-tuple (ipv4: (host, port)) or a 4-tuple (ipv6: (host, port, flow, scope))"
    if not isinstance(address_object, tuple) or \
       ((family == AF_INET and len(address_object) != 2) or \
        (family == AF_INET6 and len(address_object) not in [2,4] )) or \
       not isinstance(address_object[0], (basestring, NoneType)) or \
       not isinstance(address_object[1], (int, long)):
        raise TypeError(error_message)
    if len(address_object) == 4 and not isinstance(address_object[3], (int, long)):
        raise TypeError(error_message)
    hostname = address_object[0]
    if hostname is not None:
        hostname = hostname.strip()
    port = address_object[1]
    if family == AF_INET and sock_type == SOCK_DGRAM and hostname == "<broadcast>":
        hostname = INADDR_BROADCAST
    if hostname in ["", None]:
        if flags & AI_PASSIVE:
            hostname = {AF_INET: INADDR_ANY, AF_INET6: IN6ADDR_ANY_INIT}[family]
        else:
            hostname = "localhost"
    if isinstance(hostname, unicode):
        hostname = encodings.idna.ToASCII(hostname)
    addresses = getaddrinfo(hostname, port, family, sock_type, proto, flags)
    if len(addresses) == 0:
        raise gaierror(errno.EGETADDRINFOFAILED, 'getaddrinfo failed')
    return java.net.InetSocketAddress(addresses[0][4].jaddress, port) 
Example #30
Source File: SimulationX.py    From PySimulator with GNU Lesser General Public License v3.0 5 votes vote down vote up
def close(self):
		''' Close a Modelica/SimulationX model
		'''
		sim = None
		try:
			doc = win32com.client.Dispatch(pythoncom.CoUnmarshalInterface(self._marshalled_doc, pythoncom.IID_IDispatch))
			self._marshalled_doc.Seek(0, pythoncom.STREAM_SEEK_SET)
			if not type(doc) is types.NoneType:
				sim = doc.Application
				sim.Interactive = False
				doc.Close(False)
				doc = None
				pythoncom.CoReleaseMarshalData(self._marshalled_doc)
				self._marshalled_doc = None
		except win32com.client.pywintypes.com_error:
			print 'SimulationX: COM error.'
		except:
			print 'SimulationX: Unhandled exception.'
			import traceback
			print traceback.format_exc()
		finally:
			SimulatorBase.Model.close(self)
			if not type(sim) is types.NoneType:
				sim.Interactive = True
				sim = None

		if hasattr(self, 'variableTree'):
			del self.variableTree
		if hasattr(self, '_availableIntegrationAlgorithms'):
			del self._availableIntegrationAlgorithms
		if hasattr(self, '_solverByName'):
			del self._solverByName
		if hasattr(self, '_IntegrationAlgorithmHasFixedStepSize'):
			del self._IntegrationAlgorithmHasFixedStepSize
		if hasattr(self, '_IntegrationAlgorithmCanProvideStepSizeResults'):
			del self._IntegrationAlgorithmCanProvideStepSizeResults