当前位置: 首页>>代码示例>>Python>>正文


Python util.normalize函数代码示例

本文整理汇总了Python中util.normalize函数的典型用法代码示例。如果您正苦于以下问题:Python normalize函数的具体用法?Python normalize怎么用?Python normalize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了normalize函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: drawHouseNames

    def drawHouseNames(self, chrt, rHouseNames):
        (cx, cy) = self.center.Get()
        clr = self.options.clrhousenumbers
        if self.bw:
            clr = (0, 0, 0)
        pen = wx.Pen(clr, 1)
        self.bdc.SetPen(pen)
        asc = self.chartRadix.houses.ascmc[houses.Houses.ASC]
        if self.options.ayanamsha != 0 and self.options.hsys == "W":
            asc = util.normalize(self.chartRadix.houses.ascmc[houses.Houses.ASC] - self.chartRadix.ayanamsha)
        for i in range(1, houses.Houses.HOUSE_NUM + 1):
            width = 0.0
            if i != houses.Houses.HOUSE_NUM:
                width = chrt.houses.cusps[i + 1] - chrt.houses.cusps[i]
            else:
                width = chrt.houses.cusps[1] - chrt.houses.cusps[houses.Houses.HOUSE_NUM]

            width = util.normalize(width)
            halfwidth = math.radians(width / 2.0)
            dif = math.radians(util.normalize(asc - chrt.houses.cusps[i]))

            x = cx + math.cos(math.pi + dif - halfwidth) * rHouseNames
            y = cy + math.sin(math.pi + dif - halfwidth) * rHouseNames
            if i == 1 or i == 2:
                xoffs = 0
                yoffs = self.symbolSize / 4
                if i == 2:
                    xoffs = self.symbolSize / 8
            else:
                xoffs = self.symbolSize / 4
                yoffs = self.symbolSize / 4

            self.draw.text((x - xoffs, y - yoffs), common.common.Housenames[i - 1], fill=clr, font=self.fntText)
开发者ID:Alwnikrotikz,项目名称:morinus-astro,代码行数:33,代码来源:graphchartpds.py

示例2: test

  def test(self, categories):
    for i in range(Constants.NUM_SUBJECTS):
      trainSubjects = [1, 2, 3, 4]
      testSubjects = [i + 1]
      trainSubjects.remove(i + 1)

      trainVoxelArrayMap = util.getVoxelArray(subjectNumbers = trainSubjects)
      testVoxelArrayMap = util.getVoxelArray(subjectNumbers = testSubjects)
      util.normalize(trainVoxelArrayMap)
      util.normalize(testVoxelArrayMap)
      util.filterData(trainVoxelArrayMap, categories=categories)
      util.filterData(testVoxelArrayMap, categories=categories)

      Xtrain = numpy.array([trainVoxelArrayMap[key] for key in trainVoxelArrayMap])
      Ytrain = numpy.array([key[1] for key in trainVoxelArrayMap])

      Xtest = numpy.array([testVoxelArrayMap[key] for key in testVoxelArrayMap])
      Yanswer = numpy.array([key[1] for key in testVoxelArrayMap])

      Yprediction = OneVsRestClassifier(LinearSVC()).fit(Xtrain, Ytrain).predict(Xtest)
      # Yprediction = OneVsOneClassifier(LinearSVC()).fit(Xtrain, Ytrain).predict(Xtest)

      correct = 0
      for index in range(len(Yanswer)):
        if Yanswer[index] == Yprediction[index]:
          correct += 1
      # correct = [1 if Yanswer[index] == Yprediction[index] else 0 for index in range(len(Yanswer))]
      print categories, "Correct Predictions: ", correct, "/", len(Yanswer)
      return float(correct) * 100 / len(Yanswer)
开发者ID:AlexanderCarlisle,项目名称:FMRI_FInalProject,代码行数:29,代码来源:svm.py

示例3: test_string_derived_fields

def test_string_derived_fields():
    f = fields.EmailField()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'string',
        'format': 'email',
    }

    f = fields.IPv4Field()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'string',
        'format': 'ipv4',
    }

    f = fields.DateTimeField()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'string',
        'format': 'date-time',
    }

    f = fields.UriField()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'string',
        'format': 'uri',
    }
开发者ID:adamchainz,项目名称:jsl,代码行数:28,代码来源:test_fields.py

示例4: find_max_eigenpair

def find_max_eigenpair(T, outer_iterations = 10, inner_iterations = 100):
    """
    Run tensor power method (Algorithm 1 of Anandkumar/Ge/Hsu/Kakade/Telgarsky, 2012).
    """
    D = T.shape[0]
    eps = 1e-10

    best = (-np.inf, np.zeros(D))
    # Outer iterations
    for tau in xrange(outer_iterations):
        # (1) Draw a random initialization θ_t
        theta = normalize( randn( D ) )
        # Inner iterations
        for t in xrange(inner_iterations):
            # 2) Update θ ← T(I, θ, θ)/||T(I, θ, θ)||
            theta_ = normalize( T.ttv( (theta, theta), modes = (1,2) ) )
            if norm(theta - theta_) < eps:
                break
        # (3) Choose θ_t with max eigenvalue λ = T(θ, θ, θ)
        lbda = float( T.ttv( (theta, theta, theta), modes = (0,1,2) ) )
        epair = lbda, theta
        if epair[0] > best[0]:
            best = epair

    _, theta = best
    for t in xrange(inner_iterations):
        # 2) Update θ ← T(I, θ, θ)/||T(I, θ, θ)||
        theta = normalize( T.ttv( (theta, theta), modes = (1,2) ) )
    # (4) Update θ
    lbda = float(T.ttv( (theta, theta, theta), modes = (0,1,2) ))
    # (5) Return λ, θ
    return lbda, theta
开发者ID:sidaw,项目名称:polymom,代码行数:32,代码来源:tensor_power_method.py

示例5: test_recursive_document_field

def test_recursive_document_field():
    class Tree(Document):
        node = fields.OneOfField([
            fields.ArrayField(fields.DocumentField('self')),
            fields.StringField(),
        ])

    expected_schema = {
        '$schema': 'http://json-schema.org/draft-04/schema#',
        'definitions': {
            'test_fields.Tree': {
                'type': 'object',
                'additionalProperties': False,
                'properties': {
                    'node': {
                        'oneOf': [
                            {
                                'type': 'array',
                                'items': {'$ref': '#/definitions/test_fields.Tree'},
                            },
                            {
                                'type': 'string',
                            },
                        ],
                    },
                },
            },
        },
        '$ref': '#/definitions/test_fields.Tree',
    }
    assert normalize(Tree.get_schema()) == normalize(expected_schema)
开发者ID:adamchainz,项目名称:jsl,代码行数:31,代码来源:test_fields.py

示例6: test_string_field

def test_string_field():
    f = fields.StringField()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {'type': 'string'}

    f = fields.StringField(min_length=1, max_length=10, pattern='^test$',
                           enum=('a', 'b', 'c'), title='Pururum')

    expected_items = [
        ('type', 'string'),
        ('title', 'Pururum'),
        ('enum', ['a', 'b', 'c']),
        ('pattern', '^test$'),
        ('minLength', 1),
        ('maxLength', 10),
    ]
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == dict(expected_items)
    definitions, ordered_schema = f.get_definitions_and_schema(ordered=True)
    assert isinstance(ordered_schema, OrderedDict)
    assert normalize(ordered_schema) == OrderedDict(expected_items)

    with pytest.raises(ValueError) as e:
        fields.StringField(pattern='(')
    assert str(e.value) == 'Invalid regular expression: unbalanced parenthesis'
开发者ID:adamchainz,项目名称:jsl,代码行数:25,代码来源:test_fields.py

示例7: test_number_and_int_fields

def test_number_and_int_fields():
    f = fields.NumberField(multiple_of=10)
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'number',
        'multipleOf': 10,
    }

    f = fields.NumberField(minimum=0, maximum=10,
                           exclusive_minimum=True, exclusive_maximum=True)
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'number',
        'exclusiveMinimum': True,
        'exclusiveMaximum': True,
        'minimum': 0,
        'maximum': 10,
    }

    f = fields.NumberField(enum=(1, 2, 3))
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'number',
        'enum': [1, 2, 3],
    }

    f = fields.IntField()
    definitions, schema = f.get_definitions_and_schema()
    assert normalize(schema) == {
        'type': 'integer',
    }
开发者ID:adamchainz,项目名称:jsl,代码行数:31,代码来源:test_fields.py

示例8: test_document_field

def test_document_field():
    document_cls_mock = mock.Mock()
    expected_schema = mock.Mock()
    attrs = {
        'get_definitions_and_schema.return_value': ({}, expected_schema),
        'get_definition_id.return_value': 'document.Document',
        'is_recursive.return_value': False,
    }
    document_cls_mock.configure_mock(**attrs)

    f = fields.DocumentField(document_cls_mock)
    definitions, schema = f.get_definitions_and_schema()
    assert schema == expected_schema
    assert not definitions

    definitions, schema = f.get_definitions_and_schema(ref_documents=set([document_cls_mock]))
    assert normalize(schema) == {'$ref': '#/definitions/document.Document'}

    f = fields.DocumentField(document_cls_mock, as_ref=True)
    definitions, schema = f.get_definitions_and_schema()
    assert definitions == {'document.Document': expected_schema}
    assert normalize(schema) == {'$ref': '#/definitions/document.Document'}

    attrs = {
        'get_definitions_and_schema.return_value': ({}, expected_schema),
        'get_definition_id.return_value': 'document.Document',
        'is_recursive.return_value': True,
    }
    document_cls_mock.reset_mock()
    document_cls_mock.configure_mock(**attrs)

    f = fields.DocumentField(document_cls_mock, as_ref=True)
    definitions, schema = f.get_definitions_and_schema()
    assert schema == expected_schema
    assert not definitions
开发者ID:adamchainz,项目名称:jsl,代码行数:35,代码来源:test_fields.py

示例9: correlationNearestNeighbor

def correlationNearestNeighbor():
	voxelArrayMap = util.getVoxelArray(False, False,True,False, [4])
	
	util.normalize(voxelArrayMap)
	correct = [{ }]*3
	totalCountCorrect = [0] *3
	totalCountInCorrect = [0] *3
	incorrect = [{ }]*3
	voxelCopy = voxelArrayMap.keys()
	totalCorrect =0
	totalIncorrect =0
	count = 0
	for key in voxelCopy:
		count +=1
		testExample = voxelArrayMap[key]
		voxelArrayMap.pop(key, None)

		averageCategoryCorrelations = matrixify(calculateAverageCorrelations(voxelArrayMap))
		exampleCorrelations = calculateSingleExampleCorrelations(testExample, voxelArrayMap)
		classifiedCategory = classifyByClosestCorrelation(exampleCorrelations,averageCategoryCorrelations)

		if classifiedCategory[0] == key[1]:
			totalCorrect +=1
		else:
			totalIncorrect +=1
		voxelArrayMap[key] = testExample
	print "Correct", totalCorrect, "Incorrect", totalIncorrect, "Percentage Correct ", totalCorrect/float((totalCorrect +totalIncorrect))
开发者ID:AlexanderCarlisle,项目名称:FMRI_FInalProject,代码行数:27,代码来源:correlations.py

示例10: toHCs

	def toHCs(self, mundane, idprom, raprom, dsa, nsa, aspect, asp=0.0):
		#day-house, night-house length
		dh = dsa/3.0
		nh = nsa/3.0

		#ra rise, ra set
		rar = self.ramc+dsa
		ras = self.raic+nsa

		rar = util.normalize(rar)
		ras = util.normalize(ras)

		#ra housecusps
		rahcps = ((primdirs.PrimDir.HC2, rar+nh), (primdirs.PrimDir.HC3, rar+2*nh), (primdirs.PrimDir.HC5, self.raic+nh), (primdirs.PrimDir.HC6, self.raic+2*nh), (primdirs.PrimDir.HC8, ras+dh), (primdirs.PrimDir.HC9, ras+2*dh), (primdirs.PrimDir.HC11, self.ramc+dh), (primdirs.PrimDir.HC12, self.ramc+2*dh))

		for h in range(len(rahcps)):
			rahcp = rahcps[h][1]
			rahcp = util.normalize(rahcp)

			arc = raprom-rahcp
			ok = True
			if idprom == astrology.SE_MOON and self.options.pdsecmotion:
				for itera in range(self.options.pdsecmotioniter+1):
					ok, arc = self.calcHArcWithSM(mundane, idprom, h, arc, aspect, asp)
					if not ok:
						break

			if ok:
				self.create(mundane, idprom, primdirs.PrimDir.NONE, rahcps[h][0], aspect, chart.Chart.CONJUNCTIO, arc)
开发者ID:Alwnikrotikz,项目名称:morinus-astro,代码行数:29,代码来源:placidiancommonpd.py

示例11: isShowAsp

	def isShowAsp(self, typ, lon1, lon2, p = -1):
		res = False

		if typ != chart.Chart.NONE and (not self.options.intables or self.options.aspect[typ]):
			val = True
			#check traditional aspects
			if self.options.intables:
				if self.options.traditionalaspects:
					if not(typ == chart.Chart.CONJUNCTIO or typ == chart.Chart.SEXTIL or typ == chart.Chart.QUADRAT or typ == chart.Chart.TRIGON or typ == chart.Chart.OPPOSITIO):
						val = False
					else:
						lona1 = lon1
						lona2 = lon2
						if self.options.ayanamsha != 0:
							lona1 -= self.chart.ayanamsha
							lona1 = util.normalize(lona1)
							lona2 -= self.chart.ayanamsha
							lona2 = util.normalize(lona2)
						sign1 = int(lona1/chart.Chart.SIGN_DEG)
						sign2 = int(lona2/chart.Chart.SIGN_DEG)
						signdiff = math.fabs(sign1-sign2)
						#check pisces-aries transition
						if signdiff > chart.Chart.SIGN_NUM/2:
							signdiff = chart.Chart.SIGN_NUM-signdiff#!?
						if self.arsigndiff[typ] != signdiff:
							val = False

				if not self.options.aspectstonodes and p == astrology.SE_MEAN_NODE:
					val = False

			res = val

		return res
开发者ID:roycewells,项目名称:ktz-astrology,代码行数:33,代码来源:aspectswnd.py

示例12: init_nmf

def init_nmf(F, T, Z, q_init=None):
    if q_init is None:
        q = dict()
        q['f|z'] = normalize(1+numpy.random.exponential(size=(F, Z)), axis=0)
        q['zt'] = normalize(1+numpy.random.exponential(size=(Z, T)))
    else:
        q = copy.deepcopy(q_init)
    return q
开发者ID:ecreager,项目名称:vibntf,代码行数:8,代码来源:ntf.py

示例13: playlistinfo

 def playlistinfo(self):
     with mpd.connect(self.host, self.port) as client:
         info = client.playlistinfo()
     info = [item for item in info if item]
     for item in info:
         normalize(item, {'title' : ('file',), 'artist' : tuple()})
         item['duration'] = fmt_time(item.get('time', 0))
     return info
开发者ID:GopiGorantala,项目名称:jive,代码行数:8,代码来源:model.py

示例14: list

 def list(self, uri):
     with mpd.connect(self.host, self.port) as client:
         listing = client.lsinfo(uri)
     for d in listing:
         if 'directory' in d:
             d['dirname'] = d['directory'].split('/')[-1]
         if 'file' in d:
             normalize(d, {'title' : ('file',)})
     return listing
开发者ID:GopiGorantala,项目名称:jive,代码行数:9,代码来源:model.py

示例15: test_basics

def test_basics():
    class User(Document):
        id = Var({
            'response': IntField(required=True)
        })
        login = StringField(required=True)

    class Task(Document):
        class Options(object):
            title = 'Task'
            description = 'A task.'
            definition_id = 'task'

        id = IntField(required=Var({'response': True}))
        name = StringField(required=True, min_length=5)
        type = StringField(required=True, enum=['TYPE_1', 'TYPE_2'])
        created_at = DateTimeField(required=True)
        author = Var({'response': DocumentField(User)})

    assert normalize(Task.get_schema()) == normalize({
        '$schema': 'http://json-schema.org/draft-04/schema#',
        'additionalProperties': False,
        'description': 'A task.',
        'properties': {
            'created_at': {'format': 'date-time', 'type': 'string'},
            'id': {'type': 'integer'},
            'name': {'minLength': 5, 'type': 'string'},
            'type': {'enum': ['TYPE_1', 'TYPE_2'], 'type': 'string'}
        },
        'required': ['created_at', 'type', 'name'],
        'title': 'Task',
        'type': 'object'
    })

    assert normalize(Task.get_schema(role='response')) == normalize({
        '$schema': 'http://json-schema.org/draft-04/schema#',
        'title': 'Task',
        'description': 'A task.',
        'type': 'object',
        'additionalProperties': False,
        'properties': {
            'created_at': {'format': 'date-time', 'type': 'string'},
            'id': {'type': 'integer'},
            'name': {'minLength': 5, 'type': 'string'},
            'type': {'enum': ['TYPE_1', 'TYPE_2'], 'type': 'string'},
            'author': {
                'additionalProperties': False,
                'properties': {
                    'id': {'type': 'integer'},
                    'login': {'type': 'string'}
                },
                'required': ['id', 'login'],
                'type': 'object'
            },
        },
        'required': ['created_at', 'type', 'name', 'id'],
    })
开发者ID:adamchainz,项目名称:jsl,代码行数:57,代码来源:test_roles.py


注:本文中的util.normalize函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。