def __init__(self, name, opts, macros=None): self.opts = opts if macros is None: self.macros = opts.defaults else: self.macros = macros self.init_name = name log.trace('config: %s' % (name)) self.disable_macro_reassign = False self.configpath = [] self.wss = re.compile(r'\s+') self.tags = re.compile(r':+') self.sf = re.compile(r'%\([^\)]+\)') for arg in self.opts.args: if arg.startswith('--with-') or arg.startswith('--without-'): if '=' in arg: label, value = arg.split('=', 1) else: label = arg value = None label = label[2:].lower().replace('-', '_') if value: self.macros.define(label, value) else: self.macros.define(label) self._includes = [] self.load_depth = 0 self.pkgconfig_prefix = None self.pkgconfig_crosscompile = False self.pkgconfig_filter_flags = False self.load(name)
def sortAndViewAs(self, sort=True, first=True): ''' sort and view contact name @type sort: boolean @param sort: whether sort contact name or view contact @type first: boolean @param first: whether sort and view contact by first name or last name @return: boolean ''' trace("start sorting...") sleep(1) self.goList() self.menu() self.scroll(times=4) sleep(2) sortOrView="Sort list by" if sort else "View contact names as" firstOrLast="First name*" if first else "Last name*" try: self.getView(sortOrView).touch() sleep(1) self.getView(firstOrLast,regex=True).touch() return True except AttributeError: return False finally: self.goList()
def delete(self, kwd=''): '''delete one contact @type kwd: string @param kwd: keyword which contact to be delete, if none,delete first contact @return: True if operate sucess, False if operate fail. ''' if self.isEmpty(): trace('Could not find any contact data,no record!') return False find = self.search(kwd) if kwd else self.getView( 'id/no_id/27', iD=True, dump=False) try: # delete operate find.touch() sleep(4) trace('show contact detail information') self.menu() sleep(3) self.scroll(times=3) trace('choose delete contact') except AttributeError: trace('Could not find the contact : ' + kwd) return False try: # confirm delete operate ok_menu = self.getView('OK') ok_menu.touch() sleep(3) except AttributeError: trace('OK button not found') return False self.goList() return True
def _check_exe(_opts, macro, value, constraint, silent = False): if len(value) == 0 or constraint == 'none': return True orig_value = value if path.isabspath(value): if path.isfile(value): return True if os.name == 'nt': if path.isfile('%s.exe' % (value)): return True value = path.basename(value) absexe = True else: absexe = False paths = os.environ['PATH'].split(os.pathsep) if _check_paths(value, paths): if absexe: if not silent: log.notice('warning: exe: absolute exe found in path: (%s) %s' % (macro, orig_value)) return True if constraint == 'optional': if not silent: log.trace('warning: exe: optional exe not found: (%s) %s' % (macro, orig_value)) return True if not silent: log.notice('error: exe: not found: (%s) %s' % (macro, orig_value)) return False
def __init__(self, name, opts, macros = None): self.opts = opts if macros is None: self.macros = opts.defaults else: self.macros = macros self.init_name = name log.trace('config: %s' % (name)) self.disable_macro_reassign = False self.configpath = [] self.wss = re.compile(r'\s+') self.tags = re.compile(r':+') self.sf = re.compile(r'%\([^\)]+\)') for arg in self.opts.args: if arg.startswith('--with-') or arg.startswith('--without-'): if '=' in arg: label, value = arg.split('=', 1) else: label = arg value = None label = label[2:].lower().replace('-', '_') if value: self.macros.define(label, value) else: self.macros.define(label) self._includes = [] self.load_depth = 0 self.pkgconfig_prefix = None self.pkgconfig_crosscompile = False self.pkgconfig_filter_flags = False self.load(name)
def _select(self, config, ls): if len(ls) != 2: log.warning('invalid select statement') else: r = self.macros.set_read_map(ls[1]) log.trace('config: %s: _select: %s %s %r' % \ (self.name, r, ls[1], self.macros.maps()))
def _cp_dir(self, source_path, destination_path): log.trace('entry', [source_path, destination_path]) ## does the directory exist if not os.path.isdir(source_path): log.error('Cannot find source dir %s' % source_path) raise error, 'cp_dir() cannot find source directory="%s"' ( source_path) self.mkdir(destination_path) src = [[]] for relparts in src: dir = apply(os.path.join, [source_path] + relparts) dest_dir = apply(os.path.join, [destination_path] + relparts) for file in os.listdir(dir): full_file = os.path.join(dir, file) full_dest = os.path.join(dest_dir, file) if os.path.isdir(full_file) and not os.path.islink(full_file): src.append(relparts + [file]) # This makes it recursive self.mkdir(full_dest) else: self._cp_single(full_file, full_dest) log.trace('exit')
def Checkout(self, tag, module_list, az = None, timestamp = None, nonrecursive = 0, dir = None): """Given a CVS tag and a list of CVS modules, check them out.""" log.trace( 'entry' , [ tag , module_list , az , timestamp , nonrecursive , dir ] ) #print "cvs.Checkout(%s,%s,az=%s,timestamp=%s, %s, %s)" % ( # repr(tag),repr(module_list), # repr(az),repr(timestamp), repr(nonrecursive), repr(dir)) module_list = listify(module_list) if az: if len(module_list) > 1: print "Cannot checkout two modules as the same name" sys.exit(1) update_list,checkout_list = self.update_checkout_list(tag, module_list, az, dir) #print "UPDATE_LIST=%s" % repr(update_list) #print "CHECKOUT_LIST=%s" % repr(checkout_list) if update_list: self.update(tag, update_list, az, timestamp, nonrecursive, dir) if checkout_list: self.checkout(tag, checkout_list, az, timestamp, nonrecursive, dir) log.trace( 'exit' )
def Checkout(tag, module_list, repository_name = "", az = None, timestamp = None, nonrecursive = 0, zap = None): log.trace( 'entry' , [ module_list , repository_name , az , timestamp , nonrecursive , zap ] ) module_list = listify(module_list) if cvs_checkout_hook: module_list = cvs_checkout_hook(tag, module_list, repository_name, az, timestamp, nonrecursive) if not module_list: return if zap: for mod in module_list: if az: mod = az if os.path.exists(mod): import thread print "DELETING: %s [%d] START" % (mod, thread.get_ident()) shell.rm(mod) print "DELETING: %s [%d] END" % (mod, thread.get_ident()) log.trace( 'exit' ) return Get(repository_name).Checkout(tag, module_list, az, timestamp, nonrecursive)
def readData(self): """readData() Reads the data from the data source. Preconditions: this process has a lock on the basefile """ log.trace('entry') self.__threadLock.acquire() try: self.__checkLock() if os.path.exists(self.__filename): rawData = utils.readFile(self.__filename) log.debug('Got %s lines of raw data.' % len(rawData)) self.__parseData(rawData) log.debug('Parsed into %s lines of usable data.' % len(self.__data)) self.__dataCached = 1 finally: self.__threadLock.release() log.trace('exit')
def recordDLL(self, dll, base, size): """recordDLL(d,b,s) Records dll d with base b and size s in the basefile. If data for d is already present, the new data will replace the old data (only one record can exist per dll). Preconditions: this process has a lock on the basefile data has been read in """ # Actually, writes the entire file after removing the original entry # for the DLL, if any. log.trace('entry', [dll, base, size]) self.__threadLock.acquire() try: self.__checkLock() self.__checkDataCached() if self.__isDLLRecorded(dll): log.debug('DLL %s previously recorded - removing.' % dll) self.__removeDLL(dll) log.debug('Adding record for %s' % dll) self.__addRecord([dll, "0x%x" % base, "0x%x" % size]) log.debug('Recording data to basefile.') self.__recordData() finally: self.__threadLock.release() log.trace('exit')
def getNextBaseAddress(self, dll): """getNextBaseAddress(d) --> integer Returns the next base address to use for dll d by processing the data in the basefile, or returns the default base if no basefile exists. This will ignore the existing values for d if it is already present (it thus assumes this is a rebase and the original values get replaced) Preconditions: this thread has a lock on the basefile data has been read in """ log.trace('entry', [dll]) self.__threadLock.acquire() try: self.__checkLock() self.__checkDataCached() result = self.__defaultBase if len(self.__data): highestDLL = self.__getHighestDLL(dll) if highestDLL: base = self.__getData(highestDLL, 'base') size = self.__getData(highestDLL, 'size') if (base + size) > result: result = base + size finally: self.__threadLock.release() log.trace('exit', ["0x%x" % result]) return result
def editPhone(self, phone, add=False): trace("edit contact's phone") self.check() if not add: trace('edit phone with no add') #find EditText of Phone view = self.getView('Phone') editId = 'id/no_id/' + str(int((view.getId())[-2:]) + 6) view = self.getView(editId, iD=True) #edit phone number self.device.drag(view.getXY(), view.getXY(), 3.0) self.device.press('KEYCODE_DEL', 'DOWN_AND_UP') view.type(phone) sleep(1) trace('edit phone with no add OK') else: trace('edit phone with add') #touch 'Add another field' view = self.getView('Add another field') view.touch() sleep(3) #touch 'Phone' and edit view = self.getView('Phone') view.touch() sleep(2) self.device.type(phone) sleep(1) trace('edit phone with add OK')
def editDetails(self, name='', phone='', email='', notes='', address='', nickname=''): ''' edit contact details ''' self.check() view = self.getView('id/no_id/27', iD=True) view.touch() sleep(4) trace('enter contact OK') self.device.press('KEYCODE_MENU', 'DOWN_AND_UP') view = self.getView('Edit') view.touch() sleep(3) trace('enter contact edit view OK') if not name == '': self.editName(name) if not phone == '': if self.getDetails('Phone'): self.editPhone(phone) else: self.editPhone(phone, add=True) self.back() sleep(3) self.back()
def viewAs(self, viewAsFirstNameFirst=True): ''' view contact name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search", True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start viewing...") self.device.press("KEYCODE_MENU", "DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView = self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("View contact names as").touch() trace("click View contact names as, dump, please wait...") self.vc.dump() if viewAsFirstNameFirst: self.vc.findViewWithTextOrRaise("First name first").touch() else: self.vc.findViewWithTextOrRaise("Last name first").touch() sleep(2)
def get_file(url, local, opts, config): if local is None: raise error.general("source/patch path invalid") if not path.isdir(path.dirname(local)) and not opts.download_disabled(): log.notice("Creating source directory: %s" % (os.path.relpath(path.host(path.dirname(local))))) log.output("making dir: %s" % (path.host(path.dirname(local)))) if not opts.dry_run(): path.mkdir(path.dirname(local)) if not path.exists(local) and opts.download_disabled(): raise error.general("source not found: %s" % (path.host(local))) # # Check if a URL has been provided on the command line. # url_bases = opts.urls() urls = [] if url_bases is not None: for base in url_bases: if base[-1:] != "/": base += "/" url_path = urlparse.urlsplit(url)[2] slash = url_path.rfind("/") if slash < 0: url_file = url_path else: url_file = url_path[slash + 1 :] urls.append(urlparse.urljoin(base, url_file)) urls += url.split() log.trace("_url: %s -> %s" % (",".join(urls), local)) for url in urls: for dl in downloaders: if url.startswith(dl): if downloaders[dl](url, local, config, opts): return if not opts.dry_run(): raise error.general("downloading %s: all paths have failed, giving up" % (url))
def parse(self, bset): def _clean(line): line = line[0:-1] b = line.find('#') if b >= 0: line = line[1:b] return line.strip() bsetname = bset if not path.exists(bsetname): for cp in self.macros.expand('%{_configdir}').split(':'): configdir = path.abspath(cp) bsetname = path.join(configdir, bset) if path.exists(bsetname): break bsetname = None if bsetname is None: raise error.general('no build set file found: %s' % (bset)) try: log.trace('_bset: %s: open: %s' % (self.bset, bsetname)) bset = open(path.host(bsetname), 'r') except IOError, err: raise error.general('error opening bset file: %s' % (bsetname))
def worker_thread(self, id): log.debug('%s started' % id) while True: try: job = self.jobs.get(block=True, timeout=0.1) self.jobs.task_done() except Queue.Empty: continue if job == None: log.trace('got signal to quit') break handle, user_func, args, user_callback, user_cb_args = job try: result = user_func(args) status = True except BaseException, e: status = False result = e log.trace('%s one job done' % id) self.results.put(handle, (status, result)) if user_callback: try: user_callback(handle, user_cb_args) except: pass
def ProcessOptions(line, func, options, case_insensetive=None): log.trace( 'entry' , [line, func, options, case_insensetive] ) if type(options) == types.StringType: o={} options=string.replace(options,":",":\n") options=string.replace(options,";",";\n") options=string.replace(options,"=","=\n") options=string.replace(options,".",".\n") for x in string.split(options,"\n"): if x: if case_insensetive: o[x[:-1]]=x[-1:] else: o[x[:-1]]=string.lower(x[-1:]) options=o opt = '' for arg in umake_lib.split_arguments(line): if opt: func(opt, arg) opt='' continue if arg[0] in ['/', '-']: opt=arg[1:] if case_insensetive: opt=string.lower(opt) arg='' odata=options.get(opt) if not odata: otmp = string.split(opt, ":", 1) if len(otmp) > 1 and options.get(otmp[0]) in [':',';']: opt = otmp[0] arg = otmp[1] odata = options.get(opt) if not odata and len(opt)>1: odata=options.get(opt[0:2]) if odata: arg=opt[2:] opt=opt[0:2] if not odata: odata=options.get(opt[0]) if odata: arg=opt[1:] opt=opt[0] if odata in [':','='] and not arg: continue func(opt, arg) opt='' else: func('', arg) log.trace( 'exit' )
def ProcessOptions(line, func, options, case_insensetive=None): log.trace('entry', [line, func, options, case_insensetive]) if type(options) == types.StringType: o = {} options = string.replace(options, ":", ":\n") options = string.replace(options, ";", ";\n") options = string.replace(options, "=", "=\n") options = string.replace(options, ".", ".\n") for x in string.split(options, "\n"): if x: if case_insensetive: o[x[:-1]] = x[-1:] else: o[x[:-1]] = string.lower(x[-1:]) options = o opt = '' for arg in umake_lib.split_arguments(line): if opt: func(opt, arg) opt = '' continue if arg[0] in ['/', '-']: opt = arg[1:] if case_insensetive: opt = string.lower(opt) arg = '' odata = options.get(opt) if not odata: otmp = string.split(opt, ":", 1) if len(otmp) > 1 and options.get(otmp[0]) in [':', ';']: opt = otmp[0] arg = otmp[1] odata = options.get(opt) if not odata and len(opt) > 1: odata = options.get(opt[0:2]) if odata: arg = opt[2:] opt = opt[0:2] if not odata: odata = options.get(opt[0]) if odata: arg = opt[1:] opt = opt[0] if odata in [':', '='] and not arg: continue func(opt, arg) opt = '' else: func('', arg) log.trace('exit')
def _ifs(self, config, ls, label, iftrue, isvalid, dir, info): in_iftrue = True data = [] while True: if isvalid and ((iftrue and in_iftrue) or (not iftrue and not in_iftrue)): this_isvalid = True else: this_isvalid = False r = self._parse(config, dir, info, roc=True, isvalid=this_isvalid) if r[0] == "package": if this_isvalid: dir, info, data = self._process_package(r, dir, info, data) elif r[0] == "control": if r[1] == "%end": self._error(label + " without %endif") raise error.general("terminating build") if r[1] == "%endif": log.trace("config: %s: _ifs: %s %s" % (self.name, r[1], this_isvalid)) return data if r[1] == "%else": in_iftrue = False elif r[0] == "directive": if this_isvalid: if r[1] == "%include": self.load(r[2][0]) continue dir, info, data = self._process_directive(r, dir, info, data) elif r[0] == "data": if this_isvalid: dir, info, data = self._process_data(r, dir, info, data)
def stop(self): ''' stop the contacts activity and set the startStatus False ''' self.device.shell('am force-stop %s' % package) trace('force stop contacts package %s' % package) self.startStatus = False
def learn(self, input_, cat, gcr=None): """ input_ of len 1-256 (limit to 256 to properly emulate a CM1K). cat 0-32767. 1-32767: vector category. 0: counterexample (shrink aifs, but don't commit RTL neuron). gcr 0-127. 1-127: context. 0: use all neurons (disregard context). None: don't overwrite current context. """ log.trace("CM1KEmulator.learn()") # log.log("Input: {},{}: {}".format(gcr, cat, input_)) # self.dump_registers() self.broadcast(input_, gcr) self.write_cat(cat) min_firing_dist = self.firing_neurons[-1].dist if self.firing_neurons else self.read_maxif() minif = self.read_minif() # Shrink any misfiring neurons to the shortest distance of any firing neuron for neuron in self.firing_neurons: neuron.shrink_if_necessary(cat, min_firing_dist, minif) # Determine if any neurons correctly fired any_correctly_firing_neuron = False for neuron in self.firing_neurons: if neuron.cat == cat: any_correctly_firing_neuron = True break log.log("any_correctly_firing_neuron: {}".format(any_correctly_firing_neuron)) # for neuron in self.neurons: # log.log("(A) Neuron: {}".format(neuron.dump())) # If there are no correctly firing neurons, consider recruiting a new neuron to hold the pattern as a new prototype if not any_correctly_firing_neuron: rtl_neuron_idx = None if not self.unlimited_neurons: # Find the RTL neuron # This should be stored in the registers, but it's safer to just find it explicitly for i, neuron in enumerate(self.neurons): # log.log("RTL search, neuron: {} {}".format(neuron.id_, neuron.state)) if neuron.state == nrn.NeuronState.rtl: rtl_neuron_idx = i break else: # If the number of neurons is unlimited, then the RTL neuron is simply at the end of the list rtl_neuron_idx = len(self.neurons) - 1 # Assign the RTL neuron the input as a new pattern if rtl_neuron_idx is not None: log.log("rtl_neuron: idx{}, id{}".format(rtl_neuron_idx, self.neurons[rtl_neuron_idx].id_ if self.neurons[rtl_neuron_idx] else None)) new_aif = min(max(min_firing_dist, minif), self.read_maxif()) log.log("new_aif: {}".format(new_aif)) self.neurons[rtl_neuron_idx].commit(self.read_gcr_context(), cat, new_aif, input_) log.log("Committed: id{} st{}".format(self.neurons[rtl_neuron_idx].id_, self.neurons[rtl_neuron_idx].state)) if self.unlimited_neurons: self.neurons.append(nrn.Neuron(len(self.neurons), self)) if self.neurons[rtl_neuron_idx].id_ < len(self.neurons) - 1: self.neurons[self.neurons[rtl_neuron_idx + 1].id_].state = nrn.NeuronState.rtl self.write_total_ncount_non_ui(self.read_ncount() + 1) else: log.log("RTL neuron is None")
def slide(self,str,view=None): ''' slide the screen @type: str @param: 'left','right','up','down' @type view: @param view: specify the view, default to None ''' if str not in ['left','right','up','down']: raise SyntaxError("wrong parameter: choose from 'left','right','up' or 'down'") try: cX,cY = view.getCenter() width = view.getWidth() height = view.getHeight() cL = cX - width/4, cY cR = cX + width/4, cY cU = cX, cY - height/4 cD = cX, cY + height/4 except AttributeError: pass (left, right, up, down) = (cL, cR, cU, cD) if view else (self.left, self.right, self.up, self.down) nav = { 'left':{'start':right,'end':left}, 'right':{'start':left,'end':right}, 'up':{'start':down,'end':up}, 'down':{'start':up,'end':down} } self.device.drag(nav[str]['start'], nav[str]['end'], 0.1, 10) trace('slide the screen from %s to %s ' % (nav[str]['start'],nav[str]['end'])) sleep(2)
def _ifs(self, config, ls, label, iftrue, isvalid, dir, info): in_iftrue = True data = [] while True: if isvalid and \ ((iftrue and in_iftrue) or (not iftrue and not in_iftrue)): this_isvalid = True else: this_isvalid = False r = self._parse(config, dir, info, roc = True, isvalid = this_isvalid) if r[0] == 'package': if this_isvalid: dir, info, data = self._process_package(r, dir, info, data) elif r[0] == 'control': if r[1] == '%end': self._error(label + ' without %endif') raise error.general('terminating build') if r[1] == '%endif': log.trace('config: %s: _ifs: %s %s' % (self.name, r[1], this_isvalid)) return data if r[1] == '%else': in_iftrue = False elif r[0] == 'directive': if this_isvalid: if r[1] == '%include': self.load(r[2][0]) continue dir, info, data = self._process_directive(r, dir, info, data) elif r[0] == 'data': if this_isvalid: dir, info, data = self._process_data(r, dir, info, data)
def addContact(self,name='',phone='',email='',address=''): self.goEdit() try: offset = 0 if name: view=self.getView('id/no_id/27',iD=True) trace('type %s' % name) view.type(name) view.touch() if phone: view=self.getView('id/no_id/46',iD=True,dump=False) trace('type %s' % phone) view.type(phone) offset += 4 sleep(2) if email: view=self.getView('id/no_id/' + str(57 + offset), iD=True) trace('type %s' % email) view.type(email) offset += 4 sleep(2) if address: view=self.getView('id/no_id/' + str(68 + offset), iD=True) trace('type %s' % address) view.type(address) sleep(2) view=self.getView('Done',dump=False) view.touch() trace('Touch Done') finally: sleep(5) self.goList()
def addContact(self, name='', phone='', email='', address=''): self.goEdit() try: offset = 0 if name: view = self.getView('id/no_id/27', iD=True) trace('type %s' % name) view.type(name) view.touch() if phone: view = self.getView('id/no_id/46', iD=True, dump=False) trace('type %s' % phone) view.type(phone) offset += 4 sleep(2) if email: view = self.getView('id/no_id/' + str(57 + offset), iD=True) trace('type %s' % email) view.type(email) offset += 4 sleep(2) if address: view = self.getView('id/no_id/' + str(68 + offset), iD=True) trace('type %s' % address) view.type(address) sleep(2) view = self.getView('Done', dump=False) view.touch() trace('Touch Done') finally: sleep(5) self.goList()
def updateDetails(self,fieldName,content): ''' update details of 'fieldName' with 'content' @type fieldName: str @param fieldName: name of field that will be eidt , e.g: Phone,Email,etc @type content: str @param content: edit content @return:True ''' trace('Edit field '+fieldName+' info') #find fieldName while not self.getView(fieldName): self.slide('up') sleep(2) #get editView of fieldName view = self.getView(fieldName,dump=False) view2=self.getView(view.getId()[:-2]+str(int(view.getId()[-2:])+6),iD=True) #wipe old content and update with new content self.wipe(view2) sleep(1) view2.type(content) sleep(1) return True
def unlock(self): """unlock() Releases the lock. """ log.trace('entry') self.__threadLock.acquire() try: # If we have the lock, but we are near being stale, then we are # going to leave the lockfile and let the next guy stale us out. # This way we avoid the problem where we had the lock, but # then our process slept and some other process staled us out, # replaced our lock, and then we awaken and remove their lock. if self.__hasLock(): if self.__isNearStale(): log.debug( "I'm near stale, so pretending I already staled out.") else: log.debug("Removing the lockfile %s." % self.__lockfile) os.remove(self.__lockfile) else: log.debug("Not my lock anymore - hopefully I staled out.") finally: self.__threadLock.release() log.trace('exit')
def find_distribution_cvs(self, locations): log.trace('entry', [locations]) for dir in locations: log.debug('Trying to find %s' % dir) if not self.cvs_dir_check(dir): log.debug('Failed cvs_dir_check on "%s" - skipping.' % dir) continue # Once we have a dir, let's do something with it. message = "Looking for %s in %s (don't worry if this fails)" % ( self.cvs_path, dir) log.debug(message) outmsg.verbose(message) try: cvs.Checkout(self.cvs_tag, dir, self.cvs_root, os.path.join(tmpdir(), dir), self.cvs_timestamp) except cvs.cvs_error: ## Ignore cvs errors, report them as missing distributions instead log.warn('Failed to check out %s - skipping' % dir) return dir = os.path.join(os.curdir, tmpdir(), dir) try: for f in os.listdir(dir): if string.lower(f) not in ["cvs"]: return dir except OSError: pass log.trace('exit') return None
def sortAs(self, sortByFirstName=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search", True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start sorting...") self.device.press("KEYCODE_MENU", "DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView = self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("Sort list by").touch() trace("click Sort list by, dump, please wait...") self.vc.dump() if sortByFirstName: self.vc.findViewWithTextOrRaise("First name").touch() else: self.vc.findViewWithTextOrRaise("Last name").touch() sleep(2)
def getLock( self ): """getLock() Gets an exclusive lock on the file. This call is blocking. In some cases, might exit execution without a lock (like on an IO exception). Caller should always test hasLock() to be sure the lock was actually received. """ log.trace( 'entry' ) count = 0 # How many times have we looped self.__threadLock.acquire() try: while not self.__hasLock(): if self.__lockfileExists(): if self.__isTimeToCheckForStaleLocks( count ): self.__checkForStaleLock() self.__threadLock.release() time.sleep( self.__sleepTime ) count += 1 self.__threadLock.acquire() else: self.__tryToGetLock() finally: self.__threadLock.release() log.trace( 'exit' )
def __init__(self, name, opts, macros=None, directives=None, ignores=None): self.opts = opts if macros is None: self.macros = opts.defaults else: self.macros = macros self.init_name = name self.directives = ['%include'] if directives: self.directives += directives self.ignores = ignores log.trace('config: %s' % (name)) self.disable_macro_reassign = False self.configpath = [] self.wss = re.compile(r'\s+') self.tags = re.compile(r':+') self.sf = re.compile(r'%\([^\)]+\)') for arg in self.opts.args: if arg.startswith('--with-') or arg.startswith('--without-'): label = arg[2:].lower().replace('-', '_') self.macros.define(label) self._includes = [] self.load_depth = 0 self.lc = 0 self.name = 'none'
def unlock( self ): """unlock() Releases the lock. """ log.trace( 'entry' ) self.__threadLock.acquire() try: # If we have the lock, but we are near being stale, then we are # going to leave the lockfile and let the next guy stale us out. # This way we avoid the problem where we had the lock, but # then our process slept and some other process staled us out, # replaced our lock, and then we awaken and remove their lock. if self.__hasLock(): if self.__isNearStale(): log.debug( "I'm near stale, so pretending I already staled out." ) else: log.debug( "Removing the lockfile %s." % self.__lockfile ) os.remove( self.__lockfile ) else: log.debug( "Not my lock anymore - hopefully I staled out." ) finally: self.__threadLock.release() log.trace( 'exit' )
def _process_data(self, results, directive, info, data): new_data = [] for l in results[1]: if l.startswith('%error'): l = self._expand(l) raise error.general('config error: %s' % (l[7:])) elif l.startswith('%warning'): l = self._expand(l) log.stderr('warning: %s' % (l[9:])) log.warning(l[9:]) if not directive: l = self._expand(l) ls = self.tags.split(l, 1) log.trace('config: %s: _tag: %s %s' % (self.name, l, ls)) if len(ls) > 1: info = ls[0].lower() if info[-1] == ':': info = info[:-1] info_data = ls[1].strip() else: info_data = ls[0].strip() if info is not None: self._info_append(info, info_data) else: log.warning("invalid format: '%s'" % (info_data[:-1])) else: l = self._expand(l) log.trace('config: %s: _data: %s %s' % (self.name, l, new_data)) new_data.append(l) return (directive, info, data + new_data)
def optimizeByCsv(csvPath, resDir, cdnDir): log.good("处理 %s ..."%csvPath) csvObj = csv.reader(file(csvPath, 'rb')) absResPath = os.path.abspath(resDir) curDir = os.path.abspath(".") for line in csvObj: if len(line) > 0: os.chdir(cdnDir) pathname = line[0] if not os.path.exists(pathname): # log.error("文件 %s/%s 不存在"%(cdnDir, pathname)) os.chdir(curDir) continue targetPath = os.path.join(absResPath, pathname) log.trace("from:"+pathname+" to:"+targetPath) try: os.unlink(targetPath) except: pass try: os.renames(pathname, targetPath) os.chdir(curDir) except Exception as e: log.error("exception:%s file:%s"%(e, pathname)) log.good("处理 %s 结束"%csvPath)
def _ifs(self, config, ls, label, iftrue, isvalid, dir, info): in_iftrue = True data = [] while True: if isvalid and \ ((iftrue and in_iftrue) or (not iftrue and not in_iftrue)): this_isvalid = True else: this_isvalid = False r = self._parse(config, dir, info, roc=True, isvalid=this_isvalid) if r[0] == 'package': if this_isvalid: dir, info, data = self._process_package(r, dir, info, data) elif r[0] == 'control': if r[1] == '%end': self._error(label + ' without %endif') raise error.general('terminating build') if r[1] == '%endif': log.trace('config: %s: _ifs: %s %s' % (self.name, r[1], this_isvalid)) return data if r[1] == '%else': in_iftrue = False elif r[0] == 'directive': if this_isvalid: if r[1] == '%include': self.load(r[2][0]) continue dir, info, data = self._process_directive( r, dir, info, data) elif r[0] == 'data': if this_isvalid: dir, info, data = self._process_data(r, dir, info, data)
def sortAs(self, sortByFirstName=True): ''' sort contact name @type sortByFirstName: boolean @param sortByFirstName: whether sort contact name by first name ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search",True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start sorting...") self.device.press("KEYCODE_MENU","DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView=self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("Sort list by").touch() trace("click Sort list by, dump, please wait...") self.vc.dump() if sortByFirstName: self.vc.findViewWithTextOrRaise("First name").touch() else: self.vc.findViewWithTextOrRaise("Last name").touch() sleep(2)
def parse_options(self, name, flags, func, argstring, defopts=None, case_insensetive = None): log.trace( 'entry', [name, flags, func, argstring, defopts, case_insensetive] ) self.toolopts = defopts or {} self.toolopts["Name"]=name self.xopts=[] self.includes=[] self.forced_includes=[] self.defines=[] self.nodefaultlibs=[] self.xdeps=[] # expand_variables() is a recursive method that generates mountains # of data if logging is done inside of it. Instead, we'll need to # wrap the calls here to see what the params/return values are. # This still adds 300k to the logfiles in a simple case, we can push # up the execution path and instead investigate where variables are # getting set. line = makefile.expand_variables("$(%s)"%flags, self.variables) ProcessOptions( line, func, argstring, case_insensetive) self.toolopts["ForcedIncludeFiles"]=string.join(self.forced_includes,",") self.toolopts["AdditionalOptions"]=string.join(self.xopts) self.toolopts["AdditionalIncludeDirectories"]=string.join(self.includes,",") self.toolopts["PreprocessorDefinitions"]=string.join(self.defines,",") self.toolopts["IgnoreDefaultLibraryNames"]=string.join(self.nodefaultlibs,";") self.toolopts["AdditionalDependencies"]=string.join(self.xdeps," ") log.trace( 'exit' , self.toolopts ) return self.toolopts
def viewAs(self, viewAsFirstNameFirst=True): ''' view contact name @type viewAsFirstNameFirst: boolean @param viewAsFirstNameFirst: whether view contact by first name first ''' trace("check contact main UI, dump, please wait...") self.vc.dump() while not self.getView("Search",True): self.device.press('KEYCODE_BACK') sleep(2) self.vc.dump() trace("start viewing...") self.device.press("KEYCODE_MENU","DOWN_AND_UP") trace("click menu, dump, please wait...") self.vc.dump() settingsView=self.getView("Settings") settingsView.touch() sleep(2) trace("click Settings, dump, please wait...") self.vc.dump() self.vc.findViewWithTextOrRaise("View contact names as").touch() trace("click View contact names as, dump, please wait...") self.vc.dump() if viewAsFirstNameFirst: self.vc.findViewWithTextOrRaise("First name first").touch() else: self.vc.findViewWithTextOrRaise("Last name first").touch() sleep(2)
def __init__(self, name, opts, macros = None, directives = None, ignores = None): self.opts = opts if macros is None: self.macros = opts.defaults else: self.macros = macros self.init_name = name self.directives = ['%include'] if directives: self.directives += directives self.ignores = ignores log.trace('config: %s' % (name)) self.disable_macro_reassign = False self.configpath = [] self.wss = re.compile(r'\s+') self.tags = re.compile(r':+') self.sf = re.compile(r'%\([^\)]+\)') for arg in self.opts.args: if arg.startswith('--with-') or arg.startswith('--without-'): label = arg[2:].lower().replace('-', '_') self.macros.define(label) self._includes = [] self.load_depth = 0 self.lc = 0 self.name = 'none'
def editDetails(self,name='',phone='',email='',notes='',address='',nickname=''): ''' edit contact details ''' self.check() view = self.getView('id/no_id/27',iD=True) view.touch() sleep(4) trace('enter contact OK') self.device.press('KEYCODE_MENU','DOWN_AND_UP') view = self.getView('Edit') view.touch() sleep(3) trace('enter contact edit view OK') if not name=='': self.editName(name) if not phone=='': if self.getDetails('Phone'): self.editPhone(phone) else: self.editPhone(phone,add=True) self.back() sleep(3) self.back()
def host_setup(opts): """ Basic sanity check. All executables and directories must exist.""" checks = { 'none': _check_none, 'triplet': _check_triplet, 'dir': _check_dir, 'exe': _check_exe } sane = True for d in opts.defaults.keys(): try: (test, constraint, value) = opts.defaults.get(d) except: if opts.defaults.get(d) is None: raise error.general('invalid default: %s: not found' % (d)) else: raise error.general('invalid default: %s [%r]' % (d, opts.defaults.get(d))) if test != 'none': value = opts.defaults.expand(value) if test not in checks: raise error.general('invalid check test: %s [%r]' % (test, opts.defaults.get(d))) ok = checks[test](opts, d, value, constraint) if ok: tag = ' ' else: tag = '*' log.trace('%c %15s: %r -> "%s"' % (tag, d, opts.defaults.get(d), value)) if sane and not ok: sane = False return sane
def editPhone(self,phone,add=False): trace("edit contact's phone") self.check() if not add: trace('edit phone with no add') #find EditText of Phone view = self.getView('Phone') editId = 'id/no_id/'+str(int((view.getId())[-2:])+6) view = self.getView(editId,iD=True) #edit phone number self.device.drag(view.getXY(),view.getXY(),3.0) self.device.press('KEYCODE_DEL','DOWN_AND_UP') view.type(phone) sleep(1) trace('edit phone with no add OK') else: trace('edit phone with add') #touch 'Add another field' view = self.getView('Add another field') view.touch() sleep(3) #touch 'Phone' and edit view = self.getView('Phone') view.touch() sleep(2) self.device.type(phone) sleep(1) trace('edit phone with add OK')
def cbUnlinkFile(pathname, param): pattern = param["pattern"] lpathname = pathname.lower() m = pattern.match(lpathname) if m: os.unlink(pathname) log.trace("unlink:%s"%pathname)
def updateDetails(self, fieldName, content): ''' update details of 'fieldName' with 'content' @type fieldName: str @param fieldName: name of field that will be eidt , e.g: Phone,Email,etc @type content: str @param content: edit content @return:True ''' trace('Edit field ' + fieldName + ' info') #find fieldName while not self.getView(fieldName): self.slide('up') sleep(2) #get editView of fieldName view = self.getView(fieldName, dump=False) view2 = self.getView(view.getId()[:-2] + str(int(view.getId()[-2:]) + 6), iD=True) #wipe old content and update with new content self.wipe(view2) sleep(1) view2.type(content) sleep(1) return True
def _process_data(self, results, directive, info, data): new_data = [] for l in results[1]: if l.startswith('%error'): l = self._expand(l) raise error.general('config error: %s' % (l[7:])) elif l.startswith('%warning'): l = self._expand(l) log.stderr('warning: %s' % (l[9:])) log.warning(l[9:]) if not directive: l = self._expand(l) ls = self.tags.split(l, 1) log.trace('config: %s: _tag: %s %s' % (self.name, l, ls)) if len(ls) > 1: info = ls[0].lower() if info[-1] == ':': info = info[:-1] info_data = ls[1].strip() else: info_data = ls[0].strip() if info is not None: self._info_append(info, info_data) else: log.warning("invalid format: '%s'" % (info_data[:-1])) else: log.trace('config: %s: _data: %s %s' % (self.name, l, new_data)) new_data.append(l) return (directive, info, data + new_data)
def Checkout(self, tag, module_list, az=None, timestamp=None, nonrecursive=0, dir=None): """Given a CVS tag and a list of CVS modules, check them out.""" log.trace('entry', [tag, module_list, az, timestamp, nonrecursive, dir]) #print "cvs.Checkout(%s,%s,az=%s,timestamp=%s, %s, %s)" % ( # repr(tag),repr(module_list), # repr(az),repr(timestamp), repr(nonrecursive), repr(dir)) module_list = listify(module_list) if az: if len(module_list) > 1: print "Cannot checkout two modules as the same name" sys.exit(1) update_list, checkout_list = self.update_checkout_list( tag, module_list, az, dir) #print "UPDATE_LIST=%s" % repr(update_list) #print "CHECKOUT_LIST=%s" % repr(checkout_list) if update_list: self.update(tag, update_list, az, timestamp, nonrecursive, dir) if checkout_list: self.checkout(tag, checkout_list, az, timestamp, nonrecursive, dir) log.trace('exit')
def Checkout(tag, module_list, repository_name="", az=None, timestamp=None, nonrecursive=0, zap=None): log.trace('entry', [module_list, repository_name, az, timestamp, nonrecursive, zap]) module_list = listify(module_list) if cvs_checkout_hook: module_list = cvs_checkout_hook(tag, module_list, repository_name, az, timestamp, nonrecursive) if not module_list: return if zap: for mod in module_list: if az: mod = az if os.path.exists(mod): import thread print "DELETING: %s [%d] START" % (mod, thread.get_ident()) shell.rm(mod) print "DELETING: %s [%d] END" % (mod, thread.get_ident()) log.trace('exit') return Get(repository_name).Checkout(tag, module_list, az, timestamp, nonrecursive)
def worker_thread(self, id): log.debug('%s started'%id) while True: try: job = self.jobs.get(block=True, timeout=0.1) self.jobs.task_done() except Queue.Empty: continue if job == None: log.trace('got signal to quit') break handle, user_func, args, user_callback, user_cb_args = job try: result = user_func(args) status = True except BaseException,e: status = False result = e log.trace('%s one job done'%id) self.results.put(handle, (status, result)) if user_callback: try: user_callback(handle, user_cb_args) except: pass
def getLock(self): """getLock() Gets an exclusive lock on the file. This call is blocking. In some cases, might exit execution without a lock (like on an IO exception). Caller should always test hasLock() to be sure the lock was actually received. """ log.trace('entry') count = 0 # How many times have we looped self.__threadLock.acquire() try: while not self.__hasLock(): if self.__lockfileExists(): if self.__isTimeToCheckForStaleLocks(count): self.__checkForStaleLock() self.__threadLock.release() time.sleep(self.__sleepTime) count += 1 self.__threadLock.acquire() else: self.__tryToGetLock() finally: self.__threadLock.release() log.trace('exit')
def find_distribution_cvs(self, locations): log.trace( 'entry' , [ locations ] ) for dir in locations: log.debug( 'Trying to find %s' % dir ) if not self.cvs_dir_check(dir): log.debug( 'Failed cvs_dir_check on "%s" - skipping.' % dir ) continue # Once we have a dir, let's do something with it. message = "Looking for %s in %s (don't worry if this fails)" % (self.cvs_path, dir) log.debug( message ) outmsg.verbose( message ) try: cvs.Checkout(self.cvs_tag, dir, self.cvs_root, os.path.join(tmpdir(),dir), self.cvs_timestamp) except cvs.cvs_error: ## Ignore cvs errors, report them as missing distributions instead log.warn( 'Failed to check out %s - skipping' % dir ) return dir = os.path.join(os.curdir, tmpdir(), dir) try: for f in os.listdir(dir): if string.lower(f) not in ["cvs"]: return dir except OSError: pass log.trace( 'exit' ) return None
def recordDLL( self , dll , base , size ): """recordDLL(d,b,s) Records dll d with base b and size s in the basefile. If data for d is already present, the new data will replace the old data (only one record can exist per dll). Preconditions: this process has a lock on the basefile data has been read in """ # Actually, writes the entire file after removing the original entry # for the DLL, if any. log.trace( 'entry' , [ dll , base , size ] ) self.__threadLock.acquire() try: self.__checkLock() self.__checkDataCached() if self.__isDLLRecorded( dll ): log.debug( 'DLL %s previously recorded - removing.' % dll ) self.__removeDLL( dll ) log.debug( 'Adding record for %s' % dll ) self.__addRecord( [ dll , "0x%x" % base , "0x%x" % size ] ) log.debug( 'Recording data to basefile.' ) self.__recordData() finally: self.__threadLock.release() log.trace( 'exit' )