• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python util.clamp函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: baseAtLocation

 def baseAtLocation(self, x, y, clampX=False, clampY=False):
     """Returns the (strandType, index) under the location x,y or None.
     
     It shouldn't be possible to click outside a pathhelix and still call
     this function. However, this sometimes happens if you click exactly
     on the top or bottom edge, resulting in a negative y value.
     """
     baseIdx = int(floor(x / self.baseWidth))
     minBase, maxBase = 0, self.vhelix().numBases()
     if baseIdx < minBase or baseIdx >= maxBase:
         if clampX:
             baseIdx = util.clamp(baseIdx, minBase, maxBase-1)
         else:
             return None
     if y < 0:
         y = 0  # HACK: zero out y due to erroneous click
     strandIdx = floor(y * 1. / self.baseWidth)
     if strandIdx < 0 or strandIdx > 1:
         if clampY:
             strandIdx = int(util.clamp(strandIdx, 0, 1))
         else:
             return None
     if self.strandIsTop(StrandType.Scaffold):
         strands = StrandType.Scaffold, StrandType.Staple
     else:
         strands = StrandType.Staple, StrandType.Scaffold
     return (strands[int(strandIdx)], baseIdx)
开发者ID:MatthewMcAteer,项目名称:cadnano2,代码行数:27,代码来源:pathhelix.py


示例2: baseAtPoint

 def baseAtPoint(self, virtualHelixItem, pt):
     """Returns the (strandType, baseIdx) corresponding
     to pt in virtualHelixItem."""
     x, strandIdx = self.helixIndex(pt)
     vh = virtualHelixItem.virtualHelix()
     if vh.isEvenParity():
         strandType = (StrandType.Scaffold, StrandType.Staple)[util.clamp(strandIdx, 0, 1)]
     else:
         strandType = (StrandType.Staple, StrandType.Scaffold)[util.clamp(strandIdx, 0, 1)]
     return (strandType, x, strandIdx)
开发者ID:alaindomissy,项目名称:cadnano2,代码行数:10,代码来源:abstractpathtool.py


示例3: baseAtPoint

 def baseAtPoint(self, pathHelix, pt):
     """Returns the (strandType, baseIdx) corresponding
     to pt in pathHelix."""
     x, strandIdx = self.helixIndex(pt)
     vh = pathHelix.vhelix()
     if vh.evenParity():
         strandType = (StrandType.Scaffold, StrandType.Staple)[util.clamp(strandIdx, 0, 1)]
     else:
         strandType = (StrandType.Staple, StrandType.Scaffold)[util.clamp(strandIdx, 0, 1)]
     return (strandType, x)
开发者ID:divita,项目名称:cadnano2,代码行数:10,代码来源:abstractpathtool.py


示例4: load

    def load(self, filehandle, silent=False):
        """Load contents from a file handle containing a GIMP palette.

        If the format is incorrect, a `RuntimeError` will be raised.
        """
        comment_line_re = re.compile(r'^#')
        field_line_re = re.compile(r'^(\w+)\s*:\s*(.*)$')
        color_line_re = re.compile(r'^(\d+)\s+(\d+)\s+(\d+)\s*(?:\b(.*))$')
        fp = filehandle
        self.clear(silent=True)   # method fires events itself
        line = fp.readline()
        if line.strip() != "GIMP Palette":
            raise RuntimeError, "Not a valid GIMP Palette"
        header_done = False
        line_num = 0
        for line in fp:
            line = line.strip()
            line_num += 1
            if line == '':
                continue
            if comment_line_re.match(line):
                continue
            if not header_done:
                match = field_line_re.match(line)
                if match:
                    key, value = match.groups()
                    key = key.lower()
                    if key == 'name':
                        self._name = value.strip()
                    elif key == 'columns':
                        self._columns = int(value)
                    else:
                        logger.warning("Unknown 'key:value' pair %r", line)
                    continue
                else:
                    header_done = True
            match = color_line_re.match(line)
            if not match:
                logger.warning("Expected 'R G B [Name]', not %r", line)
                continue
            r, g, b, col_name = match.groups()
            col_name = col_name.strip()
            r = float(clamp(int(r), 0, 0xff))/0xff
            g = float(clamp(int(g), 0, 0xff))/0xff
            b = float(clamp(int(b), 0, 0xff))/0xff
            if r == g == b == 0 and col_name == self._EMPTY_SLOT_NAME:
                self.append(None)
            else:
                col = RGBColor(r, g, b)
                col.__name = col_name
                self._colors.append(col)
        if not silent:
            self.info_changed()
            self.sequence_changed()
            self.match_changed()
开发者ID:Griatch,项目名称:dopey,代码行数:55,代码来源:palette.py


示例5: calcBGOffset

 def calcBGOffset(self, cameraFocusX, cameraFocusY,
                  windowWidth, windowHeight,
                  backgroundWidth, backgroundHeight):
     '''Return the amount to offset the background.
     (cameraFocusX, cameraFocusY) is the spot where the camera is focused
     to, usually the center of the Avatar.
     '''
     return (-clamp(cameraFocusX-(windowWidth/2),
                    0, (backgroundWidth-windowWidth)),
             -clamp(cameraFocusY-(windowHeight/2),
                    0, (backgroundHeight-windowHeight))
            )
开发者ID:avuserow,项目名称:yoyobrawlah,代码行数:12,代码来源:level.py


示例6: walkTo

    def walkTo(self, oldRect, hPower, vPower):
        self.velocity[0] = clamp(self.velocity[0]+hPower, self.xMin, self.xMax)
        self.velocity[1] = clamp(self.velocity[1]+vPower, self.yMin, self.yMax)

        newRect = oldRect.move(*self.velocity)

        oob = outOfBounds(self.walkMask, self.feetPos, newRect.midtop)

        if oob:
            #TODO: more precise
            return oldRect
        else:
            return newRect
开发者ID:avuserow,项目名称:yoyobrawlah,代码行数:13,代码来源:walker.py


示例7: load

    def load(self, filehandle):
        """Load contents from a file handle containing a GIMP palette.

        If the format is incorrect, a `RuntimeError` will be raised.
        """
        comment_line_re = re.compile(r'^#')
        field_line_re = re.compile(r'^(\w+)\s*:\s*(.*)$')
        color_line_re = re.compile(r'^(\d+)\s+(\d+)\s+(\d+)\s*(?:\b(.*))$')
        fp = filehandle
        self.clear()
        line = fp.readline()
        if line.strip() != "GIMP Palette":
            raise RuntimeError, "Not a valid GIMP Palette"
        header_done = False
        line_num = 0
        for line in fp:
            line = line.strip()
            line_num += 1
            if line == '':
                continue
            if comment_line_re.match(line):
                continue
            if not header_done:
                match = field_line_re.match(line)
                if match:
                    key, value = match.groups()
                    key = key.lower()
                    if key == 'name':
                        self.__name = value
                    elif key == 'columns':
                        self.__columns = int(value)
                    else:
                        print "warning: unknown 'key: value' pair '%s'" % line
                    continue
                else:
                    header_done = True
            match = color_line_re.match(line)
            if not match:
                print "warning: expected R G B [Name]"
                continue
            r, g, b, col_name = match.groups()
            r = float(clamp(int(r), 0, 0xff))/0xff
            g = float(clamp(int(g), 0, 0xff))/0xff
            b = float(clamp(int(b), 0, 0xff))/0xff
            if r == g == b == 0 and col_name == self.__EMPTY_SLOT_NAME:
                self.append(None)
            else:
                col = RGBColor(r, g, b)
                self.append(col, col_name)
开发者ID:jesterKing,项目名称:mypaint-xsheet,代码行数:49,代码来源:palette.py


示例8: get_pos_for_color

 def get_pos_for_color(self, col):
     nr, ntheta = self.get_normalized_polar_pos_for_color(col)
     mgr = self.get_color_manager()
     if mgr:
         ntheta = mgr.distort_hue(ntheta)
     nr **= 1.0 / self.SAT_GAMMA
     alloc = self.get_allocation()
     wd, ht = alloc.width, alloc.height
     radius = self.get_radius(wd, ht, self.BORDER_WIDTH)
     cx, cy = self.get_center(wd, ht)
     r = radius * clamp(nr, 0, 1)
     t = clamp(ntheta, 0, 1) * 2 * math.pi
     x = int(cx + r * math.cos(t)) + 0.5
     y = int(cy + r * math.sin(t)) + 0.5
     return x, y
开发者ID:benpope82,项目名称:mypaint,代码行数:15,代码来源:adjbases.py


示例9: paint

 def paint(self, x, y):
   if(self.ground[x][y]):
     h, w = len(self.ground[0]), len(self.ground)
     if(self.style == 'Block'):
       c = '█'
     elif(self.style == 'Silhouette'):
       neighbors = (self.ground[x-1][y],
                    self.ground[(x+1)%w][y],
                    self.ground[x][y-1],
                    self.ground[x][min(y+1,h-1)])
       diags =(self.ground[x-1][y-1],
               self.ground[(x+1)%w][y-1],
               self.ground[x-1][min(y+1,h-1)],
               self.ground[(x+1)%w][min(y+1,h-1)])
       block = ( not(neighbors[0] and neighbors[2] and diags[0]),
                 not(neighbors[1] and neighbors[2] and diags[1]),
                 not(neighbors[0] and neighbors[3] and diags[2]),
                 not(neighbors[1] and neighbors[3] and diags[3]))
       c = blockgraphics.blocks[block]
     elif(self.style == 'Dirt'):
       grass = clamp(max([0]+[y-yi for yi in range(0, y) if self.ground[x][yi]]), 0, 4)
       c = ['█', '▓', '▒', '░', ' '][grass]
     elif(self.style == 'Candy'):
       block = (waves[0][(x*2  +2*y)%10],
                waves[0][(x*2+1+2*y)%10],
                waves[1][(x*2  +2*y)%10],
                waves[1][(x*2+1+2*y)%10])
       c = blockgraphics.blocks[block]
     elif(self.style == 'Pipes'):
       neighbors = (self.ground[x][y-1] or y % 4 == 0,
                    self.ground[x-1][y] or y % 4 == 0,
                    self.ground[(x+1)%w][y] or x % 4 == 0,
                    self.ground[x][(y+1)%h] or x % 4 == 0)
       c = blockgraphics.pipes[neighbors]
     self.groundchars[x][y] = c
开发者ID:whentze,项目名称:loltanks,代码行数:35,代码来源:world.py


示例10: applyTool

    def applyTool(self, vHelix, fr, to):
        """
        fr (from) and to take the format of (strandType, base)
        """
        fr = list(vHelix.validatedBase(*fr, raiseOnErr=False))
        to = list(vHelix.validatedBase(*to, raiseOnErr=False))
        if (None, None) in (fr, to):  # must start and end on a valid base
            return False
        beginBase = (vHelix, fr[0], fr[1])
        leftDragLimit, rightDragLimit = self.dragLimitsForDragOpBeginningAtBase(beginBase)
        to[1] = util.clamp(to[1], leftDragLimit, rightDragLimit)

        # 1 corresponds to rightwards
        if to[1] == fr[1]:
            dragDir = 0
        elif to[1] > fr[1]:
            dragDir = 1
        else:
            dragDir = -1

        dragOp = self.operationForDraggingInDirectionFromBase(dragDir, beginBase)
        op, frOffset, toOffset = dragOp[0:3]

        if op == self.ConnectStrand:
            color = dragOp[3]
            vHelix.connectStrand(fr[0], fr[1]+frOffset, to[1]+toOffset, color=color)
        elif op == self.ClearStrand:
            colorL, colorR = dragOp[3:5]
            vHelix.legacyClearStrand(fr[0], fr[1]+frOffset, to[1]+toOffset, colorL=colorL, colorR=colorR)
        elif op == self.RemoveXOver:
            vHelix.removeXoversAt(fr[0], fr[1], newColor=vHelix.palette()[0])
        else:
            assert(op == self.NoOperation)
开发者ID:MatthewMcAteer,项目名称:cadnano2,代码行数:33,代码来源:selecttool.py


示例11: mutate_brain

	def mutate_brain(brain):
		""" Add random mutations to a brain """
		# For all synapses: shift in some direction with random chance
		for s in brain.synapses:
			if util.rand(0, 1) <= Agent._MUTATE_SYNAPSE_ODDS:
				s.weight += Agent._MUTATE_SYNAPSE_SHIFT * util.rand(-1, 1)
				s.weight = util.clamp(s.weight, -1, 1)
开发者ID:pkorth,项目名称:intraspecies-cooperation,代码行数:7,代码来源:actors.py


示例12: attemptToCreateStrand

 def attemptToCreateStrand(self, virtualHelixItem, strandSet, idx):
     self._tempStrandItem.hideIt()
     sIdx = self._startIdx
     if abs(sIdx-idx) > 1:
         idx = util.clamp(idx, self._lowDragBound, self._highDragBound)
         idxs = (idx, sIdx) if self.isDragLow(idx) else (sIdx, idx)
         self._startStrandSet.createStrand(*idxs)
开发者ID:alaindomissy,项目名称:cadnano2,代码行数:7,代码来源:penciltool.py


示例13: paint_foreground_cb

    def paint_foreground_cb(self, cr, wd, ht):
        b = int(self.BORDER_WIDTH)
        col = self.get_managed_color()
        amt = self.get_bar_amount_for_color(col)
        amt = float(clamp(amt, 0, 1))
        bar_size = int((self.vertical and ht or wd) - 1 - 2 * b)
        if self.vertical:
            amt = 1.0 - amt
            x1 = b + 0.5
            x2 = wd - x1
            y1 = y2 = int(amt * bar_size) + b + 0.5
        else:
            x1 = x2 = int(amt * bar_size) + b + 0.5
            y1 = b + 0.5
            y2 = ht - y1

        cr.set_line_cap(cairo.LINE_CAP_ROUND)
        cr.set_line_width(5)
        cr.move_to(x1, y1)
        cr.line_to(x2, y2)
        cr.set_source_rgb(0, 0, 0)
        cr.stroke_preserve()

        cr.set_source_rgb(1, 1, 1)
        cr.set_line_width(3.5)
        cr.stroke_preserve()

        cr.set_source_rgb(*col.get_rgb())
        cr.set_line_width(0.25)
        cr.stroke()
开发者ID:benpope82,项目名称:mypaint,代码行数:30,代码来源:adjbases.py


示例14: predict

 def predict(self, user_id, item_id):
     pred = self.U[user_id].dot(self.VT[:, item_id])
     return clamp(
         pred +
         self.avg_item.get(item_id, self.global_avg_item) +
         self.offset_user.get(user_id, self.global_offset_user),
         1, 5)
开发者ID:yamitzky,项目名称:Regularized-SVD,代码行数:7,代码来源:baseline.py


示例15: _draw_agents

	def _draw_agents(self):
		""" Draw all Agent objects to the screen """
		blue = pygame.Color(100,100,200)
		black = pygame.Color(0,0,0)
		green = pygame.Color(0,255,0)
		red = pygame.Color(255,0,0)
		for agent in self.model.agents:
			health = agent.health / 100.0
			health = util.clamp(health, 0, 1)
			pos = util.int_tuple(agent.get_pos())
			radians = agent.radians
			radius = agent.radius
			# Draw a black line showing current heading
			line_p0 = agent.get_pos()
			line_r = radius * 1.5
			line_p1 = (line_p0[0] + math.cos(radians)*line_r,
					   line_p0[1] + math.sin(radians)*line_r)
			pygame.draw.line(self.buffer, black, line_p0, line_p1, 2)
			# Draw a circle for the body. Blue for normal, red for attacking
			col = blue
			if agent.interact_attacked:
				col = red
			pygame.draw.circle(self.buffer, col, pos, radius, 0)
			pygame.draw.circle(self.buffer, black, pos, radius, 1)
			# Draw a green health bar
			rect = (int(agent.x)-20, int(agent.y)-30, 40, 3)
			pygame.draw.rect(self.buffer, red, rect)
			rect = (int(agent.x)-20, int(agent.y)-30, int(40*health), 3)
			pygame.draw.rect(self.buffer, green, rect)
开发者ID:pkorth,项目名称:intraspecies-cooperation,代码行数:29,代码来源:gfx_driver.py


示例16: selectToolMouseMove

 def selectToolMouseMove(self, modifiers, idx):
     """
     Given a new index (pre-validated as different from the prev index),
     calculate the new x coordinate for self, move there, and notify the
     parent strandItem to redraw its horizontal line.
     """
     idx = util.clamp(idx, self._lowDragBound, self._highDragBound)
开发者ID:andreaforapani,项目名称:cadnano2,代码行数:7,代码来源:endpointitem.py


示例17: quote_context

        def quote_context():
            if channel is None:
                self.send_message(reply_target, "command only available in channel :(")
                return

            if len(args) < 1:
                self.send_message(reply_target, "missing sequence id :(")
                return

            try:
                seq_id = int(args[0])
            except ValueError:
                self.send_message(reply_target, "bad sequence id :(")
                return

            lines = 20
            if len(args) > 1:
                try:
                    lines = clamp(0, int(args[1]), 100)
                except ValueError:
                    pass

            context = self.database.quote_context(reply_target, seq_id, lines)

            if len(context) == 0:
                self.send_message(reply_target, "no context found :(")
                return

            link = link_generator.make_pastebin("\r\n".join(context), self.pastebin_api_key)
            self.send_message(reply_target, link if link is not None else "couldn't upload to pastebin :(")
开发者ID:proog,项目名称:nda,代码行数:30,代码来源:nda.py


示例18: main

def main():
  rospy.loginfo("Starting up...")

  ## Load options
  global throttle
  throttle = THROTTLE
  args = sys.argv[1:]
  while len(args) > 0:
    opt = args.pop(0)
    if opt == "-t":
      throttle = clamp( int(args.pop(0)), -100, 100)

  ## Set up ROS publisher & subscriber
  global pub
  pub = rospy.Publisher(PUBLISH_TOPIC, ServoCommand)
  rospy.Subscriber(SUBSCRIBE_TOPIC, FuriousState, on_update)
  rospy.init_node(NODE_NAME)

  ## Initialization
  global dist_r, dist_l, dist_f
  global escape
  dist_r = dist_l = dist_f = MAX_RANGE
  escape = 0

  rospy.loginfo("dist_l, dist_r, steer,   dist_f, throt")
  
  rospy.spin()

  ## Shutdown
  rospy.loginfo("Shutting down normally...")
开发者ID:UBC-Snowbots,项目名称:IARRC2010,代码行数:30,代码来源:irCommander.py


示例19: pos2linecol

    def pos2linecol(self, ctrl, x, y):
        lineh = self.getLineHeight(ctrl)
        ls = ctrl.sp.lines

        sel = None

        for t in self.getScreen(ctrl, False)[0]:
            if t.line == -1:
                continue

            # above or to the left
            if (x < t.x) or (y < t.y):
                continue

            # below
            if y > (t.y + lineh - 1):
                continue

            # to the right
            w = t.fi.fx * (len(ls[t.line].text) + 1)
            if x > (t.x + w - 1):
                continue

            sel = t
            break

        if sel == None:
            return (None, None)

        line = sel.line
        l = ls[line]

        column = util.clamp(int((x - sel.x) / sel.fi.fx), 0, len(l.text))

        return (line, column)
开发者ID:duanbailey,项目名称:trelby,代码行数:35,代码来源:viewmode.py


示例20: testClamp

	def testClamp(self):
		self.assEqual(util.clamp(-.3), 0.0)
		self.assEqual(util.clamp(0.0), 0.0)
		self.assEqual(util.clamp(.2), .2)
		self.assEqual(util.clamp(.9), .9)
		self.assEqual(util.clamp(1.0), 1.0)
		self.assEqual(util.clamp(1.6), 1.0)
		self.assEqual(util.clamp(1.6,1.2,1.9), 1.6)
		self.assEqual(util.clamp(1.6,2.8,8.9), 2.8)
开发者ID:swantescholz,项目名称:coding,代码行数:9,代码来源:util_test.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python util.clip函数代码示例发布时间:2022-05-27
下一篇:
Python util.chunks函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap