Example #1
1
 def serialize(self, buff):
     """
 serialize message into buffer
 :param buff: buffer, ``StringIO``
 """
     try:
         _x = self.agent_one
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         buff.write(struct.pack("<I%ss" % length, length, _x))
         _x = self.agent_two
         length = len(_x)
         if python3 or type(_x) == unicode:
             _x = _x.encode("utf-8")
             length = len(_x)
         buff.write(struct.pack("<I%ss" % length, length, _x))
         _x = self
         buff.write(
             _struct_6d.pack(_x.rotationx, _x.rotationy, _x.angle, _x.referencex, _x.referencey, _x.evaluation)
         )
     except struct.error as se:
         self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
     except TypeError as te:
         self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
Example #2
0
    def _add_delta(self, delta):
        """
        Add a timedelta-like, Tick, or TimedeltaIndex-like object
        to self.

        Parameters
        ----------
        delta : timedelta, np.timedelta64, Tick, TimedeltaArray, TimedeltaIndex

        Returns
        -------
        result : same type as self

        Notes
        -----
        The result's name is set outside of _add_delta by the calling
        method (__add__ or __sub__)
        """
        if isinstance(delta, (Tick, timedelta, np.timedelta64)):
            new_values = self._add_delta_td(delta)
        elif isinstance(delta, TimedeltaArrayMixin):
            new_values = self._add_delta_tdi(delta)
        elif is_timedelta64_dtype(delta):
            # ndarray[timedelta64] --> wrap in TimedeltaArray/Index
            delta = type(self)(delta)
            new_values = self._add_delta_tdi(delta)
        else:
            raise TypeError("cannot add the type {0} to a TimedeltaIndex"
                            .format(type(delta)))

        return type(self)(new_values, freq='infer')
Example #3
0
def showCumulOverlap(mode, modes, *args, **kwargs):
    """Show cumulative overlap using :func:`~matplotlib.pyplot.plot`.

    :type mode: :class:`.Mode`, :class:`.Vector`
    :arg modes: multiple modes
    :type modes: :class:`.ModeSet`, :class:`.ANM`, :class:`.GNM`, :class:`.PCA`
    """

    import matplotlib.pyplot as plt
    if not isinstance(mode, (Mode, Vector)):
        raise TypeError('mode must be NMA, ModeSet, Mode or Vector, not {0}'
                        .format(type(mode)))
    if not isinstance(modes, (NMA, ModeSet)):
        raise TypeError('modes must be NMA, ModeSet, or Mode, not {0}'
                        .format(type(modes)))
    cumov = (calcOverlap(mode, modes) ** 2).cumsum() ** 0.5
    if isinstance(modes, NMA):
        arange = np.arange(0.5, len(modes)+0.5)
    else:
        arange = modes.getIndices() + 0.5
    show = plt.plot(arange, cumov, *args, **kwargs)
    plt.title('Cumulative overlap with {0}'.format(str(mode)))
    plt.xlabel('{0} mode index'.format(modes))
    plt.ylabel('Cumulative overlap')
    plt.axis((arange[0]-0.5, arange[-1]+0.5, 0, 1))
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #4
0
    def stepDone(self, result, step):
        """This method is called when the BuildStep completes. It is passed a
        status object from the BuildStep and is responsible for merging the
        Step's results into those of the overall Build."""

        terminate = False
        text = None
        if type(result) == types.TupleType:
            result, text = result
        assert type(result) == type(SUCCESS)
        log.msg(" step '%s' complete: %s" % (step.name, Results[result]))
        self.results.append(result)
        if text:
            self.text.extend(text)
        if not self.remote:
            terminate = True
        if result == FAILURE:
            if step.warnOnFailure:
                if self.result != FAILURE:
                    self.result = WARNINGS
            if step.flunkOnFailure:
                self.result = FAILURE
            if step.haltOnFailure:
                terminate = True
        elif result == WARNINGS:
            if step.warnOnWarnings:
                if self.result != FAILURE:
                    self.result = WARNINGS
            if step.flunkOnWarnings:
                self.result = FAILURE
        elif result == EXCEPTION:
            self.result = EXCEPTION
            terminate = True
        return terminate
Example #5
0
 def RandomGraph(self, nodes, edges, maxweight = 100.0):
     """
     Generates a graph of random edges.
     
     @param nodes: list of nodes or number of nodes in the random graph
     @param edges: number of edges to generate in the random graph
     @type edges: integer
     @param maxweight: maximum weight of each edge. default = 100.0
     @type maxweight: float
     """
     import random
     nodes_size = 0
     if type(nodes) == int:
         adjacency = [range(nodes)]
         nodes_size = nodes
         for node in range(nodes):
             adjacency.append([0 for x in range(nodes)])
     elif type(nodes) == list:
         adjacency = nodes
         nodes_size = len(nodes)
         for node in range(nodes_size):
             adjacency.append([0 for x in range(nodes_size)])
     else: raise FunctionParameterTypeError('nodes can only be a list \
             or integer')
     count = 0
     while count <= edges:
         edge = (int(random.uniform(0, nodes_size)) + 1, 
                 int(random.uniform(0, nodes_size)),
                 int(random.uniform(0, 1) * maxweight))
         if adjacency[edge[0]][edge[1]] == 0:
             adjacency[edge[0]][edge[1]] = edge[2]
             count = count + 1
     self.makeGraphFromAdjacency(adjacency)
Example #6
0
 def __delitem__(self, index):
     if type(index) is int:
         del self.dict[self.list[index].name]
         del self.list[index]
     elif type(index) is str:
         self.list.remove(self[index]) #This must come first because we are using the dict to fetch the item
         del self.dict[index]
Example #7
0
    def write_24bit_int(self, n):
        """
        Writes a 24 bit integer to the stream.

        @since: 0.4
        @param n: 24 bit integer
        @type n: C{int}
        @raise TypeError: Unexpected type for int C{n}.
        @raise OverflowError: Not in range.
        """
        if type(n) not in python.int_types:
            raise TypeError('expected an int (got:%r)' % (type(n),))

        if not -8388608 <= n <= 8388607:
            raise OverflowError("n is out of range")

        order = None

        if not self._is_big_endian():
            order = [0, 8, 16]
        else:
            order = [16, 8, 0]

        if n < 0:
            n += 0x1000000

        for x in order:
            self.write_uchar((n >> x) & 0xff)
Example #8
0
def SetProperties( msg, propDict):
	""" Given a Python dictionary, set the objects properties.
	
	If the dictionary key is a string, then a property ID is queried
	otherwise the ID is assumed native.
	
	Coded for maximum efficiency wrt server calls - ie, maximum of
	2 calls made to the object, regardless of the dictionary contents
	(only 1 if dictionary full of int keys)
	"""

	newProps = []
	# First pass over the properties we should get IDs for.
	for key, val in propDict.iteritems():
		if type(key) in [str, unicode]:
			newProps.append((mapi.PS_PUBLIC_STRINGS, key))
	# Query for the new IDs
	if newProps: newIds = msg.GetIDsFromNames(newProps, mapi.MAPI_CREATE)
	newIdNo = 0
	newProps = []
	for key, val in propDict.iteritems():
		if type(key) in [str, unicode]:
			type_val=type(val)
			if type_val in [str, unicode]:
				tagType = mapitags.PT_UNICODE
			elif type_val==IntType:
				tagType = mapitags.PT_I4
			elif type_val==TimeType:
				tagType = mapitags.PT_SYSTIME
			else:
				raise ValueError("The type of object %s(%s) can not be written" % (repr(val),type_val))
			key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo]))
			newIdNo = newIdNo + 1
		newProps.append( (key, val) )
	msg.SetProps(newProps)
Example #9
0
def convert_ops(ops, s, start, idxmap):
    syms = []
    for op in ops:
        if type(op) in ops_map:
            syms.append(ops_map[type(op)])
        else:
            print("[WARNING] operator %s is missing from ops_map, "
                  "please report the bug on GitHub" % op)

    i = start
    j = 0
    ret = []
    while i < len(s) and j < len(syms):
        oplen = len(syms[j])
        if s[i:i+oplen] == syms[j]:
            op_node = Name(syms[j], None)
            op_node.node_start = i
            op_node.node_end = i+oplen
            op_node.lineno, op_node.col_offset = map_line_col(idxmap, i)
            ret.append(op_node)
            j += 1
            i = op_node.node_end
        else:
            i += 1
    return ret
Example #10
0
 def line(self):
     x1 = self.getleft()
     x2 = self.getright()
     align = self.align
     y = self.y
     
     if len(self.items) != 0 and type(self.items[-1]) == tuple:
         del self.items[-1]
     
     w = 0
     for e in self.items:
         if type(e) == tuple: w += e[0]
         else: w += e.rect.w
         
     if align == -1: x = x1
     elif align == 0: 
         x = x1 + ((x2-x1)-w)/2
         self.fit = 0
     elif align == 1: x = x2 - w
         
     for e in self.items:
         if type(e) == tuple: x += e[0]
         else:
             e.rect.x,e.rect.y = x,y
             self.widgets.append(e)
             x += e.rect.w
     
     self.items = []
     self.y = self.y + self.h
     self.x = self.getleft()
     self.h = 0
Example #11
0
    def __init__(self, name, args=[], opts=[], **kwargs):
        """
        Base class for POV objects.

        @param name: POV object name
        @param args: compulsory (comma separated?) pov args XX commas don't seem to matter?
        @param opts: eg. CSG items
        @param kwargs: key value pairs
        """
        #print "Item",name,args,opts,kwargs
        self.name = name

        args = list(args)
        for i in range(len(args)):
            args[i] = map_arg(args[i])
        self.args = flatten(args)

        opts = list(opts)
        for i in range(len(opts)):
            opts[i] = map_arg(opts[i])
        self.opts = flatten(opts)

        self.kwargs = dict(kwargs)  # take a copy
        for key, val in self.kwargs.items():
            if type(val) == tuple or type(val) == list:
                self.kwargs[key] = map_arg(val)
Example #12
0
def parseString2Pagenum(parent, string, nodialog=False):
    """ Parse a string with a list of pagenumbers to an integer list with
        page numbers.
        e.g. "1-3,5,7" --> [1,2,3,5,7]
        parent is important
    """
    listFull = string.split(",")
    PageNumbers = list()
    try:
        for item in listFull:
            pagerange = item.split("-")
            start = pagerange[0].strip()
            start = int(filter(type(start).isdigit, start))
            end = pagerange[-1].strip()
            end = int(filter(type(end).isdigit, end))
            for i in np.arange(end-start+1)+start:
                PageNumbers.append(i)
        PageNumbers.sort()
        return PageNumbers
    except:
        if nodialog is False:
            errstring = "Invalid syntax in page selection: "+string+\
                        ". Please use a comma separated list with"+\
                        " optional dashes, e.g. '1-3,6,8'." 
            try:
                wx.MessageDialog(parent, errstring, "Error", 
                                  style=wx.ICON_ERROR|wx.OK|wx.STAY_ON_TOP)
            except:
                raise ValueError(errstring)
        else:
            raise ValueError(errstring)
        return None
Example #13
0
    def check_result(self, expected, result, table, test_name):
        # TODO: don't convert to unicode, type inference for smallint is
        # currently broken, that's the reason at the moment.
        assert result, "No result set received."

        for key, value in expected.iteritems():
          self.assertEquals(unicode(result[key]), unicode(value), """
             ========================================================

             Data: {expected}

             ========================================================

             Failed {test_name} test on
             Table: "{table}"
             Field: "{key}"
               expected: {expected_value} ({expected_type})
               result: {result_value} ({result_type})

             ========================================================
            """.format(
                  expected = repr(expected),
                  test_name = test_name,
                  table = table,
                  key = key,
                  expected_value = value,
                  result_value = result[key],
                  expected_type = type(value),
                  result_type = type(result[key])
              ))
Example #14
0
def writedoc(key,top=False):
    """Write HTML documentation to a file in the current directory."""
    if(type(key) == str and (key == "modules" or key == "/.")):
        heading = pydoc.html.heading(
            '<br><big><big><strong>&nbsp;'
            'Python: Index of Modules'
            '</strong></big></big>',
            '#ffffff', '#7799ee')
        builtins = []
        for name in sys.builtin_module_names:
            builtins.append('<a href="%s">%s</a>' % (cgi.escape(name,quote=True), cgi.escape(name)))
        indices = ['<p>Built-in modules: ' + cgi.escape(join(builtins, ', '))]
        seen = {}
        for dir in pydoc.pathdirs():
            indices.append(pydoc.html.index(dir, seen))
        print cleanlinks(heading + join(indices))
        return

    if(type(key) != types.ModuleType):
        object = pydoc.locate(key)
        if(object == None and top):
            print "could not locate module/object for key " + \
                   cgi.escape(key) + "<br><a href=\"pydoc:modules\">go to index</a>";
    else:
        object = key
            
    if object:
        print cleanlinks(pydoc.html.page(pydoc.describe(object), pydoc.html.document(object)))
 def serialize(self, buff):
   """
   serialize message into buffer
   :param buff: buffer, ``StringIO``
   """
   try:
     _x = self.caller_id
     length = len(_x)
     if python3 or type(_x) == unicode:
       _x = _x.encode('utf-8')
       length = len(_x)
     if python3:
       buff.write(struct.pack('<I%sB'%length, length, *_x))
     else:
       buff.write(struct.pack('<I%ss'%length, length, _x))
     _x = self.orig_caller_id
     length = len(_x)
     if python3 or type(_x) == unicode:
       _x = _x.encode('utf-8')
       length = len(_x)
     if python3:
       buff.write(struct.pack('<I%sB'%length, length, *_x))
     else:
       buff.write(struct.pack('<I%ss'%length, length, _x))
     _x = self.data
     length = len(_x)
     if python3 or type(_x) == unicode:
       _x = _x.encode('utf-8')
       length = len(_x)
     if python3:
       buff.write(struct.pack('<I%sB'%length, length, *_x))
     else:
       buff.write(struct.pack('<I%ss'%length, length, _x))
   except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
   except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def load_data(name, plotdir, print_out=True):
    "Read data and split into train, test data."
    df = read_data(name)
    train, test = train_test_split(df, test_size=0.3)
#   plot_scatter_matrix(train, plotdir)  # takes a while, not that useful 
    yvars = ['risk', 'Y']
    train_y = train[yvars]
    test_y  = test[yvars]
#   train_r = train['risk']    # for five-way multi-class classification
    train = train.drop(['risk', 'Y'], axis=1)
    test  = test.drop(['risk', 'Y'],  axis=1)
    if print_out:
        print("train test types %s %s %s %s" % (type(train), type(test), type(train_y), type(test_y)))
        print("train test shapes %s %s %s %s" % (train.shape, test.shape, train_y.shape, test_y.shape))
        print("train head\n%s" % (train[:3]))
        print("test head\n%s" % (test[:3]))
        print("train_y set %s, test_y set %s" % (set(train_y['Y']), set(test_y['Y'])))
        print("train_y stats\n%s\ntest_y stats\n%s" % (train_y.describe(), test_y.describe()))

#   drop_col = ['b_sugar_up']
#   print('dropping high std/mean columns', drop_col)
#   train = train.drop(drop_col, axis=1)
#   test  = test.drop(drop_col, axis=1)
#   drop_col = ['age','exer_slope']
#   print('dropping low importance columns', drop_col)
#   train = train.drop(drop_col, axis=1)
#   test  = test.drop(drop_col, axis=1)
    return train, test, train_y, test_y
    def test_build_composer_environment_converts_vars_to_str(self):
        ctx = utils.FormattedDict({
            'BUILD_DIR': '/usr/awesome',
            'PHP_VM': 'php',
            'TMPDIR': 'tmp',
            'LIBDIR': 'lib',
            'CACHE_DIR': 'cache',
            'PHPRC': '/usr/awesome/phpini',
            'MY_DICTIONARY': {'KEY': 'VALUE'},
        })

        write_config_stub = Dingus()

        with patches({
            'composer.extension.PHPComposerStrategy.write_config': write_config_stub
        }):
            self.extension_module.ComposerExtension(ctx)
            cr = self.extension_module.ComposerCommandRunner(ctx, None)

            built_environment = cr._build_composer_environment()

        for key, val in built_environment.iteritems():
            assert type(val) == str, \
                "Expected [%s]:[%s] to be type `str`, but found type [%s]" % (
                    key, val, type(val))
Example #18
0
    def test_listings_and_commands_and_output(self):
        self.parse_listings()

        # sanity checks
        self.assertEqual(self.listings[0].type, 'code listing with git ref')
        self.assertEqual(type(self.listings[1]), Command)
        self.assertEqual(type(self.listings[2]), Output)

        self.sourcetree.start_with_checkout(self.chapter_no)
        # other prep
        self.sourcetree.run_command('python3 manage.py syncdb --noinput')

        # skips
        self.skip_with_check(25, 'the -b means ignore whitespace')
        self.skip_with_check(28, 'leave static, for now')
        self.skip_with_check(51, 'will now show all the bootstrap')

        # hack fast-forward
        skip = False
        if skip:
            self.pos = 55
            self.sourcetree.run_command('git checkout {0}'.format(
                self.sourcetree.get_commit_spec('ch07l018')
            ))

        while self.pos < len(self.listings):
            print(self.pos)
            self.recognise_listing_and_process_it()


        self.assert_all_listings_checked(self.listings)
        self.check_final_diff(self.chapter_no, ignore_moves=True)
Example #19
0
def GetProperties(obj, propList):
	"""Given a MAPI object and a list of properties, return a list of property values.
	
	Allows a single property to be passed, and the result is a single object.
	
	Each request property can be an integer or a string.  Of a string, it is 
	automatically converted to an integer via the GetIdsFromNames function.
	
	If the property fetch fails, the result is None.
	"""
	bRetList = 1
	if type(propList) not in [TupleType, ListType]:
		bRetList = 0
		propList = (propList,)
	realPropList = []
	rc = []
	for prop in propList:
		if type(prop)!=IntType:	# Integer
			props = ( (mapi.PS_PUBLIC_STRINGS, prop), )
			propIds = obj.GetIDsFromNames(props, 0)
			prop = mapitags.PROP_TAG( mapitags.PT_UNSPECIFIED, mapitags.PROP_ID(propIds[0]))
		realPropList.append(prop)
		
	hr, data = obj.GetProps(realPropList,0)
	if hr != 0:
		data = None
		return None
	if bRetList:
		return [v[1] for v in data]
	else:
		return data[0][1]
Example #20
0
	def unset(cls, client, resource, args) :
		ur""" Use this API to unset the properties of csaction resource.
		Properties that need to be unset are specified in args array.
		"""
		try :
			if type(resource) is not list :
				unsetresource = csaction()
				if type(resource) !=  type(unsetresource):
					unsetresource.name = resource
				else :
					unsetresource.name = resource.name
				return unsetresource.unset_resource(client, args)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						unsetresources = [ csaction() for _ in range(len(resource))]
						for i in range(len(resource)) :
							unsetresources[i].name = resource[i]
				else :
					if (resource and len(resource) > 0) :
						unsetresources = [ csaction() for _ in range(len(resource))]
						for i in range(len(resource)) :
							unsetresources[i].name = resource[i].name
				result = cls.unset_bulk_request(client, unsetresources, args)
			return result
		except Exception as e :
			raise e
Example #21
0
    def write_double_workaround(self, d):
        """
        Override the L{DataTypeMixIn.write_double} method to fix problems
        with doubles by using the third-party C{fpconst} library.

        @raise TypeError: Unexpected type for float C{d}.
        """
        if type(d) is not float:
            raise TypeError('expected a float (got:%r)' % (type(d),))

        if python.isNaN(d):
            if self._is_big_endian():
                self.write('\xff\xf8\x00\x00\x00\x00\x00\x00')
            else:
                self.write('\x00\x00\x00\x00\x00\x00\xf8\xff')
        elif python.isNegInf(d):
            if self._is_big_endian():
                self.write('\xff\xf0\x00\x00\x00\x00\x00\x00')
            else:
                self.write('\x00\x00\x00\x00\x00\x00\xf0\xff')
        elif python.isPosInf(d):
            if self._is_big_endian():
                self.write('\x7f\xf0\x00\x00\x00\x00\x00\x00')
            else:
                self.write('\x00\x00\x00\x00\x00\x00\xf0\x7f')
        else:
            write_double_workaround.old_func(self, d)
	def delete(cls, client, resource) :
		""" Use this API to delete aaapreauthenticationpolicy.
		"""
		try :
			if type(resource) is not list :
				deleteresource = aaapreauthenticationpolicy()
				if type(resource) !=  type(deleteresource):
					deleteresource.name = resource
				else :
					deleteresource.name = resource.name
				return deleteresource.delete_resource(client)
			else :
				if type(resource[0]) != cls :
					if (resource and len(resource) > 0) :
						deleteresources = [ aaapreauthenticationpolicy() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].name = resource[i]
				else :
					if (resource and len(resource) > 0) :
						deleteresources = [ aaapreauthenticationpolicy() for _ in range(len(resource))]
						for i in range(len(resource)) :
							deleteresources[i].name = resource[i].name
				result = cls.delete_bulk_request(client, deleteresources)
			return result
		except Exception as e :
			raise e
Example #23
0
    def __init__(self, addr, zmq_type, bind=True, subscribe=None):
        self.sock = _get_ctxt().socket(zmq_type)
        self.addr = addr
        self.type = zmq_type
        self.subscriptions = []

        # Support failures on sending/receiving on wrong socket type.
        self.can_recv = zmq_type in (zmq.PULL, zmq.SUB)
        self.can_send = zmq_type in (zmq.PUSH, zmq.PUB)
        self.can_sub = zmq_type in (zmq.SUB, )

        # Support list, str, & None for subscribe arg (cast to list)
        do_sub = {
            list: subscribe,
            str: [subscribe],
            type(None): []
        }[type(subscribe)]

        for f in do_sub:
            self.subscribe(f)

        str_data = {'addr': addr, 'type': self.socket_s(),
                    'subscribe': subscribe, 'bind': bind}

        LOG.debug(_("Connecting to %(addr)s with %(type)s"), str_data)
        LOG.debug(_("-> Subscribed to %(subscribe)s"), str_data)
        LOG.debug(_("-> bind: %(bind)s"), str_data)

        try:
            if bind:
                self.sock.bind(addr)
            else:
                self.sock.connect(addr)
        except Exception:
            raise RPCException(_("Could not open socket."))
	def delete(self,id):
		if type(id)==type(dict()):
			self.cursor.execute("DELETE FROM " + self.name +
					    " WHERE "+self.fields[0] +" = %("+ self.fields[0]+")s",id);
		elif type(id)==type(int()):
			self.cursor.execute("DELETE FROM " + self.name +
					    " WHERE "+self.fields[0] +" = %s",id);
Example #25
0
    def _fetch_docs(cls, resource_name, query, options=None):
        '''
        Returns a document in deserialized (hash) form.
        
        If model caching is used, then the cache will be checked
        for the document before going to the remote data endpoint.

        See toothpick/cache.py for more about caching.
        '''
        try:
            attributes = cls._resource(resource_name).read(
                query=query,
                options=options
            )
                                                  
            # things like #find are expecting lists of documents, even if there's
            # only one, but that seems a little artifact-y.  I'm putting that here
            # as a constraint rather than forcing Resource implementors to worry
            # about it.
            if not type(attributes) == type([]):
                attributes = [attributes]

            return attributes
        except exceptions.NotFound:
            return []
Example #26
0
def QScomplex(val):
    if QSMODE == MODE_NORM:
        return complex(val)
    else:
        if type(val) is str or type(val) is unicode:
            if 'nan' in val:
                return mpmath.mpc(real='nan',imag='nan')
            real = None
            imag = None
            delim = None
            if '+' in val[1:]:
                delim = '+'
            elif '-' in val[1:]:
                delim = '-'
            if delim is None:
                if 'j' in val:
                    imag = val.replace('j','')
                else:
                    real = val
            else:
                index = val[1:].find(delim) + 1
                real = val[:index]
                imag = val[index:].replace('j','')
            return mpmath.mpc(real=real,imag=imag)
        else:
            return mpmath.mpc(val)
Example #27
0
def showOverlap(mode, modes, *args, **kwargs):
    """Show overlap :func:`~matplotlib.pyplot.bar`.

    :arg mode: a single mode/vector
    :type mode: :class:`.Mode`, :class:`.Vector`
    :arg modes: multiple modes
    :type modes: :class:`.ModeSet`, :class:`.ANM`, :class:`.GNM`, :class:`.PCA`
    """

    import matplotlib.pyplot as plt
    if not isinstance(mode, (Mode, Vector)):
        raise TypeError('mode must be Mode or Vector, not {0}'
                        .format(type(mode)))
    if not isinstance(modes, (NMA, ModeSet)):
        raise TypeError('modes must be NMA or ModeSet, not {0}'
                        .format(type(modes)))
    overlap = abs(calcOverlap(mode, modes))
    if isinstance(modes, NMA):
        arange = np.arange(0.5, len(modes)+0.5)
    else:
        arange = modes.getIndices() + 0.5
    show = plt.bar(arange, overlap, *args, **kwargs)
    plt.title('Overlap with {0}'.format(str(mode)))
    plt.xlabel('{0} mode index'.format(modes))
    plt.ylabel('Overlap')
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #28
0
    def __init__(self,
                 batch_size,
                 target_lfiles=None,
                 source_lfiles=None,
                 order=0,
                 dtype="int64",
                 use_infinite_loop=True,
                 stop=-1,
                 output_format=None,
                 can_fit=False,
                 shuffle=False):

        assert type(source_lfiles) == list, "Target language file should be a list."

        if target_lfiles is not None:
            assert type(target_lfiles) == list, "Target language file should be a list."
            assert len(target_lfiles) == len(source_lfiles)

        self.batch_size = batch_size
        self.target_lfiles = target_lfiles
        self.source_lfiles = source_lfiles
        self.use_infinite_loop = use_infinite_loop
        self.target_langs = []
        self.source_langs = []
        self.order = order
        self.offset = 0
        self.data_len = 0
        self.stop = stop
        self.can_fit = can_fit
        self.dtype = dtype
        self.output_format = output_format
        self.shuffle = shuffle
        self.load_files()
def formatTemplate(line):
    lastIndex = 0
    index = 0
    isAtPairBegin = False
    templateNames = []
    while index < len(line):
        index = str.find(line, "$", index)
        if index != -1:
            if isAtPairBegin:
                templateNames.append(line[lastIndex+1:index])
                isAtPairBegin = False
            else:
                isAtPairBegin = True
            lastIndex = index
            index = index + 1
        else:
            break
    # line = re.sub(r'[1-9]\.[0-9]+\.[0-9]+', newVersion, line)
    for template in templateNames:
        old = "${0}$".format(template)
        print(type(template))
        new = "%d" % (templateDict[template])
        print(type(new))
        line = str.replace(line, old, new)

    return line
Example #30
0
 def send(self,stanza):
     """ Serialise stanza and put it on the wire. Assign an unique ID to it before send.
         Returns assigned ID."""
     if type(stanza) in [type(''), type(u'')]: return self._owner_send(stanza)
     if not isinstance(stanza,Protocol): _ID=None
     elif not stanza.getID():
         global ID
         ID+=1
         _ID=`ID`
         stanza.setID(_ID)
     else: _ID=stanza.getID()
     if self._owner._registered_name and not stanza.getAttr('from'): stanza.setAttr('from',self._owner._registered_name)
     if self._owner._route and stanza.getName()!='bind':
         to=self._owner.Server
         if stanza.getTo() and stanza.getTo().getDomain():
             to=stanza.getTo().getDomain()
         frm=stanza.getFrom()
         if frm.getDomain():
             frm=frm.getDomain()
         route=Protocol('route',to=to,frm=frm,payload=[stanza])
         stanza=route
     stanza.setNamespace(self._owner.Namespace)
     stanza.setParent(self._metastream)
     self._owner_send(stanza)
     return _ID