示例#1
0
def calculateTimeToReachBall():
    interceptPoint = getBallIntersectionWithRobot(maintainCanSeeBall=False)
    interceptToGoal = ENEMY_GOAL_CENTER.minus(interceptPoint)
    interceptToGoalHeading = normalisedTheta(
        math.atan2(interceptToGoal.y, interceptToGoal.x))
    return calculateTimeToReachPose(Global.myPos(), Global.myHeading(),
                                    interceptPoint, interceptToGoalHeading)
def redraw(screen, selectedPiece, currentGame):
    Global.drawBackground(screen)
    screen.blit(Global.boardImg, Global.boardImgRect)
    screen.blit(Global.TimerBoard, Global.TimerBoardRect)

    # draw the menu options onto the screen
    screen.blit(titleText, (Global.boardImgRect.left,
                            int(Global.boardImgRect.top / 2 - titleSize / 2)))
    if currentGame:
        screen.blit(continueGameText, continueGameRect)
    screen.blit(newGameText, newGameRect)
    screen.blit(loadGameText, loadGameRect)
    screen.blit(pieceText, pieceRect)
    screen.blit(backgroundText, backgroundRect)
    screen.blit(boardText, boardRect)
    screen.blit(timerText, timerRect)
    if selectedPiece is not None:
        selectedPiece.select(screen)

    # draw the player pieces
    for player in Global.Player1List:
        player.draw(screen)
    for player in Global.Player2List:
        player.draw(screen)
    pygame.display.update()
    Global.toUpdate.clear()
示例#3
0
    def makeProject(self):
        config = [self.ids[i].text for i in self.ids]
        
        if ("" not in config):
            xbounds = int(config[3])
            os.mkdir(save_path)

            progress, text = 40, "Fill database"
            Clock.schedule_once(partial(self.do_update, progress, text))

            createDatabase.fill(save_path, file_path, xbounds)

            createDatabase.makeConfig(save_path, config)

            progress, text = 70, "Calculating"
            Clock.schedule_once(partial(self.do_update, progress, text))

            t.sleep(4)

            self.popup.dismiss()
            
            Global.changePath(save_path)

            self.parent.current = "WeldFigure"

        else:
            self.popup.dismiss()
            showError("incorrect input")
示例#4
0
 def GetMACD(self, today):
     info = CalculationInfo.MACDInfo()
     info.today = self.datas[today].date
     info.DIFF = Global.Float4Down5Up(self.GetDiff(today))
     info.DEA = Global.Float4Down5Up(self.GetDEA(today, 10, self.EMA_Times))
     info.MACD = Global.Float4Down5Up((info.DIFF - info.DEA) * 2)
     return info
示例#5
0
 def isPercussion_name(self, name):
     for ins in Global.drum_kit:
         name = Global.get_name_from_label(name)
         ins_name = Global.get_name_from_label(ins)
         if ins_name == name:
             return True
     return False
示例#6
0
    def select(self, table, where=None, sort=None, *args, **kwargs):

        query = 'SELECT '
        keys = args
        values = tuple(kwargs.values())
        l = len(keys) - 1

        for i, key in enumerate(keys):
            query += "`" + key + "`"
            if i < l:
                query += ","
        ## End for keys

        if len(keys) == 0:
            query += '* '

        query += 'FROM %s' % table

        if where:
            query += " WHERE %s" % where
        ## End if where

        if sort:
            query += " ORDER BY %s" % sort

        self.__open()

        if self.__session.execute(query, values) > 0:
            Global.print_query(query)
            result = self.__session.fetchall()
            self.__close()
            return result
        else:
            self.__close()
            return False
示例#7
0
def svr_models(valSet,is_visual,C_cons=1e3):
    
    min_max_scaler = preprocessing.MinMaxScaler()
    svr_lin = SVR(kernel='linear', C=C_cons)
    
    if valSet == None:
        data, label = creatingMat.createDataSet()
        X_train = data[0:-100]
        Y_train = label[0:-100]
        X_test = data[-100:]
        Y_test = label[-100:]
    else:
        X_train = valSet[0]
        Y_train = valSet[1]
        X_test = valSet[2]
        Y_test = valSet[3]   
        X_minmax = min_max_scaler.fit_transform(X_train + X_test)
        Y_minmax = min_max_scaler.fit_transform(Y_train + Y_test)
        X_train_minmax = array(X_minmax[0:-100])
        Y_train_minmax = array(Y_minmax[0:-100])
        X_test_minmax = array(X_minmax[-100:])
        Y_test_minmax = array(Y_minmax[-100:])
    Y_train_minmax_1d=[i[0] for i in Y_train_minmax ]
    Y_result=svr_lin.fit(X_train_minmax,Y_train_minmax_1d).predict(array(X_test_minmax))
    Y_result_new=[[i] for i in Y_result]
    F_result = Global.getAccuracy(Y_test_minmax, Y_result_new, 20)
    return  Global.getCorrelation(Y_test_minmax, Y_result_new)
示例#8
0
 def text(x, y, s):
     clr = g.highlight(s)
     if clr:
         painter.setPen(clr)
     else:
         painter.setPen(QtCore.Qt.black)
     painter.drawText(x, y, unicode(g.pretty(s)))
示例#9
0
 def test_3(self):
     ipFailCounter = IPFailCounter.IPFailCounter(Global.MAX_TRY_BY_IP)
     srv = ChallengeServer.ChallengeServer("1.1.1.1", ipFailCounter)
     msg, keep = srv.receive(Global.getMessage(1, testUserName))
     self.assertTrue(keep)
     self.assertEqual(msg[0], "2")
     msg, keep = srv.receive(Global.getMessage(4, testUserChallenges[msg[2:].rstrip()]))
示例#10
0
def SendEmail(content):
    # qq邮箱smtp服务器
    host_server = 'smtp.qq.com'
    # sender_qq为发件人的qq号码
    sender_qq = Global.get_value('qq')
    # pwd为qq邮箱的授权码
    pwd = Global.get_value('mailpwd')
    # 发件人的邮箱
    sender_qq_mail = Global.get_value('qq')+'@qq.com'
    # 收件人邮箱
    receiver = Global.get_value('mail')
    # 邮件的正文内容
    mail_content = content['content']

    # 邮件标题
    mail_title = content['title']

    # ssl登录

    try:
        smtp = SMTP_SSL(host_server)
        smtp.login(sender_qq, pwd)
        msg = MIMEText(mail_content, "plain", 'utf-8')
        msg["Subject"] = Header(mail_title, 'utf-8')
        msg["From"] = sender_qq_mail
        msg["To"] = receiver
        smtp.sendmail(sender_qq_mail, receiver, msg.as_string())
        smtp.quit()
    except Error as e:
        print(e)
示例#11
0
 def send_data(self, data):
     print "To Server %s Port %s, Send_data:" % (Global.gw_server_ip,
                                                 self._sock_port),
     Global.dump_data(data)
     if Global.debug == 0:
         if self._conn is not None:
             if Global.NET_PROTOCOL == 'TCP':
                 try:
                     self._conn.send(data)
                 except socket.error as err:
                     if err.errno == errno.WSAECONNRESET:
                         self._conn.close()
                         print err, 'Reconnect to %s:%s' % (
                             Global.gw_server_ip, self._sock_port)
                         sock_client = socket.socket()
                         while True:
                             try:
                                 sock_client.connect(
                                     (Global.gw_server_ip, self._sock_port))
                             except socket.error as e:
                                 print 'Fail to setup socket reconnection %s:%s,try once again' % (
                                     Global.gw_server_ip, self._sock_port)
                                 time.sleep(1)
                                 continue
                             sock_client.setblocking(False)
                             self.set_sock_conn(sock_client)
                             print "set %s connection" % Global.NET_PROTOCOL
                             break
             else:
                 dst_port = (Global.gw_server_ip, self._sock_port)
                 self._conn.sendto(data, dst_port)
     else:
         Global.dump_data(data)
     pass
示例#12
0
def tick(blackboard):
    """
    This is the main entry point from C++ into our Python behaviours and back.

    More specifically it is the bridge from which C++ calls Python inside
    the runswift executable, and receives a BehaviourRequest back.

    Currently called in `robot/perception/behaviour/python/PythonSkill.cpp`,
    the `PythonSkill::execute()` C++ function, and explicitly the line
    `behaviour_tick(bb)`.

    :param blackboard: The runswift Blackboard, a bunch of things
        stored in global memory.
    :return: A `robot.BehaviourRequest()` instance, defined in C++ inside
        `robot/types/BehaviourRequest.hpp`.
    """
    # Update all blackboard dependent helper modules.
    Global.update(blackboard)
    TeamStatus.update(blackboard)
    FieldGeometry.update(blackboard)
    Timer.update(blackboard)
    LedOverride.reset()
    Sonar.update(blackboard)

    # Set the HeadSkill
    HeadSkill.singleton.resetRequestState()

    global skill_instance
    if not skill_instance:
        skill_instance = skill_instance_factory(blackboard)

    if isinstance(skill_instance, BehaviourTask):
        # On every tick of the perception thread, we update the blackboard,
        # tick the skill, and then return the resulting behaviour request.
        skill_instance.world.update(blackboard)
        skill_instance.world.b_request = robot.BehaviourRequest()
        skill_instance.world.b_request.actions = robot.All()
        skill_instance.tick()
        request = skill_instance.world.b_request
    else:
        # Backwards compat for old style skills if called directly via -s.
        request = skill_instance.tick(blackboard)

    headRequest = HeadSkill.singleton.tick(blackboard)
    request.actions.head = headRequest.actions.head

    # LED colouring.
    if len(blackboard.vision.uncertain_balls) > 0:
        request.actions.leds.rightEye = LEDColour.blue
    elif len(blackboard.vision.balls) > 0:
        request.actions.leds.rightEye = LEDColour.red
    else:
        request.actions.leds.rightEye = LEDColour.off

    if Global.amILost():
        request.actions.leds.leftEye = LEDColour.off
    else:
        request.actions.leds.leftEye = LEDColour.cyan

    return request
def getBallIntersectionWithRobot(maintainCanSeeBall=True):
    intervalInSeconds = 1
    numSecondsForward = 1.0  # Estimate the ball position up to 1 second away
    numIterations = int(round(numSecondsForward / intervalInSeconds))
    FRICTION = 0.9  # friction per second
    FRICTION_PER_ITERATION = FRICTION**intervalInSeconds

    ballVel = Global.ballWorldVelHighConfidence()
    ballPos = Global.ballWorldPos()
    myHeading = Global.myHeading()

    # If he ball is moving slowly, just chase the ball directly
    if ballVel.isShorterThan(10.0):
        return ballPos

    # Dont bother chasing a moving ball if its quite close.
    if Global.ballDistance() < 600.0:
        return ballPos

    ballVel.scale(intervalInSeconds)

    robotPos = Global.myPos()

    interceptPoint = ballPos
    bestChasePoint = ballPos.clone()

    seconds = 0.0
    for i in xrange(0, numIterations):
        seconds += intervalInSeconds

        interceptPoint.add(ballVel)
        ballVel.scale(FRICTION_PER_ITERATION)

        toIntercept = interceptPoint.minus(robotPos)
        toInterceptHeading = math.atan2(toIntercept.y, toIntercept.x)

        # How far we need to turn to point at the interceptPoint
        toInterceptTurn = abs(
            MathUtil.normalisedTheta(toInterceptHeading - myHeading))

        timeToTurn = toInterceptTurn / TURN_RATE
        timeToWalk = toIntercept.length() / WALK_RATE

        canReach = (timeToTurn + timeToWalk) <= seconds

        # Calculate difference in heading to the current ball position and the intersect position
        # to make sure we don't turn too far and lose sight of the ball
        v1 = interceptPoint.minus(robotPos).normalised()
        v2 = ballPos.minus(robotPos).normalised()
        heading = v1.absThetaTo(v2)

        if maintainCanSeeBall and heading > math.radians(75):
            return bestChasePoint

        if canReach:
            return bestChasePoint
        else:
            bestChasePoint = Vector2D.makeVector2DCopy(interceptPoint)

    return bestChasePoint
示例#14
0
    def draw_ins_list_item(self, cr, i, j):  # i: category, j: item
        [x0, y0, x1, y1] = self.get_item_bound(i, j)
        cr.rectangle(x0, y0, x1 - x0, y1 - y0)
        cr.set_source_rgb(1, 1, 1)
        cr.fill()

        cr.set_font_size(12)
        m = j % 5
        d = int(j / 5)
        label = Global.instrument_list[Global.instrument_category[i]][j]
        name = Global.get_name_from_label(label)

        is_hover = (i == self.hover_ins_list[0]
                    and j == self.hover_ins_list[1])
        is_selected = self.is_selected_instrument(name)

        img = Global.get_img_med_label(label)
        if not img == 'None':
            self.set_rgba_ins_item_icon(cr, is_hover, is_selected)
            try:
                cr.mask_surface(
                    cairo.ImageSurface.create_from_png(img),
                    Global.instrument_category_x[i] - 4 + self.xdiv * d,
                    self.y + 78 + self.ydiv * m)
                cr.fill()
            except:
                print img
        self.set_rgba_ins_item_label(cr, is_hover, is_selected)
        self.set_font(cr)
        cr.move_to(Global.instrument_category_x[i] + self.xdiv * d,
                   self.y + 78 + self.ydiv * m + 84)
        cr.show_text(label)
示例#15
0
def main():

    # configuration of the parser for the arguments
    parser = optparse.OptionParser()
    parser.add_option('--sure',
                      dest='sure',
                      action='store_true',
                      help="Option to bypass the 'Are You Sure' question",
                      default=False)
    parser.set_description(description='When this command is called it shuts'
                           ' down the server')

    (opts, _) = parser.parse_args()

    if not opts.sure:
        Noyes = input('ARE YOU SURE you really want to'
                      ' shutdown the server [NO/yes]: ')
        if not Noyes or not 'yes'.startswith(Noyes.lower()):
            print('Wise decision! you did not shutdown the server.')
            return
        print('Ok, then...')

    # Load execution script
    Global.handle_request('SHUTDOWN', wait_for_reply=False)
    print('The server was shutdown!')
示例#16
0
def submit_jobs(NewQueue):
    for k, v in NewQueue.items():
        #create temporary directory
        tempdir = '/'.join([TEMPFOLDER,FOLDERFORMAT.format(k)])
        os.mkdir(tempdir)
        #create files
        Global.createfile(name ='/'.join([tempdir,SUBMITSCRNAME.format(k)]),
                          data =SUBMITSCR.format(v.execution_script_name, k,
                                                 JOBDONE),
                          stats= Global.MyStats(st_mode=0o774))
        for name, info in v.execution_script.items():
            Global.createfile(name = '/'.join([tempdir,name]),
                              data = info[1], stats = info[0])
        for name, info in v.input_files.items():
            Global.createfile(name='/'.join([tempdir, name]),
                              data = info[1], stats = info[0])
        for name, info in v.output_files.items():
            Global.createfile(name='/'.join([tempdir, name]),
                              data = info[1], stats = info[0])
        #submit job
        proc = psutil.Popen('/'.join([tempdir, SUBMITSCRNAME.format(k)]),
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL,
                            start_new_session=True,
                            cwd = tempdir)
        #update queues
        v.status_key = 'r'
        proc.set_nice(MyConfigs.niceness)
        MyQueue.update({k:v})
        jobid2proc.update({k:proc})
        #create job file for, if necessary, later loading
        Global.createfile(name = '/'.join([tempdir,JOBFILE.format(proc.pid)]),
                          data = repr(v))
示例#17
0
def DecideNextAction():
    global g_CurrentGenerator
    global g_CurrentState
    Global.frameReset()

    # Tracking Visual Ball!!!
    HelpTrack.trackVisualBall()

    if g_CurrentGenerator == None:
        if g_CurrentState == STATE_INITIALIZE:
            print "Initializing"
            g_CurrentGenerator = StateInitialize()
        if g_CurrentState == STATE_READY:
            print "Ready"
            g_CurrentGenerator = StateReady()
        elif g_CurrentState == STATE_EXECUTE:
            print "Executing"
            g_CurrentGenerator = StateExecute()
        elif g_CurrentState == STATE_UPDATE:
            print "Update"
            g_CurrentGenerator = StateUpdate()
        elif g_CurrentState == STATE_FIX:
            print "Fixing"
            g_CurrentGenerator = StateFix()
        elif g_CurrentState == STATE_DONE:
            print "Done"
            g_CurrentGenerator = StateDone()

    next_state = g_CurrentGenerator.next()
    if next_state != g_CurrentState:
        g_CurrentState = next_state
        g_CurrentGenerator = None
示例#18
0
    def updateChatWindow(self, view, rowId):

        if rowId == view.amigosWidget.row(view.amigosWidget.currentItem()):
            objUser = User_Controller.User(self.model)
            view.messagensListWidget.clear()
            ansArray = self.model.select('amigos', 'rowId = %i' % rowId, None,
                                         'id', 'nome')
            freindId = Global.dict2var(ansArray, 'id')
            name = Global.dict2var(ansArray, 'nome')
            view.mengagemLabel.setText('Conversa com %s' % name)
            messages = self.model.select(
                'mensagens',
                '(id_remetente = %i AND id_destinatario = %i) OR (id_remetente = %i AND id_destinatario = %i)'
                % (objUser.MyID(), freindId, freindId, objUser.MyID()), 'data')

            if messages:
                for row in messages:
                    item = QtWidgets.QListWidgetItem(
                        str(objUser.nameById(row['id_remetente'])) +
                        ' disse:  ' +
                        str(row['data'].strftime("%d/%m/%Y - %H:%M")))
                    item.setFont(QtGui.QFont('Verdana', 8, QtGui.QFont.Bold))
                    view.messagensListWidget.addItem(item)
                    message = QtWidgets.QListWidgetItem(str(row['mensagem']))
                    view.messagensListWidget.addItem(message)
                    view.messagensListWidget.scrollToBottom()
                    view.messagensListWidget.scrollToItem(message, 0)
        else:
            item = view.amigosWidget.item(rowId)
            item.setFont(QtGui.QFont('Verdana', 7, QtGui.QFont.Bold))
示例#19
0
    def load_config(self):
        global dir_auto, dir_python
        if os.path.exists(self.configfile):
            self.config = ConfigObj(self.configfile, encoding='UTF8')
        else:
            self.config = None
            return
        #print "self.config=",self.config
        self.ui.path_auto.setText(unicode(self.config['app']["dir_auto"]))
        self.ui.path_tcl.setText(unicode(self.config['app']["dir_tcl"]))
        self.ui.path_python.setText(unicode(self.config['app']["dir_python"]))
        #self.ui.dut_type.setItemText(0,unicode(self.config['app']["product"]))
        self.ui.dut_user.setText(unicode(self.config['app']["user"]))
        self.ui.dut_pwd.setText(unicode(self.config['app']["pwd"]))
        self.ui.dut_ip.setText(unicode(self.config['app']["url"]))
        self.ui.cmp_user.setText(unicode(self.config['app']["user_cmp"]))
        self.ui.cmp_pwd.setText(unicode(self.config['app']["pwd_cmp"]))
        self.ui.cmp_ip.setText(unicode(self.config['app']["url_cmp"]))

        if not 'dir_log' in self.config['app']:
            self.ui.path_log.setText(
                os.path.join(mainpath, "results").decode("gbk"))
        else:
            self.ui.path_log.setText(unicode(self.config['app']["dir_log"]))
        # if "ssid" in self.config['app']:
        # self.ui.ssid_name.setText(unicode(self.config['app']["ssid"]))
        # if "ssid5" in self.config['app']:
        # self.ui.ssid_name5g.setText(unicode(self.config['app']["ssid5"]))
        dir_auto = unicode(self.ui.path_auto.text())
        #print dir_auto
        GlobalVar.set_dir_auto(self.ui.path_auto.text())
        dir_python = unicode(self.ui.path_python.text())
        GlobalVar.set_dir_python(self.ui.path_python.text())
示例#20
0
def report_data_OP(self, message, datatype):
    cmd_name, serial_port_name, cmd_data = message.getData()
    print cmd_name, serial_port_name

    #step 1 get the payload
    cmd_payload = cmd_data[4:-2]

    Global.dump_data(cmd_payload)
    dev_uuid, data_len = struct.unpack('IB',cmd_payload[:5])

    raw_data = cmd_payload[5:]
    print "uuid %d,Raw_data" %dev_uuid,
    Global.dump_data(raw_data)
    uuid_range=((dev_uuid-1)/400 +1) *400

    print 'uuid_range %d' %uuid_range

    serial_actor, ap_node = Global.serial_actor_map[serial_port_name]

    if ap_node is None or not isinstance(ap_node, Gw_AP):
        print("get ap_node from serial_actor_map error")
        return
    # support sock send
    default = None
    #sock_actor = Global.device_sock_actor_map.get(struct.pack('>I', dev_uuid), default)
    sock_actor = Global.device_sock_actor_map.get(uuid_range, default)
    if sock_actor is None or not isinstance(sock_actor, Actor):
        print("get sock_actor from device_sock_actor_map error")
        return
    self.sendMessage(sock_actor, Message(Global.HosttoCloud_Data_EVENT, raw_data))
    pass
示例#21
0
def linear_model_normal(valSet,is_visual):
    if valSet==None:
        data, label = creatingMat.createDataSet()
        X_train=data[0:-100]
        Y_train=label[0:-100]
        X_test=data[-100:]
        Y_test=label[-100:]
    else:
        X_train = valSet[0]
        Y_train = valSet[1]
        X_test = valSet[2]
        Y_test = valSet[3]
        
    linearModel_normal=LinearModel.myLM()
    linearModel_normal.myLMtrain(X_train , Y_train )   
    Y_result=linearModel_normal.myLMpredict(X_test)
    
    
    if is_visual==True:
        
        #visualization
        makeVisual(Y_test,Y_result,'Linear Regression Using Normal equation')
        Global.getAccuracy(Y_test, Y_result, 20)
    else:
        #----------------------- return Global.getAccuracy(Y_test, Y_result, 20)
        return Global.getCorrelation(Y_test, Y_result)
示例#22
0
 def TryMove(self, points):
     startP = points[0]
     Global.WriteLog("Òƶ¯Â·µã:" + str(points))
     for i in range(1, len(points)):
         midP = points[i]
         if startP[0] == midP[0]:
             stepY = (-1, 1)[startP[1] < midP[1]]
             for y in range(startP[1] + stepY, midP[1] + stepY, stepY):
                 if not self.SlotTypes[startP[0]][y] == 0:
                     Global.WriteLog("¼ì²âµ½ÕÏ°­µã:" + str(startP[0]) +
                                     "-" + str(y))
                     return 0
         else:
             stepX = (-1, 1)[startP[0] < midP[0]]
             for x in range(startP[0] + stepX, midP[0] + stepX, stepX):
                 if not self.SlotTypes[x][startP[1]] == 0:
                     Global.WriteLog("¼ì²âµ½ÕÏ°­µã:" + str(x) + "-" +
                                     str(startP[1]))
                     return 0
         startP = points[i]
     # Òƶ¯
     startP = points[0]
     endP = points[len(points) - 1]
     self.SlotTypes[endP[0]][endP[1]] = self.SlotTypes[startP[0]][startP[1]]
     self.SlotTypes[startP[0]][startP[1]] = 0
     self.EmptySlots.remove(endP)
     self.EmptySlots.append(startP)
     return 1
示例#23
0
    def draw_instruments(self, cr):
        for i in range(self.n_ins):
            #            if i == self.active_instrument:
            #cr.set_source_rgb(Global.colors[i].red_float, Global.colors[i].green_float, Global.colors[i].blue_float)
            cr.set_source_rgb(Global.get_color_red_float(i),
                              Global.get_color_green_float(i),
                              Global.get_color_blue_float(i))
            #            else:
            #                cr.set_source_rgb(0.4, 0.4, 0.4)
            self.create_curvy_rectangle(cr, 678 + i * 60, self.y + 21, 52, 52,
                                        4)
            cr.fill()
            if i == self.active_instrument:
                cr.set_source_rgb(1, 1, 1)
                cr.set_line_width(2)
                self.create_curvy_rectangle(cr, 678 + i * 60 + 1,
                                            self.y + 21 + 1, 50, 50, 4)
                cr.stroke()
            if i == self.active_instrument:
                cr.set_source_rgb(1, 1, 1)
            else:
                cr.set_source_rgb(0.16, 0.16, 0.16)
#                cr.set_source_rgb(0.32, 0.32, 0.32)
            label = self.instruments[i]
            img = Global.get_img_sm_label(label)
            cr.mask_surface(cairo.ImageSurface.create_from_png(img),
                            678 + i * 60 + 4, self.y + 21 + 4)
            cr.fill()
            if i == self.hover_instrument:
                cr.set_source_rgba(1, 1, 1, 0.5)
                self.create_curvy_rectangle(cr, 678 + i * 60, self.y + 21, 52,
                                            52, 4)
                cr.fill()
示例#24
0
def frameReset():
    VisionLink.startProfile("hFrameResetR")
    Action.frameReset()
    Global.frameReset()
    sGrab.frameReset()
    hStuck.frameReset()
    VisionLink.stopProfile("hFrameResetR")
示例#25
0
def main(mode):
    __opts__ = salt.config.client_config('%s/plugins/salt/etc/salt/master' %
                                         gl.get_value('wkdir'))
    event = salt.utils.event.MasterEvent(__opts__['sock_dir'])
    for eachevent in event.iter_events(full=True):
        ret = eachevent['data']
        print eachevent
        if "salt/job/" in eachevent['tag']:
            #Return Event
            if ret.has_key('id') and ret.has_key('jid') and (
                    ret.has_key('return') or ret.has_key('stdout')):
                try:
                    ret['fun']
                except:
                    ret['fun'] = 'ssh.shell'
                finally:
                    pass
                #Ignore saltutil.find_job event
                if ret['fun'] == "saltutil.find_job" or ret[
                        'fun'] == "mine.update":
                    continue
                # 重写SALT-SSH模块中无法获取success状态,统一获取retcode代码
                ret['success'] = ret['retcode']
                try:
                    ret['return']
                except:
                    ret['return'] = ret['stdout'] + ret['stderr']
                finally:
                    pass
                if mode == 'rundaemon':
                    # write SQL mode (存在阻塞问题)
                    #i=1
                    #while True:
                    #   sql = ''' select count(*) as count from apscheduler_logs where jid=%s '''
                    #   result = readDb(sql,(ret['jid'],))
                    #   if result[0].get('count') == 0 and (ret['fun'] == 'cmd.run' or ret['fun'] == 'ssh.shell'):
                    #      time.sleep(1) #延迟写入数据库1s
                    #      if i > 10:
                    #         break
                    #      i+=1
                    #   else:
                    #      sql = ''' UPDATE apscheduler_logs SET full_ret=CONCAT(full_ret,"_sep_",%s),run_status=%s where jid=%s '''
                    #      break
                    #writeDb(sql,(json.dumps(ret),ret['success'],ret['jid']))
                    #
                    # storage result file
                    mkdir('%s/plugins/salt/jid/%s' %
                          (gl.get_value('wkdir'), ret['jid'][0:8]))
                    rfile = open(
                        '%s/plugins/salt/jid/%s/%s' %
                        (gl.get_value('wkdir'), ret['jid'][0:8], ret['jid']),
                        'a')
                    rfile.write('%s\n' % json.dumps(ret))
                    rfile.close()
                else:
                    print ret
                    # Other Event
            else:
                pass
def getBallIntersectionWithRobot(maintainCanSeeBall = True):
   intervalInSeconds = 1
   numSecondsForward = 1.0 # Estimate the ball position up to 1 second away
   numIterations = int(round(numSecondsForward / intervalInSeconds))
   FRICTION = 0.9 # friction per second
   FRICTION_PER_ITERATION = FRICTION ** intervalInSeconds

   ballVel = Global.ballWorldVelHighConfidence()
   ballPos = Global.ballWorldPos()
   myHeading = Global.myHeading()

   # If he ball is moving slowly, just chase the ball directly
   if ballVel.isShorterThan(10.0):
      return ballPos

   # Dont bother chasing a moving ball if its quite close.
   if Global.ballDistance() < 600.0:
      return ballPos

   ballVel.scale(intervalInSeconds)

   robotPos = Global.myPos()
   
   interceptPoint = ballPos
   bestChasePoint = ballPos.clone()

   seconds = 0.0
   for i in xrange(0, numIterations):
      seconds += intervalInSeconds

      interceptPoint.add(ballVel)
      ballVel.scale(FRICTION_PER_ITERATION)

      toIntercept = interceptPoint.minus(robotPos)
      toInterceptHeading = math.atan2(toIntercept.y, toIntercept.x)
   
      # How far we need to turn to point at the interceptPoint
      toInterceptTurn = abs(MathUtil.normalisedTheta(toInterceptHeading - myHeading))

      timeToTurn = toInterceptTurn / TURN_RATE
      timeToWalk = toIntercept.length() / WALK_RATE

      canReach = (timeToTurn + timeToWalk) <= seconds
      
      # Calculate difference in heading to the current ball position and the intersect position
      # to make sure we don't turn too far and lose sight of the ball
      v1 = interceptPoint.minus(robotPos).normalised()
      v2 = ballPos.minus(robotPos).normalised()
      heading = v1.absThetaTo(v2)

      if maintainCanSeeBall and heading > math.radians(75):
         return bestChasePoint

      if canReach:
         return bestChasePoint
      else:
         bestChasePoint = Vector2D.makeVector2DCopy(interceptPoint)

   return bestChasePoint
示例#27
0
 def test_3(self):
     ipFailCounter = IPFailCounter.IPFailCounter(Global.MAX_TRY_BY_IP)
     srv = ChallengeServer.ChallengeServer("1.1.1.1", ipFailCounter)
     msg, keep = srv.receive(Global.get_message(1, testUserName))
     self.assertTrue(keep)
     self.assertEqual(msg[0], "2")
     msg, keep = srv.receive(
         Global.get_message(4, testUserChallenges[msg[2:].rstrip()]))
示例#28
0
def globalPoseToRobotRelativePose(globalVector, globalHeading):
    robotPos = Global.myPos()
    robotHeading = Global.myHeading()

    rrVector = globalVector.minus(robotPos).rotate(-robotHeading)
    rrHeading = globalHeading - robotHeading

    return rrVector, rrHeading
示例#29
0
def delip(IP_dic):
    global IPPool
    try:
        IPPool.remove(IP_dic)
    except:
        Global.instatesinf("IP池中已无此IP".decode('utf-8'))
    a=("已将%s清除出IP池".decode('utf-8'))%(IP_dic["ip"])
    Global.instatesinf(a)
def update_portfolio_excelpart(p:portfolio):
    '''
    Further build the holding portfolio's content based on excel information
    Attention: This must be used after update_portfolio_onlinepart in Online_Access
    '''
    sheet0=Global.get_value('sheet0');
    sheet1=Global.get_value('sheet1');
    sheet2=Global.get_value('sheet2');
    rowcount=Global.get_value('rowcount');

    #Locate the last record except today's.
    i=rowcount[3];
    while(1):
        lastdate=sheet2.range('b{0}'.format(i)).value;
        if lastdate != None:
            lastDate=lastdate.strftime("%Y/%m/%d");
            if lastDate != p.date:
                break;
        i-=1;
    period=datetime.datetime.now().day-lastdate.day-1;

    #Read in that historical record. This will be used to calculate the earning of monetary funds.
    end=ExcelF.find_the_end(sheet2,'b',i,rowcount[3]);
    tempp=read_portfolio_in_history(i,end);

    for a in p.content:
        if a.type==0:
            p.stockvalue+=a.curvalue;
        elif a.type==1:
            p.bondvalue+=a.curvalue;
        elif a.type==2:
            for b in tempp.content:
                    if a.ID == b.ID:
                        a.curvalue=b.curvalue+(b.curvalue+period*a.curgrowth/360)/10000*a.curneat;
            a.arevenue=a.curvalue-a.inivalue;
            a.agrowth=a.arevenue/a.inivalue;
            p.monevalue+=a.curvalue;
        elif a.type==3:
            startdate=a.ID;
            today=datetime.datetime.now();
            enddate=today;
            for b in tempp.content:
                if a.name==b.name:
                    a.curvalue=b.curvalue+b.curvalue*a.curgrowth/360*(enddate-lastdate).days;
            a.arevenue=a.curvalue-a.inivalue;
            a.agrowth=a.arevenue/a.inivalue;
            p.savevalue+=a.curvalue;
        p.pvalue+=a.curvalue;

    p.inivalue=float(sheet0.range('b3').value);
    p.sparevalue=float(sheet0.range('h8').value);
    p.pvalue+=p.sparevalue;
    p.prevenue=p.pvalue-p.inivalue;
    p.pgrowth=p.prevenue/p.inivalue;

    #Calculate the ratio of each asset.
    for a in p.content:
        a.ratio=a.curvalue/p.pvalue;
示例#31
0
 def test_2(self):
     ipFailCounter = IPFailCounter.IPFailCounter(Global.MAX_TRY_BY_IP)
     srv = ChallengeServer.ChallengeServer("1.1.1.1", ipFailCounter)
     msg, keep = srv.receive(Global.get_message(1, testUserName))
     self.assertTrue(keep)
     self.assertEqual(msg[0], "2")
     msg, keep = srv.receive(Global.get_message(4, "abcdefgh"))
     self.assertFalse(keep)
     self.assertEqual(msg[0], "6")
def globalPoseToRobotRelativePose(globalVector, globalHeading):

   robotPos = Global.myPos()
   robotHeading = Global.myHeading()

   rrVector = globalVector.minus(robotPos).rotate(-robotHeading)
   rrHeading = globalHeading - robotHeading

   return rrVector, rrHeading
示例#33
0
class ChallengeServer:
    errorUser = Global.get_message(3, "user KO")
    errorBadFormat = None
    errorBadProtocol = None
    errorChallenge = Global.get_message(6, "challenge KO")

    def __init__(self, clientIp, ipFailCounter):
        self.__clientIp = clientIp
        self.__ipFailCounter = ipFailCounter
        self.__state = State.StateWaitUser
        self.__user = None

    def error(self, message=None):
        self.__state = State.StateError
        self.__ipFailCounter.fail(self.__clientIp)
        return message, False

    def receive(self, msg):
        print("receive '%s' state %s" % (msg.rstrip(), self.__state))
        message = Global.Message(msg)

        # Check validity of the message.
        if not message.is_valid():
            print("Invalid message received.")
            return self.error(self.errorBadFormat)

        if message.get_code() == 1 and self.__state == State.StateWaitUser:

            if not re.match(Global.REGEX_USER, message.get_content()):
                print("Error991")
                return self.error(self.errorUser)

            self.__user = User.User(message.get_content())

            if self.__user.is_user_valid():
                self.__state = State.StateWaitChallenge
                return Global.get_message(2, self.__user.get_challenge()), True
            else:
                print("Error992")
                return self.error(self.errorUser)

        elif message.get_code(
        ) == 4 and self.__state == State.StateWaitChallenge:

            if not re.match(Global.REGEX_CHALLENGE, message.get_content()):
                print("Error993")
                return self.error(self.errorChallenge)

            if self.__user.is_challenge_valid(message.get_content()):
                self.__state = State.StateConnected
                return Global.get_message(5, "Challenge ok"), True
            else:
                print("Error994")
                return self.error(self.errorChallenge)

        print("Error995")
        return self.error(self.errorBadProtocol)
示例#34
0
    def write_data(self, data):
        print("To serial_id  %s, write_data done*************************" %
              self._serialport)

        if Global.debug == 0:
            self._serialfd.write(data)
        else:
            Global.dump_data(data)
        pass
def count():
    sheet1=Global.get_value('sheet1');
    sheet2=Global.get_value('sheet2');
    a='a{0}'.format(stock_start_row-1)
    b='a{0}'.format(monetary_start_row-1)
    c='a{0}'.format(save_start_row-1)
    obj=zip([sheet1,sheet1,sheet1,sheet2],[a,b,c,'f1']);
    rowcount=tuple(map(ExcelF.count_rows,obj));
    Global.set_value('rowcount',rowcount);
示例#36
0
 def test_2(self):
     ipFailCounter = IPFailCounter.IPFailCounter(Global.MAX_TRY_BY_IP)
     srv = ChallengeServer.ChallengeServer("1.1.1.1", ipFailCounter)
     msg, keep = srv.receive(Global.getMessage(1, testUserName))
     self.assertTrue(keep)
     self.assertEqual(msg[0], "2")
     msg, keep = srv.receive(Global.getMessage(4, "abcdefgh"))
     self.assertFalse(keep)
     self.assertEqual(msg[0], "6")
示例#37
0
def init(**args):
	Global.init()
	Global.API.register_callback(int(args['gameid']),
		Logic, Render, None,
		on_key_msg = None, 
		on_mouse_msg = onMouseMsg, 
		on_mouse_wheel =  None)
	Global.API.register_game_room_msgdefine_and_callback(Message.MsgDefine, EventMap.EventMap)
	MCreator.initial()
	GameManager.Initial()
示例#38
0
	def __init__(self, room_id=0, name='', mode=0, host=0, pwd='', max_num=0):

		super(BufanRoom, self).__init__(room_id, name, mode, host, pwd, max_num)

		self.MsgMgr = hall_callback.get_game_room_msgmgr()
		
		# 玩家管理器
		self.gameMgr = GameMgr.GameMgr()
		
		Global.init(self)
示例#39
0
def normal(acl, player):
    Armagetronad.SendCommand("INCLUDE settings.cfg")
    Armagetronad.SendCommand("SINCLUDE settings_custom.cfg")
    Global.reloadPlayerList()
    if Mode.current_mode:
        Mode.current_mode.activate(True) #@UndefinedVariable (for Eclipse)
    for player in Player.players.values():
        player.kill()
    Global.state="normal"
    global data
    data=None
示例#40
0
文件: System.py 项目: Lee-12/lnmVPN
def getbackupsetinfo():
    info=[]
    status,result=cmds.gettuplerst('find %s/backupset -name \'*.bkt\' -exec basename {} \;|sort' % gl.get_value('plgdir'))
    for i in result.split('\n'):
        if str(i) != "":
           infos={}
           infos['filename']=str(i)
           infos['filesize']=os.path.getsize('%s/backupset/%s' % (gl.get_value('plgdir'),i))
           cctime=os.path.getctime('%s/backupset/%s' % (gl.get_value('plgdir'),i))
           infos['filetime']=time.strftime('%Y%m%d%H%M%S',time.localtime(cctime))
           info.append(infos)
    return json.dumps(info)
示例#41
0
def test_thin():
    import operator
    def betterthan(l, r):
        return l[0] == r[0] and len(l) > len(r)

    l = ["abcd", "a", "ab", "abc", "b", "bc"]
    r = g.thin(l, betterthan, lambda x: x)

    eq_(r,["abcd", "bc"])

    l = ['a1', 'b1', 'c1', 'a', 'd', 'b']
    r = g.thin(l, betterthan)
    eq_(set(r), set(['a1', 'b1', 'c1', 'd']))
示例#42
0
def getAlt(core):
    ret = ["@action", "@agent", "@des"]
    
    word = Global.lookup(core)

    cat = Global.get_cat(word.category())
    if cat is not None:
        acList = cat.getActions()
        ret[0] = acList[random.randint(1,len(acList)-1)].val
        agList = cat.getAgents()
        ret[1] = agList[random.randint(1,len(agList)-1)].val
        deList = cat.getDescs()
        ret[2] = deList[random.randint(1,len(deList)-1)].val
    return ret
示例#43
0
def deal_with_finished_jobs():
    for k, v in MyQueue.items():
        if v.status_key in {'e', 't', 'q'}:
            folder = '/'.join([TEMPFOLDER, FOLDERFORMAT.format(k)])
            files = os.listdir(path=folder)
            for file in set(files) - (v.input_files.keys() |
                                       set([JOBDONE,
                                            SUBMITSCRNAME.format(k)])):
                data = Global.load_file(os.path.join(folder,file))
                v.output_files.update({file: data})
            for file in v.input_files.keys(): # Reload the input_files
                data = Global.load_file(os.path.join(folder,file))
                v.input_files.update({file: data})
            MyQueue.update({k:v})
示例#44
0
   def printStateChange(self, prevState, nextState):
      """Print State Change.

      Prints the change in state to terminal in our common format if the state changes.
      """

      if prevState != nextState:
         Log.info(
            "%20s: %20s -> %20s (%ld | %ld)",
            self.__class__.__name__,
            prevState.__class__.__name__,
            nextState.__class__.__name__,
            Global.currentVisionTime(),
            Global.ticksSinceStart()
         )
示例#45
0
    def __init__(self):
        super(GraphWidget, self).__init__()

        self.timerId = 0

        scene = QtGui.QGraphicsScene(self)
        scene.setItemIndexMethod(QtGui.QGraphicsScene.NoIndex)
        scene.setSceneRect(-20, -20, 790, 240)

        self.setScene(scene)
        self.setCacheMode(QtGui.QGraphicsView.CacheBackground)
        self.setViewportUpdateMode(QtGui.QGraphicsView.BoundingRectViewportUpdate)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorViewCenter)

        self.neck = NeckWidget(0, 0, 750, 150)
        self.neck.tuning = NeckModel(E9)

        scene.addItem(self.neck)

        self.scale(2.0, 2.0)
        self.setMinimumSize(0, 500)
        self.setWindowTitle("Pedal Steel")
        self.timerId = self.startTimer(1000)

        #
        # pedals
        # 
        spacing = 50
        pedalx = 200
        pedaly = 170

        self.pedals = {}
        pedals = self.pedals
        for k in knee_classes:
            name = str(k)
            gi = PedalWidget(name)
            gi.setPos(pedalx, pedaly)
            pedalx += spacing
            pedals[k] = gi
            scene.addItem(gi)

        pedalx = 200
        pedaly = 185
        for p in pedal_classes:
            name = str(p)
            gi = PedalWidget(name)
            gi.setPos(pedalx, pedaly)
            pedalx += spacing
            pedals[p] = gi
            scene.addItem(gi)

        g.tonic = [C]
        self.tonicwidget = QtGui.QGraphicsTextItem(g.letter(g.tonic[0]) + g.chordname)
        self.tonicwidget.setPos(0,170)
        font = self.tonicwidget.font()
        font.setPointSize(30)
        self.tonicwidget.setFont(font)
        scene.addItem(self.tonicwidget)
def calculateTimeToReachPose(myPos, myHeading, targetPos, targetHeading=None):
   toTarget = targetPos.minus(myPos)
   toTargetHeading = math.atan2(toTarget.y, toTarget.x)
   
   # How far we need to turn to point at the targetPos
   toTargetTurn = abs(MathUtil.normalisedTheta(toTargetHeading - myHeading))

   # The straightline distance to walk to the targetPos
   toTargetDistance = toTarget.length()

   # How far we need to turn once we get to the targetPos so that we are facing the targetHeading
   if targetHeading is None:
      toTargetHeadingTurn = 0.0
   else:
      toTargetHeadingTurn = abs(MathUtil.normalisedTheta(toTargetHeading - targetHeading))
      
   # approximate time it takes to avoid robots on the way
   avoidTime = 0
   if toTargetDistance > 400 :
       robots = Global.robotObstaclesList()
       for robot in robots:
           robotPos = Vector2D.makeVector2DCopy(robot.pos)
           toRobot = robotPos.minus(myPos)
           dist = toRobot.length()
           heading = abs(MathUtil.normalisedTheta(toRobot.heading() - toTargetHeading))
           # further away robots are less relevant
           distValue = min(1, dist / toTargetDistance)
           # robots aren't in the way are less relevant
           headingValue = min(1, heading / (math.pi/2))
           # heading is more relevant than distance, has enough weighting to revert striker bonus time
           combinedValue = (1 - distValue ** 4)*(1 - headingValue ** 2) * 3
           if combinedValue > avoidTime :
               avoidTime = combinedValue
   
   return toTargetTurn/TURN_RATE + toTargetDistance/WALK_RATE + toTargetHeadingTurn/CIRCLE_STRAFE_RATE + avoidTime
示例#47
0
文件: __main__.py 项目: Jan-David/Dip
def main():
    #read instance
    #path=sys.argv[1]
    id,n,p,d,s,w,cxy,V,mytype,id = read('Instances/pmedcap1.dat')
    
    CVPMP.init(n,p,d,s,w,V)
    z, solution = CVPMP.Solver()

    #display solution
    data = Global.path()+'/out.dat'
    f = open(data,'w')
        
    for s in solution:
        i=s[0]
        for j in s[1]:
            if i == j:
                mytype = 1
            else:
                mytype = 0

            f.write('%d\t%d\t%d\t%d\t%d\n'%
                        (mytype, j, i, cxy[j][0], cxy[j][1]))

    f.close();
    draw.draw(data, mytype, id)
示例#48
0
	def fill_card_pile(self):
		for suit in Global.suits:
			for num in Global.numbers:
				Global.cards_pile.append(Cards(suit=(suit,num)))
		Global.cards_pile=Global.randomize(Global.cards_pile)
		'''
		for item in cards_pile:
			item.show()
		'''
		self.deck_packages = {
			# user cards_packages
			'deck_cat_0':			 Deck(160, 400, type="cat"),
			'deck_cat_1':			 Deck(320, 400, type="cat"),
			'deck_cat_2':			 Deck(480, 400, type="cat"),
			'deck_cat_3':			 Deck(640, 400, type="cat"),
			
			# computer cards_package
			'deck_pile':		Deck(15, 210, type="pile"),
			
			# fish cards_packages
			'deck_fish_0':		Deck(160, 20, type="fish"),
			'deck_fish_1':		Deck(320, 20, type="fish"),
			'deck_fish_2':		Deck(480, 20, type="fish"),
			'deck_fish_3':		Deck(640, 20, type="fish"),
		}
		
		self.deck_packages['deck_pile'].fill_deck(42)
		for deck in self.deck_packages:
			if(deck!='deck_pile'):
				self.deck_packages[deck].fill_deck(1)
def nearFieldBorder():
   pos = Global.myPos()
   # print "Near Field edge - %5d > %5d , %5d > %5d? " % (pos.x, Constants.FIELD_LENGTH/2 - 100, pos.y, Constants.FIELD_WIDTH/2 - 100),
   if abs(pos.x) > Constants.FIELD_LENGTH/2 - 300 or abs(pos.y) > Constants.FIELD_WIDTH/2 - 300:
      # print "Yes."
      return True
   #print "No."
   return False
示例#50
0
def test_grip_superset():
    g = Grip([], [1, 0, 0])
    h = Grip([], [1, 0, 1])
    assert g != h
    assert h.superset_of(g)
    assert not g.superset_of(h)
    h = Grip([], [1, 0, 0])
    assert g == h
    
    g = Grip([], [0, 0, 0])
    h = Grip([], [0, 0, 1])
    assert h.superset_of(g)
    assert not g.superset_of(h)

    g = Grip([P1], [0, 0, 0])
    h = Grip([], [0, 0, 1])
    assert not h.superset_of(g)
    assert not g.superset_of(h)
示例#51
0
文件: System.py 项目: Lee-12/lnmVPN
def delbackupset(filename):
    s = request.environ.get('beaker.session')
    if filename != "":
       x,y=cmds.gettuplerst('rm -rf %s/backupset/%s' % (gl.get_value('plgdir'),filename))
       if x == 0:
          msg = {'color':'green','message':u'备份集删除成功'}
       else:
          msg = {'color':'red','message':u'备份集删除失败'}
    return template('backupset',session=s,msg=msg)
示例#52
0
 def impl():
     g.tonic[0] = key
     def myhighlight(x):
         if x in g.chord:
             return QtCore.Qt.red
         return None
     g.highlight = myhighlight
     w.tonicwidget.setPlainText(g.letter(key) + g.chordname)
     w.update()
     setchordtype('n', w)()
示例#53
0
def handle_request(*items):
    server_down = True
    while server_down:
        try:
            result = Global.handle_request(*items, exit_on_err=False)
            server_down = False
        except Global.ServerDown:
            time.sleep(WAIT_TIME)
            locally_manage_jobs()
    return result
示例#54
0
def makeVisual(Y_test,Y_result,label_string):
        Xaxi = range(1, 50)
        Yaxi = [Global.getAccuracy(Y_test, Y_result, i) for i in Xaxi ]
        plt.axis([0, 70, 0, 52])
        plt.xlabel('Success percentage')
        plt.ylabel('Error Tolerance')
        plt.title('Success percentage Against Error Tolerance ')
        plt.plot(Yaxi, Xaxi, color='red', label=label_string, linewidth=2.5, linestyle="-")
        plt.legend()
        plt.show()
示例#55
0
def test_grip_normalize():
    print E9.tuning
    g = Grip([P1, P2], [1,0,0,0,0, 1,0,0,0,0], NeckModel(E9))
    h = g.normalize()
    print "normalized:", h
    assert P2 not in h.pedals
    print h.pedals
    assert h.pedals == set([P1])

    g = Grip([], [1,1,1,1,1, 1,1,1,1,1], NeckModel(E9))
    h = g.normalize()
    assert len(h.pedals) == 0

    g.pedals = set([P5])
    h = g.normalize()
    assert len(h.pedals) == 0

    g = Grip([P2, P3, P4, RL, RR], [0,0,0,0,0, 0,0,0,1,1], NeckModel(E9))
    h = g.normalize()
    assert h.pedals == set([RL, RR])
def getRepulsiveField(obsPos, repScale=1, distThresh=1400):
    Urep = Vector2D(0, 0)
    myPos = Global.myPos()
    dist = myPos.minus(obsPos).length()
    dist = max(EPSILON, dist - Constants.ROBOT_DIAM/2)
    # find new obsPos with modified dist
    direction = obsPos.minus(myPos).normalised()
    obsPos = myPos.plus(direction.multiply(dist))
    if dist <= distThresh :
        Urep = myPos.minus(obsPos).multiply(MAX_REP * repScale * (1/distThresh - 1/dist)/dist)
    return Urep
示例#57
0
def levuser_notif(name):  # don't disclass different ways to leave for the clients
    #------------------------- broadcasting for each online user -----------------------------
    #if len(Global.list_user) != 0:
    for user in Global.list_user:
        if user.name != name:  # not broadcasting the message to himself
            message = Global.message("System(broadcast)", user.name, "\"" + name + "\"" + " has just logged out.")
            Global.message_rep[user.name].append(message)
            Global.event[user.name].set()
    disp = "User \"" + name + "\" logging out notification has been sent!"
    print disp
    Global.log.write(disp + "\n")
    return
示例#58
0
def newuser_notif(name):
    #------------------------- broadcasting for each online user -----------------------------
    #if len(Global.list_user) != 0:
    for user in Global.list_user:
        if user.name != name:  # not broadcasting the message to himself
            message = Global.message("System(broadcast)", user.name, "\"" + name + "\"" + " has just logged in.")
            Global.message_rep[user.name].append(message)
            Global.event[user.name].set()
    disp = "New user \"" + name + "\" logging in notification has been sent!"
    print disp
    Global.log.write(disp + "\n")
    return
示例#59
0
def get_results_from_server_and_save():
    ok, ResQueue = handle_request('GIME_RESULTS')
    if not ok:
        return

    for k, v in ResQueue.items():
        working_dir = v.working_dir
        try:
            with open(os.path.join(working_dir, 'test'), mode='w') as fh:
                fh.write('teste')
            os.remove(os.path.join(working_dir, 'test'))
        except PermissionError:
            if not os.path.isdir(RESULTSFOLDER):
                os.mkdir(path=RESULTSFOLDER)
            working_dir = '/'.join([RESULTSFOLDER, FOLDERFORMAT.format(k)])
            os.mkdir(working_dir)

        files = []
        for name, content in v.output_files.items():
            if not name.startswith(JOBFILE[0:4]):
                files.append(name)
                Global.createfile(name=os.path.join(working_dir, name),
                                  data=content[1], stats=content[0])
        for name, content in v.input_files.items():
            files.append(name)
            Global.createfile(name=os.path.join(working_dir, name),
                              data=content[1], stats=content[0])

        # create script to copy the files to the right folder
        if working_dir != v.working_dir:
            rec_file = RECSCRPT.format(working_dir + '/{'+','.join(files)+'}',
                                       v.working_dir)
            Global.createfile(name='/'.join([working_dir, RECSCRPTNAME]),
                              data=rec_file,
                              stats=Global.MyStats(st_mode=0o774))
示例#60
0
def get_new_jobs_and_submit(njobstoget):

    # If it still can run more jobs, I ask the server for new ones:
    if (njobstoget > 0) and MyConfigs.MoreJobs:
        ok, NewQueue = handle_request('GIME_JOBS', njobstoget)
        if not ok:
            return
        for k, v in NewQueue.items():
            # create temporary directory
            tempdir = '/'.join([TEMPFOLDER, FOLDERFORMAT.format(k)])
            os.mkdir(tempdir)
            # create files
            Global.createfile(
                name='/'.join([tempdir, SUBMITSCRNAME.format(k)]),
                data=SUBMITSCR.format(v.execution_script_name, k, JOBDONE),
                stats=Global.MyStats(st_mode=0o774))
            for name, info in v.execution_script.items():
                Global.createfile(name='/'.join([tempdir, name]),
                                  data=info[1], stats=info[0])
            for name, info in v.input_files.items():
                Global.createfile(name='/'.join([tempdir, name]),
                                  data=info[1], stats=info[0])
            for name, info in v.output_files.items():
                Global.createfile(name='/'.join([tempdir, name]),
                                  data=info[1], stats=info[0])
            # submit job
            proc = psutil.Popen('/'.join([tempdir, SUBMITSCRNAME.format(k)]),
                                stdout=subprocess.DEVNULL,
                                stderr=subprocess.DEVNULL,
                                start_new_session=True,
                                cwd=tempdir)
            # update queues
            v.status_key = 'r'
            proc.nice(MyConfigs.niceness)
            MyQueue.update({k: v})
            jobid2proc.update({k: proc})
            # create job file to be loaded later, if necessary:
            Global.createfile(
                name='/'.join([tempdir, JOBFILE.format(proc.pid)]),
                data=repr(v))