本文整理汇总了Golang中speter/net/go/exp/math/dec/inf.NewDec函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDec函数的具体用法?Golang NewDec怎么用?Golang NewDec使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDec函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ExampleDec_QuoExact_ok
func ExampleDec_QuoExact_ok() {
// 1 / 25 is a finite decimal; it has exact Dec representation
x, y := inf.NewDec(1, 0), inf.NewDec(25, 0)
z := new(inf.Dec).QuoExact(x, y)
fmt.Println(z)
// Output: 0.04
}
示例2: ExampleDec_QuoExact_fail
func ExampleDec_QuoExact_fail() {
// 1 / 3 is an infinite decimal; it has no exact Dec representation
x, y := inf.NewDec(1, 0), inf.NewDec(3, 0)
z := new(inf.Dec).QuoExact(x, y)
fmt.Println(z)
// Output: <nil>
}
示例3: TestDecScan
func TestDecScan(t *testing.T) {
tmp := new(inf.Dec)
for i, test := range decStringTests {
if test.scale < 0 {
// SetString only supports scale >= 0
continue
}
// initialize to a non-zero value so that issues with parsing
// 0 are detected
tmp.Set(inf.NewDec(1234567890, 123))
n1, n2 := new(inf.Dec), tmp
nn1, err1 := fmt.Sscan(test.in, n1)
nn2, err2 := fmt.Sscan(test.in, n2)
if !test.scanOk {
if err1 == nil || err2 == nil {
t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk)
}
continue
}
expected := inf.NewDec(test.val, test.scale)
if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil {
t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2)
continue
}
if n1.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
}
if n2.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
}
}
}
示例4: Test_GetNodeResources
// test mesos.GetNodeResources
func Test_GetNodeResources(t *testing.T) {
defer log.Flush()
md := FakeMasterDetector{}
httpServer, httpClient, httpTransport := makeHttpMocks()
defer httpServer.Close()
cacheTTL := 500 * time.Millisecond
mesosClient, err := createMesosClient(md, httpClient, httpTransport, cacheTTL)
mesosCloud := &MesosCloud{client: mesosClient, config: createDefaultConfig()}
resources, err := mesosCloud.GetNodeResources("mesos1.internal.company.com")
if err != nil {
t.Fatalf("GetNodeResources does not yield an error: %#v", err)
}
expectedCpu := inf.NewDec(8, 0)
expectedMem := inf.NewDec(15360, 0)
actualCpu := resources.Capacity["cpu"].Amount
actualMem := resources.Capacity["memory"].Amount
if actualCpu.Cmp(expectedCpu) != 0 {
t.Fatalf("GetNodeResources should return the expected amount of cpu: (expected: %#v, vactual: %#v)", expectedCpu, actualCpu)
}
if actualMem.Cmp(expectedMem) != 0 {
t.Fatalf("GetNodeResources should return the expected amount of memory: (expected: %#v, vactual: %#v)", expectedMem, actualMem)
}
}
示例5: newClusterResourceOverride
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(client clientset.Interface, config io.Reader) (admission.Interface, error) {
parsed, err := ReadConfig(config)
if err != nil {
glog.V(5).Infof("%s admission controller loaded with error: (%T) %[2]v", api.PluginName, err)
return nil, err
}
if errs := validation.Validate(parsed); len(errs) > 0 {
return nil, errs.ToAggregate()
}
glog.V(5).Infof("%s admission controller loaded with config: %v", api.PluginName, parsed)
var internal *internalConfig
if parsed != nil {
internal = &internalConfig{
limitCPUToMemoryRatio: inf.NewDec(parsed.LimitCPUToMemoryPercent, 2),
cpuRequestToLimitRatio: inf.NewDec(parsed.CPURequestToLimitPercent, 2),
memoryRequestToLimitRatio: inf.NewDec(parsed.MemoryRequestToLimitPercent, 2),
}
}
limitRanger, err := limitranger.NewLimitRanger(client, wrapLimit)
if err != nil {
return nil, err
}
return &clusterResourceOverridePlugin{
Handler: admission.NewHandler(admission.Create),
config: internal,
LimitRanger: limitRanger,
}, nil
}
示例6: ExampleDec_QuoRound_scale2RoundCeil
func ExampleDec_QuoRound_scale2RoundCeil() {
// -42 / 400 is an finite decimal with 3 digits beyond the decimal point
x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0)
// use 2 digits beyond decimal point, round towards positive infinity
z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil)
fmt.Println(z)
// Output: -0.10
}
示例7: ExampleDec_QuoRound_scale2RoundDown
func ExampleDec_QuoRound_scale2RoundDown() {
// 10 / 3 is an infinite decimal; it has no exact Dec representation
x, y := inf.NewDec(10, 0), inf.NewDec(3, 0)
// use 2 digits beyond the decimal point, round towards 0
z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown)
fmt.Println(z)
// Output: 3.33
}
示例8: checkResource
// checkResource determines whether a specific resource needs to be over-written.
func checkResource(threshold int64, actual, expected api.ResourceList, res api.ResourceName) bool {
val, ok := actual[res]
expVal, expOk := expected[res]
if ok != expOk {
return true
}
if !ok && !expOk {
return false
}
q := new(inf.Dec).QuoRound(val.Amount, expVal.Amount, 2, inf.RoundDown)
lower := inf.NewDec(100-threshold, 2)
upper := inf.NewDec(100+threshold, 2)
if q.Cmp(lower) == -1 || q.Cmp(upper) == 1 {
return true
}
return false
}
示例9: Admit
// TODO this will need to update when we have pod requests/limits
func (a *clusterResourceOverridePlugin) Admit(attr admission.Attributes) error {
glog.V(6).Infof("%s admission controller is invoked", api.PluginName)
if a.config == nil || attr.GetResource() != kapi.Resource("pods") || attr.GetSubresource() != "" {
return nil // not applicable
}
pod, ok := attr.GetObject().(*kapi.Pod)
if !ok {
return admission.NewForbidden(attr, fmt.Errorf("unexpected object: %#v", attr.GetObject()))
}
glog.V(5).Infof("%s is looking at creating pod %s in project %s", api.PluginName, pod.Name, attr.GetNamespace())
// allow annotations on project to override
if ns, err := a.ProjectCache.GetNamespace(attr.GetNamespace()); err != nil {
glog.Warningf("%s got an error retrieving namespace: %v", api.PluginName, err)
return admission.NewForbidden(attr, err) // this should not happen though
} else {
projectEnabledPlugin, exists := ns.Annotations[clusterResourceOverrideAnnotation]
if exists && projectEnabledPlugin != "true" {
glog.V(5).Infof("%s is disabled for project %s", api.PluginName, attr.GetNamespace())
return nil // disabled for this project, do nothing
}
}
// Reuse LimitRanger logic to apply limit/req defaults from the project. Ignore validation
// errors, assume that LimitRanger will run after this plugin to validate.
glog.V(5).Infof("%s: initial pod limits are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
if err := a.LimitRanger.Admit(attr); err != nil {
glog.V(5).Infof("%s: error from LimitRanger: %#v", api.PluginName, err)
}
glog.V(5).Infof("%s: pod limits after LimitRanger are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
for _, container := range pod.Spec.Containers {
resources := container.Resources
memLimit, memFound := resources.Limits[kapi.ResourceMemory]
if memFound && a.config.memoryRequestToLimitRatio.Cmp(zeroDec) != 0 {
resources.Requests[kapi.ResourceMemory] = resource.Quantity{
Amount: multiply(memLimit.Amount, a.config.memoryRequestToLimitRatio),
Format: resource.BinarySI,
}
}
if memFound && a.config.limitCPUToMemoryRatio.Cmp(zeroDec) != 0 {
resources.Limits[kapi.ResourceCPU] = resource.Quantity{
// float math is necessary here as there is no way to create an inf.Dec to represent cpuBaseScaleFactor < 0.001
Amount: multiply(inf.NewDec(int64(float64(memLimit.Value())*cpuBaseScaleFactor), 3), a.config.limitCPUToMemoryRatio),
Format: resource.DecimalSI,
}
}
cpuLimit, cpuFound := resources.Limits[kapi.ResourceCPU]
if cpuFound && a.config.cpuRequestToLimitRatio.Cmp(zeroDec) != 0 {
resources.Requests[kapi.ResourceCPU] = resource.Quantity{
Amount: multiply(cpuLimit.Amount, a.config.cpuRequestToLimitRatio),
Format: resource.DecimalSI,
}
}
}
glog.V(5).Infof("%s: pod limits after overrides are: %#v", api.PluginName, pod.Spec.Containers[0].Resources)
return nil
}
示例10: newClusterResourceOverride
// newClusterResourceOverride returns an admission controller for containers that
// configurably overrides container resource request/limits
func newClusterResourceOverride(client clientset.Interface, config *api.ClusterResourceOverrideConfig) (admission.Interface, error) {
glog.V(2).Infof("%s admission controller loaded with config: %v", api.PluginName, config)
var internal *internalConfig
if config != nil {
internal = &internalConfig{
limitCPUToMemoryRatio: inf.NewDec(config.LimitCPUToMemoryPercent, 2),
cpuRequestToLimitRatio: inf.NewDec(config.CPURequestToLimitPercent, 2),
memoryRequestToLimitRatio: inf.NewDec(config.MemoryRequestToLimitPercent, 2),
}
}
limitRanger, err := limitranger.NewLimitRanger(client, &limitRangerActions{})
if err != nil {
return nil, err
}
return &clusterResourceOverridePlugin{
Handler: admission.NewHandler(admission.Create),
config: internal,
LimitRanger: limitRanger,
}, nil
}
示例11: TestSemantic
func TestSemantic(t *testing.T) {
table := []struct {
a, b interface{}
shouldEqual bool
}{
{resource.MustParse("0"), resource.Quantity{}, true},
{resource.Quantity{}, resource.MustParse("0"), true},
{resource.Quantity{}, resource.MustParse("1m"), false},
{
resource.Quantity{inf.NewDec(5, 0), resource.BinarySI},
resource.Quantity{inf.NewDec(5, 0), resource.DecimalSI},
true,
},
{resource.MustParse("2m"), resource.MustParse("1m"), false},
}
for index, item := range table {
if e, a := item.shouldEqual, Semantic.DeepEqual(item.a, item.b); e != a {
t.Errorf("case[%d], expected %v, got %v.", index, e, a)
}
}
}
示例12: TestDecSetString
func TestDecSetString(t *testing.T) {
tmp := new(inf.Dec)
for i, test := range decStringTests {
if test.scale < 0 {
// SetString only supports scale >= 0
continue
}
// initialize to a non-zero value so that issues with parsing
// 0 are detected
tmp.Set(inf.NewDec(1234567890, 123))
n1, ok1 := new(inf.Dec).SetString(test.in)
n2, ok2 := tmp.SetString(test.in)
expected := inf.NewDec(test.val, test.scale)
if ok1 != test.ok || ok2 != test.ok {
t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
continue
}
if !ok1 {
if n1 != nil {
t.Errorf("#%d (input '%s') n1 != nil", i, test.in)
}
continue
}
if !ok2 {
if n2 != nil {
t.Errorf("#%d (input '%s') n2 != nil", i, test.in)
}
continue
}
if n1.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
}
if n2.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
}
}
}
示例13: TestRowBinding
func TestRowBinding(t *testing.T) {
header := []string{"n", "d", "c", "r"}
row := []string{"foo", "2014-04-06 10:02:21", "4459813", "1.55"}
input := [][]string{header, row}
s := make(map[string]string)
s["n"] = "Name"
s["d"] = "Date"
s["c"] = "Counter"
s["r"] = "Rating"
d := Destination{
Name: "foo",
Counter: 4459813,
Date: time.Date(2014, 4, 6, 10, 02, 21, 0, time.UTC),
Rating: inf.NewDec(155, 2),
}
runScenario(t, input, s, d)
}
示例14: scaleWithNodes
func (e LinearEstimator) scaleWithNodes(numNodes uint64) *api.ResourceRequirements {
limits := make(api.ResourceList)
requests := make(api.ResourceList)
for _, r := range e.Resources {
num := inf.NewDec(int64(numNodes), 0)
num.Mul(num, r.ExtraPerNode.Amount)
num.Add(num, r.Base.Amount)
limits[r.Name] = resource.Quantity{
Amount: num,
Format: r.Base.Format,
}
requests[r.Name] = resource.Quantity{
Amount: num,
Format: r.Base.Format,
}
}
return &api.ResourceRequirements{
Limits: limits,
Requests: requests,
}
}
示例15:
type Page struct {
Title string
RevId UUID
Body string
Views int64
Protected bool
Modified time.Time
Rating *inf.Dec
Tags []string
Attachments map[string]Attachment
}
type Attachment []byte
var rating, _ = inf.NewDec(0, 0).SetString("0.131")
var pageTestData = []*Page{
&Page{
Title: "Frontpage",
RevId: TimeUUID(),
Body: "Welcome to this wiki page!",
Rating: rating,
Modified: time.Date(2013, time.August, 13, 9, 52, 3, 0, time.UTC),
Tags: []string{"start", "important", "test"},
Attachments: map[string]Attachment{
"logo": Attachment("\x00company logo\x00"),
"favicon": Attachment("favicon.ico"),
},
},
&Page{