def __init__(self): self.blockCounter = 0 self.objCounter = 0 if ( "cache_meta_driver" and "cache_storage_driver" and "cache_block_size" and "cache_meta_size" not in options.keys() ): define("cache_meta_driver", default="mem", help="Metadata Driver") define("cache_storage_driver", default="disk", help="Block Storage system") define("cache_block_size", default=100, help="Cache Block Max size") define("cache_meta_size", default=100, help="Cache Block Max size") storage_plugin = "restfsc.cache.%s.CacheStorageDriver" % options.cache_storage_driver storage_mod = __import__(storage_plugin, globals(), locals(), ["CacheStorageDriver"]) CacheStorageDriver = getattr(storage_mod, "CacheStorageDriver") self.cacheStorageDriver = CacheStorageDriver() meta_plugin = "restfsc.cache.%s.CacheMetaDriver" % options.cache_meta_driver meta_mod = __import__(meta_plugin, globals(), locals(), ["CacheMetaDriver"]) CacheMetaDriver = getattr(meta_mod, "CacheMetaDriver") self.cacheMetaDriver = CacheMetaDriver() self.meta_lock = thread.allocate_lock() self.block_lock = thread.allocate_lock() #####STATS self.num_get = 0 self.num_set = 0 self.num_get_failed = 0
def __init__(self, world, name, center, width = 35, height = 45, beacon_point = Point(0, 0)): # For simple bounding circle computations let the radius be half diagonal WorldObject.__init__(self, center, sqrt(width**2 + height**2)/2) self.wr = width/2 self.hr = height/2 self.world = world self.name = name self.beacon_point = beacon_point # "Forward" is the unit direction vector where the robot is facing # (0, 1) is the "default" (height along the Y axis) self.forward = Point(0, 1) self.left = Point(-self.forward.y, self.forward.x) # Those are state parameters self.leftSpeed = 0 self.rightSpeed = 0 # Camera sensor parameters self.CAMERA_DEPTH = 120 self.CAMERA_SIDE = 100 # Write concurrency lock (we assume reads are atomic, and even if not, just ignore read errors) self.data_lock = thread.allocate_lock() # Whether there's a ball in the grabber self.grabbed_ball = None self.grabbed_ball_lock = thread.allocate_lock()
def __init__(self): self.PROCESSING = True self.SERVER_HOST = "127.0.0.1" self.SERVER_PORT = 51423 self.MY_HOST = "127.0.0.1" self.MY_PORT = "" self.ALL_HOST = "" self.Status={} self.Status["login"]= False self.Status["update"]= 0 self.Status["openwin"] = {} self.NameList = {} self.Username = "" self.BEAT_TIME = 10 self.find_MY_PORT() self.thread_for_p2p() self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((self.SERVER_HOST, self.SERVER_PORT)) self.Buffer = [] self.fileLock = thread.allocate_lock() self.fileLock2 = thread.allocate_lock() self.SendCode = {} self.RecvCode = {} self.ReplyCode = {}
def demoWithLock(): import time import thread def loop0(lock): print 'start loop0 at:', time.ctime() time.sleep(4) print 'loop0 done at:', time.ctime() lock.release() def loop1(lock): print 'start loop1 at:', time.ctime() time.sleep(2) print 'loop1 done at:', time.ctime() lock.release() lock0 = thread.allocate_lock() lock0.acquire() lock1 = thread.allocate_lock() lock1.acquire() thread.start_new_thread(loop0, (lock0,)) thread.start_new_thread(loop1, (lock1,)) while lock0.locked(): pass while lock1.locked(): pass print 'all DONE at:', time.ctime()
def test(): global TID, tid, io, wh, randint, alive import whrandom randint = whrandom.randint TID = 0 # thread ID (1, 2, ...) tid = thread.allocate_lock() # for changing TID io = thread.allocate_lock() # for printing, and 'alive' wh = thread.allocate_lock() # for calls to whrandom alive = [] # IDs of active threads NSORTS = 5 arrays = [] for i in range(NSORTS): arrays.append( range( (i+1)*10 ) ) bar = barrier(NSORTS) finished = event() for i in range(NSORTS): _new_thread(_run_one_sort, arrays[i], bar, finished) finished.wait() print 'all threads done, and checking results ...' if alive: raise ValueError, ('threads still alive at end', alive) for i in range(NSORTS): a = arrays[i] if len(a) != (i+1)*10: raise ValueError, ('length of array', i, 'screwed up') _check_sort(a) print 'test passed!', TID, 'threads created in all'
def __init__(self): Gtk.IconView.__init__(self) self.set_item_width(BACKGROUND_ICONS_SIZE * 1.1) self._model = Gtk.ListStore(object, GdkPixbuf.Pixbuf, str, str) self._model_filter = self._model.filter_new() self._model_filter.set_visible_func(self.visible_func) self.set_model(self._model_filter) area = self.get_area() self.current_path = None pixbuf_renderer = Gtk.CellRendererPixbuf() text_renderer = Gtk.CellRendererText(ellipsize=Pango.EllipsizeMode.END) text_renderer.set_alignment(.5, .5) area.pack_start(pixbuf_renderer, True, False, False) area.pack_start(text_renderer, True, False, False) self.add_attribute (pixbuf_renderer, "pixbuf", 1) self.add_attribute (text_renderer, "markup", 2) text_renderer.set_property("alignment", Pango.Alignment.CENTER) self._loading_queue = [] self._loading_queue_lock = thread.allocate_lock() self._loading_lock = thread.allocate_lock() self._loading = False self._loaded_data = [] self._loaded_data_lock = thread.allocate_lock()
def __init__(self, mod_name = '__main__', launch_file = None): ReplBackend.__init__(self) self.launch_file = launch_file self.mod_name = mod_name self.km = VsKernelManager() if is_ipython_versionorgreater(0, 13): # http://pytools.codeplex.com/workitem/759 # IPython stopped accepting the ipython flag and switched to launcher, the new # default is what we want though. self.km.start_kernel(**{'extra_arguments': self.get_extra_arguments()}) else: self.km.start_kernel(**{'ipython': True, 'extra_arguments': self.get_extra_arguments()}) self.km.start_channels() self.exit_lock = thread.allocate_lock() self.exit_lock.acquire() # used as an event self.members_lock = thread.allocate_lock() self.members_lock.acquire() self.km.shell_channel._vs_backend = self self.km.stdin_channel._vs_backend = self if is_ipython_versionorgreater(1, 0): self.km.iopub_channel._vs_backend = self else: self.km.sub_channel._vs_backend = self self.km.hb_channel._vs_backend = self self.execution_count = 1
def __init__(self, game, extra=None, tile=-1, play=0, is_restore=None): """Overriding is not recommended unless __reduce__ also overridden Argument play is true if should attach new interface.""" self.all_objects=None #class attribute, not for instances if is_restore: self.__dict__.update(is_restore) self.handlers = [] self._lock = allocate_lock() self.myinstance = None GridObject.all_objects.append(self) #Two underscores, mangles to _PlayableObject__playercheck self.add_handler(1, self.__playercheck) self.add_handler(self.init_hp_interval, self.up_hitpoint) self.reinitialise() return self.game = game self.extra = extra if tile != -1: self.tile = tile GridObject.all_objects.append(self) self.handlers = [] self.known = [] self._lock = allocate_lock() if play: self.play() #Two underscores, mangles to _PlayableObject__playercheck self.add_handler(1, self.__playercheck) self.add_handler(self.init_hp_interval, self.up_hitpoint) self.contents = [] self.initialise()
def dl(self): lock1 = thread.allocate_lock() flag1 = thread.allocate_lock() flag2 = thread.allocate_lock() songinfo = '' picpath = '' while True: if len(self.songs)>2 or lock1.locked(): #print "self.song:",len(self.songs) #print "lock1.locked():",lock1.locked() sleep(1) else: if flag1.locked() and songinfo != '': if flag2.locked(): songinfo['picture']=picpath self.songs.append(songinfo) print "new song" songinfo = self.playlist.next() musicname = songinfo['url'].split("/")[-1] picname = songinfo['picture'].split("/")[-1] picpath = TEMP_PATH+picname savepath = TEMP_PATH+musicname lock1.acquire() if flag1.locked(): flag1.release() if flag2.locked(): flag2.release() flag1.acquire() flag2.acquire() print songinfo['picture'] thread.start_new_thread(download.download,(lock1,flag1,songinfo['url'],savepath,flag2,songinfo['picture'],picpath)) songinfo['path']=savepath
def __init__(self, base_dir = '../InputData/GreekGear/GreekGearProductImages', image_output_dirname='../OutputData/GreekGear/GreekGearWebsiteImages', no_of_threads = 10, get_image_size_only = 0, NoOfRetries=0, output_file_to_write_image_sizes = None, writer = None, log_file_sucess_obj = None, log_file_fail_obj = None ): if output_file_to_write_image_sizes == None: output_file_to_write_image_sizes = image_output_dirname + '/' + str(time.time()).replace('.','') + 'image-size.csv' global dirname self.base_dir = base_dir; #fname = 'greekgear_images.txt' #File name which stores various URL's dirname = image_output_dirname # '../OutputData/GreekGear/GreekGearWebsiteImages' #Name of the directory to be created, to store the downloaded images #crosswalk = 'greekgear_images.txt' #Crosswalk file to track the updated id self.MAXTHREADS = no_of_threads # 10 #Max number of threads to be created self.NoOfRetries = NoOfRetries self.get_image_size_only = get_image_size_only if writer == None: self.output_file = output_file_to_write_image_sizes #"".join(["../OutputData/GreekGear/",'GreekGear.com-images-size.csv']) self.final_csv_file = open(self.output_file, "wb") # binary mode to not add extra line breaks between rows in windows self.writer = csv.writer(self.final_csv_file) self.cw_lookup = dict() self.writelock = thread.allocate_lock() self.exitlock = [thread.allocate_lock() for i in range(self.MAXTHREADS)] self.f_open_sucess = log_file_sucess_obj #open(log_file_sucess, 'w') self.f_open_fail = log_file_fail_obj #open(log_file_fail, 'w')
def write(self, data="", flush=0): import thread if flush or len(self._data)>self._maxsize: try: lock = thread.allocate_lock() lock.acquire(1) fd = open(self._path, "ab+") fd.write(self._data + data) self._data = "" fd.close() if lock.locked(): lock.release() return True except: try: fd.close() except: pass try: if lock.locked(): lock.release() except: pass return False else: try: lock = thread.allocate_lock() lock.acquire(1) self._data += data if lock.locked(): lock.release() return True except: return False
def test_dealloc_other_thread(): if not thread: py.test.skip("this is a test about thread") seen = [] someref = [] lock = thread.allocate_lock() lock.acquire() lock2 = thread.allocate_lock() lock2.acquire() def f(): g1 = greenlet(fmain) g1.switch(seen) someref.append(g1) del g1 gc.collect() lock.release() lock2.acquire() greenlet() # trigger release lock.release() lock2.acquire() t = threading.Thread(target=f) t.start() lock.acquire() assert seen == [] assert len(someref) == 1 del someref[:] gc.collect() # g1 is not released immediately because it's from another thread assert seen == [] lock2.release() lock.acquire() assert seen == [greenlet.GreenletExit] lock2.release() t.join()
def __init__(self, config): self.config = config self.MyHost = '' self.ListenPort = self.config['GENERAL']['LISTEN_PORT'] self.sigLock = thread.allocate_lock() # For locking in the sigHandler self.monLock = thread.allocate_lock() # For keeping the monitor thread sane self.watchUpstream = 0 if not self.config['NTLM_AUTH']['NTLM_TO_BASIC']: if not self.config['NTLM_AUTH']['PASSWORD']: tries = 3 print '------------------------' while tries and (not self.config['NTLM_AUTH']['PASSWORD']): tries = tries - 1 self.config['NTLM_AUTH']['PASSWORD'] = getpass.getpass('Your NT password to be used:') if not self.config['NTLM_AUTH']['PASSWORD']: print 'Sorry. PASSWORD is required, bye.' sys.exit(1) else: # TODO: migrate this properly so placeholders aren't required self.config['NTLM_AUTH']['USER'] = '******' self.config['NTLM_AUTH']['PASSWORD'] = '******' # hashed passwords calculation if self.config['DEBUG']['DEBUG']: print ("user:%s") % self.config['NTLM_AUTH']['USER'] print ("passwd:%s") % self.config['NTLM_AUTH']['PASSWORD'] self.config['NTLM_AUTH']['LM_HASHED_PW'] = ntlm_procs.create_LM_hashed_password(self.config['NTLM_AUTH']['PASSWORD']) self.config['NTLM_AUTH']['NT_HASHED_PW'] = ntlm_procs.create_NT_hashed_password(self.config['NTLM_AUTH']['PASSWORD'])
def __init__(self, title='', server=None, handle=0, parent=None): if not server: if parent: server = parent.server else: server = Server.Server() if handle or not self._type: Widget.Widget.__init__(self, server, handle, parent) else: Widget.Widget.__init__(self, server, server.register(title, self._type), parent) self.default_relationship = 'inside' if parent is None: self._widget_registry = {self.handle: self} self._event_registry = EventRegistry() self._event_stack = [] self._infilter_registry = {} if thread is not None: self._run_lock = thread.allocate_lock() self._dispatch_lock = thread.allocate_lock() self.app = self else: parent._notify_new_widget(self) self._widget_registry = parent._widget_registry self._event_registry = parent._event_registry self._event_stack = parent._event_stack self._infilter_registry = parent._infilter_registry if thread is not None: self._run_lock = parent._run_lock self._dispatch_lock = parent._dispatch_lock self.app = parent.app
def __init__(self, port = 10000, logger = null_logger, ns = ""): if not port is types.IntType: pass self.logger = logger port = str(port) path = "xm.rem" if ns != "": #gain access to the xmlrpc server rpc = xmlrpclib.Server("http://127.0.0.1:" + port + "/xmserver.rem") nodes = rpc.listNodes() path = "" for node in nodes: #All nodes export themselves as namespace:node_address if node[:len(ns)] == ns: path = node break if path == "": print "Could not find a matching namespace" pass self.rpc_path = "http://127.0.0.1:%s/%s" % (port, path) # access to the "nodes" table self.lock = thread.allocate_lock() # sort of like a "join" statement self.done = thread.allocate_lock() self.nodes = {} self.attempts = 3
def test_current_frames(self): import sys import time import thread # XXX workaround for now: to prevent deadlocks, call # sys._current_frames() once before starting threads. # This is an issue in non-translated versions only. sys._current_frames() thread_id = thread.get_ident() def other_thread(): print "thread started" lock2.release() lock1.acquire() lock1 = thread.allocate_lock() lock2 = thread.allocate_lock() lock1.acquire() lock2.acquire() thread.start_new_thread(other_thread, ()) def f(): lock2.acquire() return sys._current_frames() frames = f() lock1.release() thisframe = frames.pop(thread_id) assert thisframe.f_code.co_name in ('f', '?') assert len(frames) == 1 _, other_frame = frames.popitem() assert other_frame.f_code.co_name in ('other_thread', '?')
def launch(samplingLogPattern, samplingBSQ): global gnutellaPOP, crawlingQueue, crawlingQueueLock, peerActiveInGnu, peerQueuedInGnu global mainLock, queue samplingLogInit(samplingLogPattern) mainLock = thread.allocate_lock() queue = Queue.PriorityQueue() p2pProtocol = './gnutella_%s' % platform.system().lower() pop = Popen(['nice', 'bash', '-c', 'cd %s; ulimit -n hard; %s' % (os.path.dirname(p2pProtocol), \ p2pProtocol)], stdin = PIPE, stdout=PIPE, stderr=STDOUT, preexec_fn=os.setsid) fin = pop.stdin fout = pop.stdout comm_server.sample_pop = gnutellaPOP = pop crawlingQueueLock = thread.allocate_lock() crawlingQueue = set() peerActiveInGnu = 0 peerQueuedInGnu = 0 thread.start_new_thread(sampler_safety_wrapper, (writer, fin)) thread.start_new_thread(sampler_safety_wrapper, (reader, fout)) try: samplingLoop(samplingBSQ) finally: samplingLogClose() gc.collect()
def __init__(self, maxsize): import thread self._init(maxsize) self.mutex = thread.allocate_lock() self.esema = thread.allocate_lock() self.esema.acquire_lock() self.fsema = thread.allocate_lock()
def __init__(self): Thread.__init__(self) self.too_old_clockssecs = 1000 * 30 # 30 seconds self.midiin_lock = thread.allocate_lock() self.scheduled_lock = thread.allocate_lock() self.midiin = {} self.midiin_add = None self.midiin_del = None self.midiout_del = None self.midiout = {} self.firstevent = 0 self.nextevent = 0 self.keepgoing = True self.clocks_per_second = 192.0 # 96/quarter, 120 bpm self.timenow = Midi.time_now() self.scheduled = [] self.next_scheduled = None self.callback_func = None self.callback_data = None self.outputcallback_func = None self.outputcallback_data = None self._timer_calls = [] self._next_timer = None
def record(v, info, filename, audiofilename, \ mono, grey, greybits, monotreshold, fields): import thread format, x, y, number, rate = info fps = 59.64 # Fields per second # XXX (Strange: need fps of Indigo monitor, not of PAL or NTSC!) tpf = 1000.0 / fps # Time per field in msec # # Go grab # if audiofilename: gl.wintitle('(start audio) ' + filename) audiodone = thread.allocate_lock() audiodone.acquire_lock() audiostart = thread.allocate_lock() audiostart.acquire_lock() audiostop = [] initaudio(audiofilename, audiostop, audiostart, audiodone) audiostart.acquire_lock() gl.wintitle('(rec) ' + filename) try: ninfo, data, bitvec = v.CaptureBurst(info) except sv.error, arg: print 'CaptureBurst failed:', arg print 'info:', info gl.wintitle(filename) return
def __init__(self, agent, p2p=False): # , msgrecv): self._client = agent.getAID().getName() #self.msgrecv = msgrecv self.myAgent = agent self._server = agent.server # Add Disco Behaviour agent.addBehaviour(DiscoBehaviour(), Behaviour.MessageTemplate(Iq(queryNS=NS_DISCO_INFO))) # Add Stream Initiation Behaviour iqsi = Iq() si = iqsi.addChild("si") si.setNamespace(NS_SI) #"http://jabber.org/protocol/si") agent.addBehaviour(StreamInitiationBehaviour(), Behaviour.MessageTemplate(iqsi)) # Add P2P Behaviour self.p2p_ready = False # Actually ready for P2P communication self.p2p = p2p self.p2p_routes = {} self.p2p_lock = thread.allocate_lock() self.p2p_send_lock = thread.allocate_lock() self._p2p_failures = 0 # Counter for failed attempts to send p2p messages if p2p: agent.registerLogComponent("p2p") self.P2PPORT = random.randint(70000, 80000) # Random P2P port number p2pb = P2PBehaviour() agent.addBehaviour(p2pb)
def test_threadstate(self): def thread_proc(start, loop, success, finished): try: try: start.release() x = 1 while not loop.locked(): x = -x except StopIteration: success.acquire() finally: finished.release() start = allocate_lock() start.acquire() loop = allocate_lock() success = allocate_lock() finished = allocate_lock() finished.acquire() tid = start_new_thread(thread_proc, (start, loop, success, finished)) start.acquire() rval = PyThreadState_SetAsyncExc(tid, StopIteration()) if rval > 1: PyThreadState_SetAsyncExc(tid, py_object()) self.fail() self.failUnlessEqual(rval, 1) loop.acquire() finished.acquire() self.failUnless(success.locked())
def run(self, argv): # The real thing starts here # FIXME: Maybe this should be done on __init__? self.config = configlib.ConfigAgent() self.config.parseCmdLine(sys.argv[1:]) # We need some config data before.. self.config.parseConfigFile() # But we also need to give priority to parseCmdLine so it's parsed again... self.config.parseCmdLine(sys.argv[1:]) self.logAgent = logger.LogAgent() self.loadReplyList() self.checkLock() self.createLock() # Prevent the list growing too much if len(self.repliedList) > 500: for i in xrange(len(self.repliedList) - 500): del self.repliedList[0] # Set the timeout # FIXME: Duplicated in configlib.py!!! if self.config.alarmtime != 0: # 60 by default setDefaultSocketTimeout(self.config.alarmtime) self.CLock = thread.allocate_lock() self.repLock = thread.allocate_lock() # Main thread will create per-server threads self.mainThread = threading.Thread(target=self.main) self.mainThread.start() return 0
def __init__(self,init_path): self.path = os.path.realpath(init_path) self.AK = '72UZoe-AJao4469EfG0kSZ1B4CBzmn_WO6wd2fdQ' self.SK = 'Bn6vHxfwuX5IKiruRJsBLNQCmJwzLWr_9CCN89-2' self.BN = 'xiaoyphoto' self.BD = '7xpg1h.com1.z0.glb.clouddn.com' self.wait_time = 3600 self.pre = '' self.user = '' self.passwd = '' self.inflock = thread.allocate_lock() self.ordlock = thread.allocate_lock() self.datlock = thread.allocate_lock() self.lislock = thread.allocate_lock() self.order = [] self.log_state = 0 self.filelist = [] self.clouds = [] self.static_file = '..\\map\\log.txt' self.inf = dict() self.__connect() thread.start_new_thread(self.__run,())
def newConnection(self): '''create a new connection''' connectionPossibilities = self._connectionPossibilities[:] if not connectionPossibilities: return l = thread.allocate_lock() l2 = thread.allocate_lock() def notify(): released = False for p in connectionPossibilities[1:]: self.debug('released:', released) if not released and self.hasConnections(): self.debug('release') l.release() released = True yield if not released: l.release() yield generator = notify() def notify(): with l2: next(generator) l.acquire(False) for possibility in connectionPossibilities: thread.start_new(self._connect, (possibility, notify)) l.acquire() self.debug('hasconnection!!!')
def __init__(self, cfg): BotBase.__init__(self, cfg) self.type = 'irc' self.wait = Wait() self.outputlock = thread.allocate_lock() self.fsock = None self.oldsock = None self.sock = None self.nolimiter = self.cfg['nolimiter'] self.reconnectcount = 0 self.pongcheck = 0 self.nickchanged = 0 self.noauto433 = 0 if not self.state.has_key('alternick'): self.state['alternick'] = self.cfg['alternick'] if not self.state.has_key('no-op'): self.state['no-op'] = [] self.nick = self.cfg['nick'] self.nrevents = 0 self.gcevents = 0 self.outqueues = [Queue.Queue() for i in range(10)] self.tickqueue = Queue.Queue() self.nicks401 = [] self.stopreadloop = False self.stopoutloop = False if self.port == 0: self.port = 6667 self.connectlock = thread.allocate_lock() self.encoding = 'utf-8'
def setUp(self): self.done_mutex = thread.allocate_lock() self.done_mutex.acquire() self.running_mutex = thread.allocate_lock() self.random_mutex = thread.allocate_lock() self.running = 0 self.next_ident = 0
def __init__(self, threads): 'x.__init__(...) initializes x' self.__threads = threads self.__count = 0 self.__main = thread.allocate_lock() self.__exit = thread.allocate_lock() self.__exit.acquire()
def __init__(self, config="regress.json", level='info', suiteDir=None, timeout=-1, numOfThreads=1): self.config = Config(config).configObj setConfig(self.config) self.suites = {} self.log = Logger(level) if timeout == '-1': self.timeout = int(self.config.timeout); else: self.timeout = int(timeout) if numOfThreads == 0: numOfThreads = 1; if not suiteDir: self.suiteDir = self.config.suiteDir if not self.suiteDir: raise Error("2002") else: self.suiteDir = suiteDir self.suiteDir = ExpandCheck.dir_exists(suiteDir, True) self.regressionDir = ExpandCheck.dir_exists(self.config.regressionDir, True) self.logDir = ExpandCheck.dir_exists(self.config.logDir, True) self.setupDir = ExpandCheck.dir_exists(os.path.join(self.suiteDir, self.config.setupDir), True) self.dir_ec = ExpandCheck.dir_exists(os.path.join(self.suiteDir, self.config.eclDir), True) self.dir_ex = ExpandCheck.dir_exists(os.path.join(self.suiteDir, self.config.keyDir), True) self.dir_a = os.path.join(self.regressionDir, self.config.archiveDir) self.dir_r = os.path.join(self.regressionDir, self.config.resultDir) logging.debug("Suite Dir : %s", suiteDir) logging.debug("Regression Dir : %s", self.regressionDir) logging.debug("Result Dir : %s", self.dir_r) logging.debug("Log Dir : %s", self.logDir) logging.debug("ECL Dir : %s", self.dir_ec) logging.debug("Key Dir : %s", self.dir_ex) logging.debug("Setup Dir : %s", self.setupDir) logging.debug("Archive Dir : %s", self.dir_a) self.loggermutex = thread.allocate_lock() self.numOfCpus = 2 ver = getVersionNumbers() if numOfThreads == -1: if (ver['main'] >= 2) and (ver['minor'] >= 7): if 'linux' in sys.platform : command = 'grep cores /proc/cpuinfo | sort -u' cpuInfo = os.popen(command).read() if cpuInfo == "": self.numOfCpus = 1 else: self.numOfCpus = int(cpuInfo.split()[3]) numOfThreads = self.numOfCpus * 2 else: if (ver['main'] <= 2) and (ver['minor'] < 7): numOfThreads = self.numOfCpus * 2 logging.debug("Number of CPUs:%d, NUmber of threads:%d", self.numOfCpus, numOfThreads ) self.maxthreads = numOfThreads self.maxtasks = 0 self.exitmutexes = [thread.allocate_lock() for i in range(self.maxthreads)] self.timeouts = [(-1) for i in range(self.maxthreads)] self.timeoutHandlerEnabled = False; self.timeoutThread = threading.Timer(1.0, self.timeoutHandler)
def initialize(): if DEBUG_LOGGING >0: dev_log_file = open("developerlog.txt","w") dev_log_lock = thread.allocate_lock() if DEVELOPER_LOGGING >0: debug_log_file = open("debuglog.txt","w") debug_log_lock = thread.allocate_lock()
# acquisition was disabled (within the __of__ method for example). It was # inspired by the Tim McLaughlin's GlobalGetRequest proposal, see # http://dev.zope.org/Wikis/DevSite/Proposals/GlobalGetRequest # # Currently it keeps a Context instance, which wraps the request object, # but also other things, like the user's session, as it is required by # the ikaaro CMS. # # The request objects are stored in a dictionary in the Publish module, # whose keys are the thread id. # # Also, we keep the get_request method in the Globals module for backwards # compatibility (with TranslationService for example). _requests = {} _requests_lock = allocate_lock() def get_request(): """Get a request object""" return _requests.get(get_ident(), None) def new_publish(request, module_name, after_list, debug=0, zope_publish=Publish.publish): # Get the process id ident = get_ident()
def __init__(self): rospy.init_node("battery_simulator") # The rate at which to publish the battery level self.rate = rospy.get_param("~rate", 1) # Convert to a ROS rate r = rospy.Rate(self.rate) # The battery runtime in seconds self.battery_runtime = rospy.get_param("~battery_runtime", 30) # seconds # The intial battery level - 100 is considered full charge self.initial_battery_level = rospy.get_param("~initial_battery_level", 100) # Error battery level for diagnostics self.error_battery_level = rospy.get_param("~error_battery_level", 20) # Warn battery level for diagnostics self.warn_battery_level = rospy.get_param("~warn_battery_level", 50) # Initialize the current level variable to the startup level self.current_battery_level = self.initial_battery_level # Initialize the new level variable to the startup level self.new_battery_level = self.initial_battery_level # The step sized used to decrease the battery level on each publishing loop self.battery_step = float( self.initial_battery_level) / self.rate / self.battery_runtime # Reserve a thread lock self.mutex = thread.allocate_lock() # Create the battery level publisher battery_level_pub = rospy.Publisher("battery_level", Float32, queue_size=5) # A service to maually set the battery level rospy.Service('~set_battery_level', SetBatteryLevel, self.SetBatteryLevelHandler) # Create a diagnostics publisher diag_pub = rospy.Publisher("diagnostics", DiagnosticArray, queue_size=5) # Create a dynamic_reconfigure server and set a callback function dyn_server = dynamic_reconfigure.server.Server( BatterySimulatorConfig, self.dynamic_reconfigure_callback) rospy.loginfo("Publishing simulated battery level with a runtime of " + str(self.battery_runtime) + " seconds...") # Start the publishing loop while not rospy.is_shutdown(): # Initialize the diagnostics status status = DiagnosticStatus() status.name = "Battery Level" # Set the diagnostics status level based on the current battery level if self.current_battery_level < self.error_battery_level: status.message = "Low Battery" status.level = DiagnosticStatus.ERROR elif self.current_battery_level < self.warn_battery_level: status.message = "Medium Battery" status.level = DiagnosticStatus.WARN else: status.message = "Battery OK" status.level = DiagnosticStatus.OK # Add the raw battery level to the diagnostics message status.values.append( KeyValue("Battery Level", str(self.current_battery_level))) # Build the diagnostics array message msg = DiagnosticArray() msg.header.stamp = rospy.Time.now() msg.status.append(status) diag_pub.publish(msg) battery_level_pub.publish(self.current_battery_level) self.current_battery_level = max( 0, self.current_battery_level - self.battery_step) r.sleep()
def __init__(self): rospy.init_node("object_follower") # Set the shutdown function (stop the robot) rospy.on_shutdown(self.shutdown) # How often should we update the robot's motion? self.rate = rospy.get_param("~rate", 10) r = rospy.Rate(self.rate) # Scale the ROI by this factor to avoid background distance values around the edges self.scale_roi = rospy.get_param("~scale_roi", 0.8) # The max linear speed in meters per second self.max_linear_speed = rospy.get_param("~max_linear_speed", 0.03) # The minimum linear speed in meters per second self.min_linear_speed = rospy.get_param("~min_linear_speed", 0.002) # The maximum rotation speed in radians per second self.max_rotation_speed = rospy.get_param("~max_rotation_speed", 0.2) # The minimum rotation speed in radians per second self.min_rotation_speed = rospy.get_param("~min_rotation_speed", 0.1) # The x threshold (% of image width) indicates how far off-center # the ROI needs to be in the x-direction before we react self.x_threshold = rospy.get_param("~x_threshold", 0.1) # How far away from the goal distance (in meters) before the robot reacts self.z_threshold = rospy.get_param("~z_threshold", 0.05) # The maximum distance a target can be from the robot for us to track self.max_z = rospy.get_param("~max_z", 2) # The minimum distance to respond to self.min_z = rospy.get_param("~min_z", 0.5) # The goal distance (in meters) to keep between the robot and the person self.goal_z = rospy.get_param("~goal_z", 0.8) # How much do we weight the goal distance (z) when making a movement self.z_scale = rospy.get_param("~z_scale", 0.3) # How much do we weight (left/right) of the person when making a movement self.x_scale = rospy.get_param("~x_scale", 1.0) self.gain = rospy.get_param("~gain", 2.0) # Slow down factor when stopping self.slow_down_factor = rospy.get_param("~slow_down_factor", 0.8) # Initialize the global ROI self.roi = RegionOfInterest() # Publisher to control the robot's movement self.cmd_vel_pub = rospy.Publisher('cmd_vel_mux/input/teleop', Twist) # Intialize the movement command self.move_cmd = Twist() # Get a lock for updating the self.move_cmd values self.lock = thread.allocate_lock() # We will get the image width and height from the camera_info topic self.image_width = 640 self.image_height = 480 # We need cv_bridge to convert the ROS depth image to an OpenCV array self.cv_bridge = CvBridge() self.depth_array = None # Set flag to indicate when the ROI stops updating self.target_visible = False # Wait for the camera_info topic to become available rospy.loginfo("Waiting for camera_info topic...") rospy.wait_for_message('/camera/rgb/camera_info', CameraInfo) # Subscribe to the camera_info topic to get the image width and height rospy.Subscriber('/camera/rgb/camera_info', CameraInfo, self.get_camera_info) # Wait until we actually have the camera data while self.image_width == 0 or self.image_height == 0: rospy.sleep(1) # Wait for the depth image to become available rospy.loginfo("Waiting for depth_image topic...") rospy.wait_for_message('camera/depth/image_raw', Image) # Subscribe to the depth image self.depth_subscriber = rospy.Subscriber("camera/depth/image_raw", Image, self.convert_depth_image, queue_size=1) # Subscribe to the ROI topic and set the callback to update the robot's motion rospy.Subscriber('tld_roi', RegionOfInterest, self.set_cmd_vel) # Wait until we have an ROI to follow rospy.loginfo("Waiting for an ROI to track...") rospy.wait_for_message('tld_roi', RegionOfInterest) rospy.loginfo("ROI messages detected. Starting follower...") # Begin the tracking loop while not rospy.is_shutdown(): # Acquire a lock while we're setting the robot speeds self.lock.acquire() try: # If the target is not visible, stop the robot # if not self.target_visible: # self.move_cmd = Twist() # else: # # Reset the flag to False by default # self.target_visible = False # Send the Twist command to the robot self.cmd_vel_pub.publish(self.move_cmd) finally: # Release the lock self.lock.release() # Sleep for 1/self.rate seconds r.sleep()
def __init__(self): self.value = 0.0 self.lock = thread.allocate_lock()
This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <*****@*****.**> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Functions required to execute app components ============================================ FOR INTERNAL USE ONLY """ import os import stat import thread cfs = {} # for speed-up cfs_lock = thread.allocate_lock() # and thread safety def getcfs(key, filename, filter=None): """ Caches the *filtered* file `filename` with `key` until the file is modified. :param key: the cache key :param filename: the file to cache :param filter: is the function used for filtering. Normally `filename` is a .py file and `filter` is a function that bytecode compiles the file. In this way the bytecode compiled file is cached. (Default = None) This is used on Google App Engine since pyc files cannot be saved. """
class Server(object): @property def name(self): return camera.name from thread import allocate_lock lock = allocate_lock() from persistent_property import persistent_property ip_address = persistent_property("GigE_camera.{name}.ip_address","pico20.niddk.nih.gov:2000") def get_address(self): return self.ip_address.split(":")[0] def set_address(self,value): self.ip_address = value+":"+str(self.port) address = property(get_address,set_address) def get_port(self): if ":" in self.ip_address: port = self.ip_address.split(":")[-1] else: port = "2000" try: port = int(port) except: port = 2000 return port def set_port(self,value): self.ip_address = self.address+":"+str(value) port = property(get_port,set_port) def get_running(self): return self.server is not None def set_running(self,value): if self.running != value: if value: self.start() else: self.stop() running = property(get_running,set_running) server = None def start(self): """make a threaded server, listen/handle clients forever""" import socket for self.port in range(self.port,self.port+10): try: self.server = self.ThreadingTCPServer(("",self.port),self.ClientHandler) break except socket.error,msg: warn("server port %s: %s" % (self.port,msg)) self.address = local_ip_address() info("server version %s, listening on %s." % (__version__,self.ip_address)) from threading import Thread self.thread = Thread(target=self.run) self.thread.start() # Stop with: "self.server.shutdown()" def run(self): try: self.server.serve_forever() except Exception,msg: info("server: %s" % msg) info("server shutting down") def stop(self): if self.server is not None: self.server.shutdown() self.server = None # By default, the "ThreadingTCPServer" class binds to the sever port # without the option SO_REUSEADDR. The consequence of this is that # when the server terminates you have to let 60 seconds pass, for the # socket to leave to "CLOSED_WAIT" state before it can be restarted, # otherwise the next bind call would generate the error # 'Address already in use'. # Setting allow_reuse_address to True makes "ThreadingTCPServer" use to # SO_REUSEADDR option when calling "bind". import SocketServer class ThreadingTCPServer(SocketServer.ThreadingTCPServer): allow_reuse_address = True class ClientHandler(SocketServer.BaseRequestHandler): def handle(self): """Called when a client connects. 'self.request' is the client socket""" info("accepted connection from "+self.client_address[0]) input_queue = "" while 1: # Commands from a client are not necessarily received as one packet # but each command is terminated by a newline character. # If 'recv' returns an empty string it means client closed the # connection. while input_queue.find("\n") == -1: try: received = self.request.recv(2*1024*1024) except Exception,x: error("%r %r" % (x,str(x))) received = "" if received == "": info("client disconnected"); break ##debug("received %8d+%8d = %8d bytes" % (len(input_queue), ## len(received),len(input_queue)+len(received))) input_queue += received if input_queue == "": break if input_queue.find("\n") != -1: end = input_queue.index("\n") query = input_queue[0:end] input_queue = input_queue[end+1:] else: query = input_queue; input_queue = "" query = query.strip("\r ") from numpy import array,nan if query.find("=") >= 0: debug("executing command: '%s'" % query) try: with Server.lock: exec(query) except Exception,x: error("%r %r" % (x,str(x))) else: debug("evaluating query: '%s'" % query) try: with Server.lock: reply = eval(query) except Exception,x: error("%r %r" % (x,str(x))); reply = str(x) if reply is None: reply = "" elif type(reply) == str and len(reply) > 1024: pass # do not waste time reformatting a string elif reply is not None: try: reply = repr(reply) except: reply = str(reply) reply = reply.replace("\n","") # "\n" = end of reply reply += "\n" debug("sending reply: "+repr(reply)) self.request.sendall(reply) info("closing connection to "+self.client_address[0]) self.request.close()
def __init__(self, application, parentWindow): self.app = application self.parentWindow = parentWindow QtCore.QObject.__init__(self) # Get the home directory, and set a default save-state file home = os.getenv("HOME") self.saveFileName = home + '/.CRI.xml' # Initialize a tf listener self.tf = tf.TransformListener() # Initialize default pick scripts self.typeToName = { 1: 'Grid', 2: 'Frame', 3: 'Reticle', 4: 'Reticle', 5: 'Marker', 10: 'Point Cloud', 11: 'Path', 12: 'Grid Cells', 13: 'Texture Quad', 14: 'Laser Scan', 15: 'Quiver', 16: 'Odometry', 17: 'Pose Stamped', 18: 'Pose Array' } self.pickTypeToScriptDict = dict() rootPath = roslib.packages.get_pkg_dir('cri') # frameOptions = {'Attach' : 'AttachToFrame.py', # 'Orbit' : 'OrbitFrame.py'} # self.pickTypeToScriptDict[2] = frameOptions gridOptions = { 'Orbit': rootPath + '/src/python/DefaultPickScripts/OrbitGridPoint.py', 'Place Gimbal': rootPath + '/src/python/DefaultPickScripts/SelectDirection.py' } self.pickTypeToScriptDict[1] = gridOptions # markerOptions = {'beer' : 'beer.py'} # self.pickTypeToScriptDict[5] = markerOptions self.dialogMainMenu = None self.dialogAddTopic = None self.dialogTFFrames = None self.dialogListGadgets = None self.dialogListSelections = None self.dialogGeneralSettings = None self.dialogPCSettings = None self.dialogQuiverSettings = None self.dialogReticleSettings = None self.dialogKeyAssign = None self.dialogPickAssign = None self.dialogSettingsMenu = None self.dialogStatus = None self.maxStatusMessages = 1000 # Allocate mutex for status messages self.statusMutex = thread.allocate_lock() self.statusMessages = [] self.msgNo = 0
# serial debug console. It implements the subject_base class. The serial port # parameters come from the values PORT_8388V and RATE_8388V in the conf object # passed to the constructor. import sys import serial import time import re import config from zc_base import subject_base, zc_test_exception import thread #extract SSID from scan result line re_ssid = re.compile( r'\s+\d+\.\s+BSSID\s+\w+\:\w+\:\w+\:\w+\:\w+\:\w+\s+RSSI\s+\d+\s+SSID\s+(\S+)\t' ) mutex = thread.allocate_lock() class subject_8388V(subject_base): def __init__( self, conf ): self.conf = conf port = conf.PORT_8388V rate = conf.RATE_8388V try: self.ser = serial.Serial( port, rate,\ xonxoff=0,\ rtscts=0,\ bytesize=serial.EIGHTBITS,\ parity=serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ timeout=1 ) # clear the buffer
def __init__(self, watermark, parentframe): self.watermark = watermark self.parent2 = parentframe * 2.0 self.lock = thread.allocate_lock()
def __init__(self, parent, id, title, paths): """ Setup Application Window @author: Derek Buranen @author: Aaron Gerber @author: Markus Roth """ self.ToggleValue = 0 self.paths = paths self.thread = None self.threadLock = thread.allocate_lock() # Disable until 0.7 release self.enablePMP = False if re.match('(?:open|free|net)bsd|linux',sys.platform): width = 165 height = 350 xval1 = 155 xval2 = 250 else: height = 350 width = 175 xval1 = 180 xval2 = 265 wx.Frame.__init__(self, parent, wx.ID_ANY, title, size=(height,width), style=wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.RESIZE_BOX | wx.MAXIMIZE_BOX)) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) if sys.platform == 'win32': icon = wx.Icon(os.path.join(self.paths['main'], 'icon.ico'), wx.BITMAP_TYPE_ICO) self.SetBackgroundColour(wx.Colour(236,233,216)) else: icon = wx.Icon(os.path.join(self.paths['main'], 'icon.ico'), wx.BITMAP_TYPE_ICO) self.SetIcon(icon) #Buttons self.connectButton = wx.Button(self, 10, "Start", wx.Point(xval1, 81)) self.connectButton.SetDefault() wx.EVT_BUTTON(self, 10, self.ConnectSupport) self.stopButton = wx.Button(self, wx.ID_STOP, "", wx.Point(xval2, 81)) self.stopButton.Enable(False) wx.EVT_BUTTON(self, wx.ID_STOP, self.KillPID) # Radio Boxes self.rb1 = wx.RadioButton(self, -1, 'Get Help', (10, 15), style=wx.RB_GROUP) self.rb2 = wx.RadioButton(self, -1, 'Give Support', (10, 48)) self.rb1.SetValue(True) self.Bind(wx.EVT_RADIOBUTTON, self.RadioToggle, id=self.rb1.GetId()) self.Bind(wx.EVT_RADIOBUTTON, self.RadioToggle, id=self.rb2.GetId()) # checkbox for natpmp if sys.platform == 'darwin' or re.match('(?:open|free|net)bsd|linux',sys.platform): if self.enablePMP: self.cb1 = wx.CheckBox(self, -1, 'Use NAT-PMP', (130, 48)) self.cb1.Enable(False) # Checkbox for low color self.cb2 = wx.CheckBox(self, -1, 'Use low colors', (10, 81)) self.cb2.Set3StateValue(False) self.cb2.SetValue(self.paths['low-colors']) # Use value of --low-colors from command line self.cb2.Enable(False) # the combobox Control self.sampleList = self.paths['list'] self.sampleList = self.getHosts(self.sampleList, os.path.join(self.paths['main'], 'hosts.txt')) self.sampleList = self.getHosts(self.sampleList, self.paths['preferences']) self.displayHostBox(self.sampleList, "Enter/Select Support Address") # Menu menuBar = wx.MenuBar() fileMenu = wx.Menu() editMenu = wx.Menu() editMenu.Append(11, "&Cut\tCtrl+X", "Cut IP Address") editMenu.Append(12, "&Copy\tCtrl+C", "Copy IP Address") editMenu.Append(wx.ID_PASTE, "&Paste\tCtrl+V", "Paste IP Address") wx.EVT_MENU(self, 11, self.SetClipboard) wx.EVT_MENU(self, 12, self.SetClipboard) wx.EVT_MENU(self, wx.ID_PASTE, self.GetClipboard) fileMenu.Append(13, "&Clear History", "Clear History") if sys.platform == 'darwin': fileMenu.Append(wx.ID_ABOUT, "&About", "About Gitso") wx.EVT_MENU(self, wx.ID_ABOUT, self.ShowAbout) else: fileMenu.Append(wx.ID_EXIT, "&Quit\tCtrl+Q", "Quit Gitso") wx.EVT_MENU(self, wx.ID_EXIT, self.OnCloseWindow) helpMenu = wx.Menu() helpMenu.Append(wx.ID_ABOUT, "&About", "About Gitso") wx.EVT_MENU(self, wx.ID_ABOUT, self.ShowAbout) wx.EVT_MENU(self, 13, self.clearHistory) menuBar.Append(fileMenu, "&File") menuBar.Append(editMenu, "&Edit") if re.match('(?:open|free|net)bsd|linux',sys.platform) or sys.platform == 'win32': menuBar.Append(helpMenu, "&Help") self.SetMenuBar(menuBar) self.statusBar = self.CreateStatusBar() self.statusBar.SetStatusWidths([350]) self.setMessage("Idle", False) self.SetDefaultItem(self.hostField) self.hostField.SetFocus() self.SetThemeEnabled(True) self.Centre() self.Show(True) if self.paths['listen']: self.rb2.Value = True self.RadioToggle(None) self.ConnectSupport(None) elif self.paths['connect'] <> "": self.rb1.Value = True self.RadioToggle(None) self.hostField.Value = self.paths['connect'] self.ConnectSupport(None)
def __init__(self, pObjects=None, topic=""): self.pObjects = pObjects # initally array of strings and later crossreferenced to form an array of Pep P object self.topic = topic self.currentValue = None # should only be handled using setValue() (or read indirectly using pObjects[i].value) self.lock = thread.allocate_lock() # construct lock (mutex)
# Install myself on top of pygame.event def install(): """Installs this module (eventwrap) as an in-place replacement for the pygame.event module. Use install() when you need to interact with unaware Pygame code, forcing it to use this module's event queue.""" import eventwrap, pygame pygame.event = eventwrap import sys sys.modules["pygame.event"] = eventwrap # Event queue: g_events = Queue.Queue() # Set of blocked events as set by set g_blocked = set() g_blockedlock = thread.allocate_lock() g_blockAll = False def pump(): """Handle any window manager and other external events that aren't passed to the user. Call this periodically (once a frame) if you don't call get(), poll() or wait().""" pygame_pump() def get(): """Get a list of all pending events. (Unlike pygame, there's no option to filter by event type; you should use set_blocked() if you don't want to see certain events.)""" pump() eventlist = [] try: while True: eventlist.append(g_events.get(block=False))
from . import api, model from .commontypes import COMMON_TYPES, resolve_common_type try: from . import _pycparser as pycparser except ImportError: import pycparser import weakref, re, sys try: if sys.version_info < (3, ): import thread as _thread else: import _thread lock = _thread.allocate_lock() except ImportError: lock = None _r_comment = re.compile(r"/\*.*?\*/|//.*?$", re.DOTALL | re.MULTILINE) _r_define = re.compile(r"^\s*#\s*define\s+([A-Za-z_][A-Za-z_0-9]*)\s+(.*?)$", re.MULTILINE) _r_partial_enum = re.compile(r"=\s*\.\.\.\s*[,}]|\.\.\.\s*\}") _r_enum_dotdotdot = re.compile(r"__dotdotdot\d+__$") _r_partial_array = re.compile(r"\[\s*\.\.\.\s*\]") _r_words = re.compile(r"\w+|\S") _parser_cache = None def _get_parser(): global _parser_cache if _parser_cache is None: _parser_cache = pycparser.CParser()
from jsb.utils.locking import lockdec from jsb.utils.generic import tolatin1 from jsb.utils.exception import handle_exception from jsb.lib.datadir import getdatadir ## basic imports import thread import os import time import types import logging ## locks dblock = thread.allocate_lock() dblocked = lockdec(dblock) ## Db class class Db(object): """ this class implements a database connection. it connects to the database on initialisation. """ def __init__(self, dbname=None, dbhost=None, dbuser=None, dbpasswd=None, dbtype=None,
def __init__(self): """ Initializes the engine.""" # this is the event queue that holds all the events in # the system. self._event_queue = Queue.Queue() # this is a lock for writing stuff to the ui--makes sure # we're not hosing things by having multiple things write # to the ui simultaneously.... ick. self._ui_lock = thread.allocate_lock() # this is the master shutdown flag for the event queue # handling. self._shutdownflag = 0 # Lyntin counts the total number of errors it's encountered. # This enables us to shut ourselves down if we encounter too # many which indicates a "bigger problem". self._errorcount = 0 # listeners exist at an engine level. if you sign up for # an input hook, you get the input hook for ALL sessions. # this might change at some point.... we'll see. self._listeners = {} self._managers = {} # the help manager manages all the help content in a hierarchical # structure. self._managers["help"] = helpmanager.HelpManager(self) # our config manager self._managers["config"] = config.ConfigManager(self) # our history manager self._managers["history"] = history.HistoryManager(self) # our command manager self._managers["command"] = commandmanager.CommandManager(self) # there is only one ui in the system. self._ui = None # current tick count self._current_tick = 0 # list of registered threads self._threads = [] # counts the total number of events processed--for diagnostics self._num_events_processed = 0 # holds all the sessions self._sessions = {} # the current session. points to a Session object. self._current_session = None # map of hook name -> utils.PriorityQueue objects self._hooks = {} # we register ourselves with the shutdown hook self.hookRegister("shutdown_hook", self.shutdown) commonsession = session.Session(self) commonsession.setName("common") # this creates a "common" entry in all the managers that manage # session scoped data--the session base is None # for mem in self._managers.values(): # mem.addSession(commonsession, None) self._sessions["common"] = commonsession self._current_session = commonsession self.hookRegister("user_filter_hook", self._managers["command"].filter, 100)
def initAll(self): self.audioSourceLabelControl = self.getControl(AUDIO_SOURCE_LABLE_CONTROL) self.audioSpeakerConfigLabelControl = self.getControl(AUDIO_SPEAKER_CONFIG_LABLE_CONTROL) self.audioHelper = AudioHelper() self.audioSourceLabelControl.setLabel(self.audioHelper.getSelectedOutput()) self.audioSourceSelectedIndex = self.audioHelper.getSelectedIndex() self.updateSpeakerConfig(self.audioSourceSelectedIndex) self.audioVolumeLabelControl = self.getControl(AUDIO_VOLUME_LABLE_CONTROL) self.audioVolumeSliderControl = self.getControl(AUDIO_VOLUME_SLIDER_CONTROL) self.audioVolumeMinusButtonControl = self.getControl(AUDIO_VOLUME_MINUS_BUTTON_CONTROL) self.audioVolumePlusButtonControl = self.getControl(AUDIO_VOLUME_PLUS_BUTTON_CONTROL) self.audioVolumeMuteRadioControl = self.getControl(AUDIO_VOLUME_MUTE_RADIO_CONTROL) volume = self.audioHelper.getVolume() self.audioVolumeSliderControl.setPercent(volume) self.audioVolumeLabelControl.setLabel("{0}%".format(volume)) self.setVolumeControlButtons(volume, False) self.wifilist = self.getControl(WIFI_LIST_CONTROL) self.wifiNetworkLabelControl = self.getControl(WIFI_NETWORK_LABEL_CONTROL) self.wifihelper = WiFiHelper(self.wifilist, __language__) self.wifihelper.FillList() self.spinControls = [] self.alienFXControls = AlienFXLights(self) alienFxBrightness = [] for x in range(0,101): alienFxBrightness.append('{0}%'.format(x)) self.alienFxHeadSpinControl = SpinControl(self,ALIENFX_HEAD_GROUP_CONTROL,ALIENFX_HEAD_LABEL_CONTROL,self.alienFxHeadColorChanged, self.alienFxHeadUpCallback, self.alienFxHeadDownCallback, self.alienFXControls.colors,ALIENFX_HEAD_SPIN_LEFT, ALIENFX_HEAD_SPIN_RIGHT, ALIENFX_HEAD_LEFT_FOCUS, ALIENFX_HEAD_RIGHT_FOCUS) self.alienFxHeadSpinControl.selectText(self.alienFXControls.zone1SelectedColor) self.alienFxCornerSpinControl = SpinControl(self,ALIENFX_CORNER_GROUP_CONTROL,ALIENFX_CORNER_LABEL_CONTROL,self.alienFxCornerColorChanged, self.alienFxCornerUpCallback, self.alienFxCornerDownCallback, self.alienFXControls.colors,ALIENFX_CORNER_SPIN_LEFT, ALIENFX_CORNER_SPIN_RIGHT, ALIENFX_CORNER_LEFT_FOCUS, ALIENFX_CORNER_RIGHT_FOCUS) self.alienFxCornerSpinControl.selectText(self.alienFXControls.zone2SelectedColor) self.alienFxBrightnessImageControl = self.getControl(ALIENFX_BRIGHTNESS_IMAGE_CONTROL) self.alienFxBrightnessSpinControl = SpinControl(self,ALIENFX_BRIGHTNESS_GROUP_CONTROL,ALIENFX_BRIGHTNESS_LABEL_CONTROL,self.alienFxBrightnessChanged, self.alienFxBrightnessUpCallback, self.alienFxBrightnessDownCallback, alienFxBrightness,ALIENFX_BRIGHTNESS_SPIN_LEFT, ALIENFX_BRIGHTNESS_SPIN_RIGHT, ALIENFX_BRIGHTNESS_LEFT_FOCUS,ALIENFX_BRIGHTNESS_RIGHT_FOCUS) self.alienFxBrightnessSpinControl.selectText('{0}%'.format(self.alienFXControls.brightnessSpinIndex)) self.setAlienFxBrightnessImage(self.alienFXControls.brightnessSpinIndex) self.spinControls.append(self.alienFxHeadSpinControl) self.spinControls.append(self.alienFxCornerSpinControl) self.spinControls.append(self.alienFxBrightnessSpinControl) self.bluetoothOnRadioButton = self.getControl(BLUETOOTH_ON_RADIO_BUTTON_CONTROL) self.bluetoothDiscoverabilityRadioButton = self.getControl(BLUETOOTH_DISCOVERABILITY_ON_RADIO_BUTTON_CONTROL) self.bluetoothDevicesListControl = self.getControl(BLUETOOTH_DEVICES_LIST_CONTROL) self.bluetoothHelper = BluetoothHelper(self.bluetoothDevicesListControl,__addon__,__language__) self.bluetoothOnRadioButton.setSelected(self.bluetoothHelper.isBluetoothOn()) self.updateWindowLabelControl = self.getControl(UPDATE_WINDOWS_LABEL_CONTROL) self.updateNvidiaLabelControl = self.getControl(UPDATE_NVIDIA_LABEL_CONTROL) self.updateAlienwareLabelControl = self.getControl(UPDATE_ALIENWARE_LABEL_CONTROL) self.updateWindowSetting = AlphaUIUtils.GetWindowsUpdateSetting() if (self.updateWindowSetting == 1): self.updateWindowSetting = 0 self.updateWindowLabelControl.setLabel(__language__(33070 + self.updateWindowSetting)) json_response = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.GetSettingValue", "params": {"setting": "general.addonupdates"}, "id": 1 }')) self.updateAlienwareSetting = json_response['result']['value'] self.updateAlienwareLabelControl.setLabel(__language__(33070 + self.updateAlienwareSetting)) self.updateNvidiaLabelControl.setLabel(__language__(33070 + 2)) self.refreshMute() self.lock = thread.allocate_lock() self.IsInitDone = True
if sys.platform == 'cli': import clr # save start_new_thread so we can call it later, we'll intercept others calls to it. DETACHED = False def thread_creator(func, args, kwargs={}): id = _start_new_thread(new_thread_wrapper, (func, ) + args, kwargs) return id _start_new_thread = thread.start_new_thread exit_lock = thread.allocate_lock() exit_lock.acquire() THREADS = {} THREADS_LOCK = thread.allocate_lock() try: l = (lambda: 42) weakref.ref(getattr(l, 'func_code', None) or getattr(l, '__code__', None)) # this Python implementation supports weak refs to code objects (new in 2.7) MODULES = weakref.WeakKeyDictionary() except TypeError: MODULES = {} # Py3k compat - alias unicode to str try: unicode
Objects for packages that have been uninstalled. """ from cgi import escape from logging import getLogger from thread import allocate_lock from Acquisition import Acquired from Acquisition import Explicit from App.special_dtml import DTMLFile from OFS.SimpleItem import Item from Persistence import Overridable from ZODB.broken import Broken as ZODB_Broken from ZODB.broken import persistentBroken broken_klasses = {} broken_klasses_lock = allocate_lock() LOG = getLogger('OFS.Uninstalled') class BrokenClass(ZODB_Broken, Explicit, Item, Overridable): _p_changed = 0 meta_type = 'Broken Because Product is Gone' icon = 'p_/broken' product_name = 'unknown' id = 'broken' manage_page_header = Acquired manage_page_footer = Acquired def __getattr__(self, name): if name[:3] == '_p_':
def init_webservice_locker(): try: global g_webservice_url_locker g_webservice_url_locker = thread.allocate_lock() except Exception as e: print_log("init webservice url locker failed, error {}".format(e))
def __init__(self): self._lock = thread.allocate_lock() self._counter = 0
def gettype(self): return self.type def getmaintype(self): return self.maintype def getsubtype(self): return self.subtype try: import thread except ImportError: import dummy_thread as thread _counter_lock = thread.allocate_lock() del thread _counter = 0 def _get_next_counter(): global _counter _counter_lock.acquire() _counter += 1 result = _counter _counter_lock.release() return result _prefix = None
Note: obviously this is *not* thread safe, it's just informative... """ try: for element in self.queue: if filterFunction(element): return element return None except RuntimeError, err: return None # none yet, at least g_events = _FilterQueue() # Set of blocked events as set by set g_blocked = set() g_blockedlock = thread.allocate_lock() # should use threading instead g_blockAll = False def _typeChecker(types): """Create check whether an event is in types""" try: if 1 in types: pass def check(element): return element.type in types return check except TypeError, err:
def _access_default(self): return allocate_lock()
def __init__(self): self.q = Queue.Queue() self.lock = thread.allocate_lock()
def __init__(self, user_msg, sync): self._user_msg = user_msg self._sync_msg = sync self.reply_lock = thread.allocate_lock() self.reply_lock.acquire()
def __init__(self, args): self.args = args self.config = getConfig() self.suites = {} # Use the existing logger instance self.log = self.config.log self.log.setLevel(args.loglevel) if args.timeout == '0': self.timeout = int(self.config.timeout); else: self.timeout = int(args.timeout) logging.debug("Suite timeout: %d sec / testcase", self.timeout) if not args.suiteDir: self.suiteDir = self.config.suiteDir if not self.suiteDir: raise Error("2002") else: self.suiteDir = args.suiteDir if args.keyDir == self.config.keyDir: self.keyDir = self.config.keyDir if not self.keyDir: raise Error("2003") else: self.keyDir = args.keyDir logging.debug("Try to use alternative key directory: %s", self.keyDir) self.suiteDir = ExpandCheck.dirExists(self.suiteDir, True) self.regressionDir = ExpandCheck.dirExists(self.config.regressionDir, True) self.logDir = ExpandCheck.dirExists(self.config.logDir, True) self.dir_ec = ExpandCheck.dirExists(os.path.join(self.suiteDir, self.config.eclDir), True) self.dir_ex = ExpandCheck.dirExists(os.path.join(self.suiteDir, self.keyDir), True) self.dir_a = os.path.join(self.regressionDir, self.config.archiveDir) self.dir_r = os.path.join(self.regressionDir, self.config.resultDir) self.dir_zap = os.path.join(self.regressionDir,self.config.zapDir) self.dir_inc = self.dir_ec logging.debug("Suite Dir : %s", self.suiteDir) logging.debug("Regression Dir : %s", self.regressionDir) logging.debug("Result Dir : %s", self.dir_r) logging.debug("Log Dir : %s", self.logDir) logging.debug("ECL Dir : %s", self.dir_ec) logging.debug("Key Dir : %s", self.dir_ex) logging.debug("Archive Dir : %s", self.dir_a) logging.debug("ZAP Dir : %s", self.dir_zap ) logging.debug("INC Dir : %s", self.dir_inc ) numOfThreads=1 if 'pq' in args: if args.pq == 0: numOfThreads = 1; else: numOfThreads = args.pq self.loggermutex = thread.allocate_lock() self.numOfCpus = 2 self.threadPerCpu = 2 ver = getVersionNumbers() if numOfThreads == -1: if (ver['main'] >= 2) and (ver['minor'] >= 7): if 'linux' in sys.platform : command = "grep 'core\|processor' /proc/cpuinfo | awk '{print $3}' | sort -nru | head -1" cpuInfo = os.popen(command).read() if cpuInfo == "": self.numOfCpus = 1 else: self.numOfCpus = int(cpuInfo)+1 numOfThreads = self.numOfCpus * self.threadPerCpu elif (ver['main'] <= 2) and (ver['minor'] < 7): numOfThreads = self.numOfCpus * self.threadPerCpu logging.debug("Number of CPUs:%d, NUmber of threads:%d", self.numOfCpus, numOfThreads ) self.maxthreads = numOfThreads self.maxtasks = 0 self.exitmutexes = [thread.allocate_lock() for i in range(self.maxthreads)] self.timeouts = [(-1) for i in range(self.maxthreads)] self.timeoutHandlerEnabled = False; self.timeoutThread = threading.Timer(1.0, self.timeoutHandler)
import sys import time import rospy import random import socket import thread from iiwa_driver.srv import * # ----------------------------------------------------------------------------- # Default parameters, they will be overwritten by the config.yaml file # ----------------------------------------------------------------------------- TCP_IP = "172.31.1.147" TCP_PORT = 30000 SERVICE_NAME = 'iiwa_telnet' # ----------------------------------------------------------------------------- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) lock = thread.allocate_lock( ) # Lock for tcp communication. Only one command can be sent at the same time # ----------------------------------------------------------------------------- # Connect with the robot. It will try to reconnect in case of error # ----------------------------------------------------------------------------- def connect(): while not rospy.is_shutdown(): try: rospy.logwarn('Connecting to ' + TCP_IP + ":" + str(TCP_PORT)) sock.connect((TCP_IP, TCP_PORT)) rospy.logwarn('Connected to ' + TCP_IP + ":" + str(TCP_PORT)) break except: time.sleep(1)
def __init__(self): self.mutex = _thread.allocate_lock() self.dict = {}