rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if value.startswith("["): if value.endswith("]"): value2 = value[1:-1].strip().split(",") if len(value2) == 1 and value2[0] == "": config[key] = [] else: config[key] = [s_or_i(s.strip()) for s in value2]
if (((value.startswith("[") and not value.endswith("]")) or (not value.startswith("[") and value.endswith("]")))): raise ConfigSyntaxErrorException( "config syntax error: list '%s' missing [ or ]" % value) elif value.startswith("[") and value.endswith("]"): value2 = value[1:-1].strip().split(",") if len(value2) == 1 an...
def s_or_i(text): """Takes a string and if it begins with " or ' and ends with " or ', then it returns the string. If it's an int, returns the int. Otherwise it returns the text. """ if text.startswith('"'): if text.endswith('"'): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s'...
raise ConfigSyntaxErrorException("config syntax error: " "list '%s' missing end ]" % value)
config[key] = [s_or_i(s.strip()) for s in value2]
def s_or_i(text): """Takes a string and if it begins with " or ' and ends with " or ', then it returns the string. If it's an int, returns the int. Otherwise it returns the text. """ if text.startswith('"'): if text.endswith('"'): return text[1:-1] raise ConfigSyntaxErrorException("config syntax error: " "string '%s'...
except AttributeError:
except KeyError:
def cb_head(args): # adds a taglist to header/footer request = args["request"] entry = args["entry"] data = request.get_data() config = request.get_configuration() tagsdata = data.get("tagsdata", {}) tags = tagsdata.keys() tags.sort() start_t = config.get("tags_list_start", '<p>') item_t = config.get("tags_list_item"...
if ext not in ["." + taste, ""]:
if ext not in ["." + taste, ""] or name.startswith("."):
def get_included_flavour(taste): """ PyBlosxom comes with flavours in taste.flav directories in the flavours subdirectory of the Pyblosxom package. This method pulls the template files for the associated taste (assuming it exists) or None if it doesn't. @param taste: The name of the taste. e.g. "html", "rss", ... @t...
return SelOne.pick()
return SelOne.pick(self)
def pick(self): if self.decider.decide(): return SelOne.pick() else: return []
else: self.hard_formulas.append(formula)
else:
def __init__(self, filename_or_list=None, defaultInferenceMethod=InferenceMethods.MCSAT, parameterType='weights', verbose=False, mlnContent=None): ''' constructs an MLN object at least one of the arguments filename_or_list: either a single filename or a list of filenames (.mln files) mlnContent: string containing an ML...
if verbose: "setting hard weights to %f" % hard_weight
if verbose: print "setting hard weights to %f" % hard_weight
def _createFormulaGroundings(self, verbose=False): '''this is the method that creates the ground MRF''' self.gndFormulas = [] self.gndAtomOccurrencesInGFs = [[] for i in range(len(self.gndAtoms))] if verbose: print "grounding formulas..." for idxFormula, formula in enumerate(self.formulas): if verbose: print " %s" % s...
f.weight = hard_weight
f.weight = hard_weight self.printGroundFormulas()
def _createFormulaGroundings(self, verbose=False): '''this is the method that creates the ground MRF''' self.gndFormulas = [] self.gndAtomOccurrencesInGFs = [[] for i in range(len(self.gndAtoms))] if verbose: print "grounding formulas..." for idxFormula, formula in enumerate(self.formulas): if verbose: print " %s" % s...
var.set(self.settings.get("maxSteps", ""))
var.set(self.settings.get("maxSteps", "1000"))
def __init__(self, master, dir, settings): self.initialized = False master.title("BLN Query Tool") self.master = master self.settings = settings if not "queryByDB" in self.settings: self.settings["queryByDB"] = {}
return self.pick()
return SelOne.pick()
def pick(self): if self.decider.decide(): return self.pick() else: return []
self.selected_emln = FilePickEdit(self.selected_mln, "*.emln", None, 12, self.changedMLN, rename_on_edit=self.settings.get("mln_rename", 0), font=config.fixed_width_font, coloring=config.coloring)
self.selected_emln = FilePickEdit(self.selected_mln, "*.emln", None, 12, None, rename_on_edit=self.settings.get("mln_rename", 0), font=config.fixed_width_font, coloring=config.coloring)
def __init__(self, master, dir, settings): self.initialized = False master.title("MLN Query Tool") self.master = master self.settings = settings if not "queryByDB" in self.settings: self.settings["queryByDB"] = {} if not "emlnByDB" in self.settings: self.settings["emlnByDB"] = {}
if default_file in self.files:
self.select(default_file) self.row = row def select(self, filename): ''' selects the item given by filename ''' if filename in self.files:
def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True): ''' file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) ''' self.master = master self.user_onChange = user_onChange Frame.__init__(self, master) ro...
self.picked_name.set(default_file)
self.picked_name.set(filename)
def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True): ''' file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) ''' self.master = master self.user_onChange = user_onChange Frame.__init__(self, master) ro...
self.list.selectitem(default_file) self.onSelChange(default_file) pass
self.list.selectitem(filename) self.onSelChange(filename)
def __init__(self, master, file_mask, default_file, edit_height = None, user_onChange = None, rename_on_edit=0, font = None, coloring=True): ''' file_mask: file mask (e.g. "*.foo") or list of file masks (e.g. ["*.foo", "*.abl"]) ''' self.master = master self.user_onChange = user_onChange Frame.__init__(self, master) ro...
self.select(filename)
def get(self): filename = self.save_name.get() if self.unmodified == False: self.unmodified = True # save the file f = file(filename, "w") f.write(self.editor.get("1.0", END)) f.close() # add it to the list of files if not filename in self.files: self.files.append(filename) self.files.sort() self.list.destroy() self.ma...
either the world object (which is expected to have a container for objtype) or
either the world object (if it has a container for objtype, it is used for generated objects; otherwise the container is added) or
def __init__(self, objtype, world_or_container, attrgens = None): ''' objtype: a string representing the name of the type of the objects that this generator is to generate world_or_container: either the world object (which is expected to have a container for objtype) or directly a container (ObjectContainer instance) i...
raise Exception("World object does not have a container for '%s'" % objtype)
self.container = world_or_container.addContainer(objtype)
def __init__(self, objtype, world_or_container, attrgens = None): ''' objtype: a string representing the name of the type of the objects that this generator is to generate world_or_container: either the world object (which is expected to have a container for objtype) or directly a container (ObjectContainer instance) i...
def generate(self, **args): o = Object(self.objtype, **args) self._createAttributes(o, **args) self._createLinks(o, **args)
def generate(self, **kwargs): o = Object(self.objtype, **kwargs) self._createAttributes(o, **kwargs) self._createLinks(o, **kwargs)
def generate(self, **args): o = Object(self.objtype, **args) self._createAttributes(o, **args) self._createLinks(o, **args) self.container.add(o) return o
distribuction = dict(distribution)
distribution = dict(distribution)
def __init__(self, distribution=None, **convenient_distribution_specification): if distribution is None: distribution = {} distribuction = dict(distribution) # copying for safety reasons distribution.update(convenient_distribution_specification) self.distribution = distribution sum = 0.0 for item,value in distribution....
hard_formulas = []
self.hard_formulas = []
def __init__(self, filename_or_list=None, defaultInferenceMethod=InferenceMethods.MCSAT, parameterType='weights', verbose=False, mlnContent=None): ''' constructs an MLN object at least one of the arguments filename_or_list: either a single filename or a list of filenames (.mln files) mlnContent: string containing an ML...
hard_formulas.append(formula)
self.hard_formulas.append(formula) formula.weight = None
def __init__(self, filename_or_list=None, defaultInferenceMethod=InferenceMethods.MCSAT, parameterType='weights', verbose=False, mlnContent=None): ''' constructs an MLN object at least one of the arguments filename_or_list: either a single filename or a list of filenames (.mln files) mlnContent: string containing an ML...
hard_weight = max(20, max_weight+20) for formula in hard_formulas: formula.weight = hard_weight
def __init__(self, filename_or_list=None, defaultInferenceMethod=InferenceMethods.MCSAT, parameterType='weights', verbose=False, mlnContent=None): ''' constructs an MLN object at least one of the arguments filename_or_list: either a single filename or a list of filenames (.mln files) mlnContent: string containing an ML...
w = str(f.weight) w = re.sub(r'domSize\((.*?)\)', r'self.domSize("\1")', w) try: f.weight = eval(w) except: raise Exception("Evaluation error while trying to compute '%s'" % w)
if f.weight is not None: w = str(f.weight) while "$" in w: for (var,value) in self.vars.iteritems(): w = w.replace(var, value) w = re.sub(r'domSize\((.*?)\)', r'self.domSize("\1")', w) try: f.weight = eval(w) except: sys.stderr.write("Evaluation error while trying to compute '%s'\n" % w) raise max_weight = max(abs(f.we...
def _createFormulaGroundings(self, verbose=False): '''this is the method that creates the ground MRF''' self.gndFormulas = [] self.gndAtomOccurrencesInGFs = [[] for i in range(len(self.gndAtoms))] if verbose: print "grounding formulas..." for idxFormula, formula in enumerate(self.formulas): if verbose: print " %s" % s...
self.master.deiconify() self.setGeometry()
def learn(self): try: # update settings mln = self.selected_mln.get() db = self.selected_db.get() if "" in (db,mln): return method = self.selected_method.get() params = self.params.get() self.settings["mln"] = mln self.settings["db"] = db self.settings["output_filename"] = self.output_filename.get() self.settings["para...
from sys import argv
def learn(self): try: # update settings mln = self.selected_mln.get() db = self.selected_db.get() if "" in (db,mln): return method = self.selected_method.get() params = self.params.get() self.settings["mln"] = mln self.settings["db"] = db self.settings["output_filename"] = self.output_filename.get() self.settings["para...
app = LearnWeights(root, ".", settings) root.mainloop()
app = LearnWeights(root, ".", settings) if "-run" in argv: app.learn() else: root.mainloop()
def learn(self): try: # update settings mln = self.selected_mln.get() db = self.selected_db.get() if "" in (db,mln): return method = self.selected_method.get() params = self.params.get() self.settings["mln"] = mln self.settings["db"] = db self.settings["output_filename"] = self.output_filename.get() self.settings["para...
def iterGroundings(self, mln): other_params = list(set(self.literal.params).difference(self.fixed_params)) for assignment in self._iterAssignment(mln, list(self.fixed_params), {}):
def iterGroundings(self, mln): a = {} other_params = [] for param in self.literal.params: if param[0].isupper(): a[param] = param else: if param not in self.fixed_params: other_params.append(param) for assignment in self._iterAssignment(mln, list(self.fixed_params), a):
def iterGroundings(self, mln): other_params = list(set(self.literal.params).difference(self.fixed_params)) for assignment in self._iterAssignment(mln, list(self.fixed_params), {}): gndAtoms = [] for full_assignment in self._iterAssignment(mln, list(other_params), assignment): gndLit = self.literal.ground(mln, full_assi...
if len(toks) == 4:
print toks if len(toks) in (3,4):
def trigger(self, a, loc, toks, op): #print op, toks if op == 'lit': negated = False if toks[0] == '!' or toks[0] == '*': if toks[0] == '*': negated = 2 else: negated = True toks = toks[1] else: toks = toks[0] self.stack.append(Lit(negated, toks[0], toks[1])) elif op == '!': if len(toks) == 1: formula = Negation(self.s...
fixed_params, op, count = list(toks[1]), toks[2], int(toks[3])
if len(toks) == 3: fixed_params, op, count = [], toks[1], int(toks[2]) else: fixed_params, op, count = list(toks[1]), toks[2], int(toks[3])
def trigger(self, a, loc, toks, op): #print op, toks if op == 'lit': negated = False if toks[0] == '!' or toks[0] == '*': if toks[0] == '*': negated = 2 else: negated = True toks = toks[1] else: toks = toks[0] self.stack.append(Lit(negated, toks[0], toks[1])) elif op == '!': if len(toks) == 1: formula = Negation(self.s...
count_constraint = Literal("count(").suppress() + atom + Literal("|").suppress() + varList + Literal(")").suppress() + (Literal("=") | Literal(">=") | Literal("<=")) + Word(nums)
count_constraint = Literal("count(").suppress() + atom + Optional(Literal("|").suppress() + varList) + Literal(")").suppress() + (Literal("=") | Literal(">=") | Literal("<=")) + Word(nums)
def getConstraint(self): if len(self.stack) > 1: raise Exception("Not a valid formula - reduces to more than one element %s" % str(self.stack)) if len(self.stack) == 0: raise Exception("Constraint could not be parsed") if not isinstance(self.stack[0], Constraint): raise Exception("Not an instance of Constraint!") retur...
test = 'NF'
test = 'count'
def parseFormula(input): tree = TreeBuilder() literal.setParseAction(lambda a,b,c: tree.trigger(a,b,c,'lit')) negation.setParseAction(lambda a,b,c: tree.trigger(a,b,c,'!')) #item.setParseAction(lambda a,b,c: foo(a,b,c,'item')) disjunction.setParseAction(lambda a,b,c: tree.trigger(a,b,c,'v')) conjunction.setParseAction(...
self.setUsername(base.appRunner.getToken("username")) self.loginDialogShown = True
token = base.appRunner.getToken("username") if token != "" and token != "Unnamed": self.setUsername(token) self.loginDialogShown = True
def __init__(self, skipIntro = False): render.show() engine.renderLit.show() # In case we just got back from the tutorial, which hides everything sometimes. engine.Mouse.hideCursor() self.backgroundSound = audio.FlatSound("menu/background.ogg", volume = 0.3) self.backgroundSound.setVolume(0) self.backgroundSound.setLoo...
if self.backend.enableRespawn: self.unitSelector.show()
self.unitSelector.show()
def showBuyScreen(self): self.unitSelector.clearPurchases() if self.backend.gameOver: self.promptText.setText("Next game in 10 seconds...") else: self.promptText.hide() if self.backend.enableRespawn: self.unitSelector.show() self.gameui.hide()
if not self.loginDialogShown and self.showLogin and elapsedTime > self.introTime: self.loginDialog.show() self.loginDialogShown = True
if elapsedTime > self.introTime: if not self.loginDialogShown and self.showLogin: self.loginDialog.show() self.loginDialogShown = True elif self.chatLog.hidden and not self.showLogin: self.chatLog.show()
def update(self): if not self.active: return net.context.readTick() if self.startTime == -1: self.startTime = engine.clock.getTime() elapsedTime = engine.clock.getTime() - self.startTime if elapsedTime < self.introTime: blend = elapsedTime / self.introTime if self.introText != None: self.introText["scale"] = 0.05 + (bl...
opts, args = getopt.getopt(sys.argv[1:], "r", ["release"]) testing_only = (len(opts) == 0 or opts[0][0] not in ("-r", "--release"))
def upload_to_server(testing_only): print "Uploading to server\n" target_folder = "/home/pculture/data/mirovideoconverter" "/{0}MiroConverterSetup.msi".format("testing/" if testing_only else "") for line in os.popen(("pscp -v -i %USERPROFILE%\\.ssh\\osuosl.ppk " ".\\WindowsSetup\\Release\MiroConverterSetup.msi " "pcult...
for line in os.popen("devenv /build Release FFMPEGWrapper.sln /project WindowsSetup").readlines():
for line in os.popen(("devenv /build Release FFMPEGWrapper.sln " "/project WindowsSetup")).readlines():
def build(): print "Building" for line in os.popen("devenv /build Release FFMPEGWrapper.sln /project WindowsSetup").readlines(): print line
s = self.connect(slaveBackend=backend.ipAddress) reply = self._sendRequest(s, msg) result = self._isOk(reply) s.shutdown(socket.SHUT_RDWR) s.close()
try: s = self.connect(slaveBackend=backend.ipAddress) reply = self._sendRequest(s, msg) result = self._isOk(reply) s.shutdown(socket.SHUT_RDWR) s.close() except socket.error, se: if backend.slave: log.error('YYY Slave down, rerouting to master') return self.generateThumbnail(program, self.db().getMasterBackend().ipAddr...
def generateThumbnail(self, program, backendHost, width=None, height=None): """ Request the backend generate a thumbnail for a program. The backend generates the thumbnail and persists it do the filesystem regardless of whether a thumbnail existed or not. Thumbnail filename = recording filename + '.png' @type program:...
commandSocket = self.connect(announce='Playback', slaveBackend=backend.ipAddress)
try: commandSocket = self.connect(announce='Playback', slaveBackend=backend.ipAddress) except socket.error, se: if backend.slave: log.error('XXX slave %s is not available...trying master' % backend) return self.transferFile(backendPath, destPath, self.db().getMasterBackend().ipAddress, numBytes)
def transferFile(self, backendPath, destPath, backendHost, numBytes=None): """ Copy a file from the remote myththv backend to destPath on the local filesystem. Valid files include recordings, thumbnails, and channel icons. @param backendPath: myth url to file. Ex: myth://<host>:<port>/<path> @param destPath: path of d...
programs = map(lambda t: TVProgram({'title': t, 'category_type':'movie'}, translator=Mock()), self.movies) provider = TheMovieDbFanartProvider(nextProvider=None) @run_async def work(p): posters = provider.getPosters(p) if not posters: self.fail = True for poster in posters: log.debug('%s - %s' % (p.title(), poster)) ...
def test_getRandomPoster_When_program_is_not_movie_Then_returns_poster(self): # Setup program = TVProgram({'title':'Seinfeld', 'category_type':'series'}, translator=Mock()) provider = TvdbFanartProvider(self.platform, nextProvider=None) # Test def test_getPosters_When_pounded_by_many_threads_Then_doesnt_fail_misera...
self.onEvent({'id': Event.SETTING_CHANGED, 'old':'DontCare', 'new':self.settings.get('logging_enabled')})
self.onEvent({'id': Event.SETTING_CHANGED, 'tag':'logging_enabled', 'old':'DontCare', 'new':self.settings.get('logging_enabled')})
def bootstrapSettings(self): self.stage = 'Initializing Settings' from fanart import FanArt from mythbox.settings import MythSettings self.settings = MythSettings(self.platform, self.translator, 'settings.xml', self.bus) self.log.debug('Settings = \n %s' % self.settings) self.fanArt = FanArt(self.platform, self.httpCac...
self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
self.win = xbmcgui.Window(xbmcgui.getCurrentWindowDialogId())
def onInit(self): #log.debug('onInit %s' % self.win) #log.debug('dlg id = %s' % xbmcgui.getCurrentWindowDialogId()) self.win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) self.enabledCheckBox = self.getControl(212) self.autoCommFlagCheckBox = self.getControl(205) self.autoExpireCheckBox = self.getControl(207) self.au...
backendPath = recording.getRemoteThumbnailPath()
backendPath = recording.getBareFilename() + '.640x360.png'
def test_transferFile_FileExistsOnBackend_Success(self):
thumb = md5(url).hexdigest()
thumb = md5.new(url).hexdigest()
def calculate_cache_path(cache_location, url): """Checks if [cache_location]/[hash_of_url].headers and .body exist """ thumb = md5(url).hexdigest() header = os.path.join(cache_location, thumb + ".headers") body = os.path.join(cache_location, thumb + ".body") return header, body
self.closeRequested = False
self.startLock.wait()
def __init__(self, httpCache, nextProvider=None): BaseFanartProvider.__init__(self, nextProvider) self.httpCache = httpCache self.workQueue = Queue.Queue() self.workThread = self.workerBee() self.closeRequested = False
self.conn().generateThumbnail(program, program.hostname()) result = self.conn().transferFile(program.getBareFilename() + '.640x360.png', dest, program.hostname())
key = self.getKey(program) result = self.conn().transferFile(key, dest, program.hostname())
def store(self, program, dest): """ @type program : RecordedProgram @param dest: file to save downloaded program thumbnail to """ self.conn().generateThumbnail(program, program.hostname()) result = self.conn().transferFile(program.getBareFilename() + '.640x360.png', dest, program.hostname()) if result == -1: # no recou...
fp = open(dest, 'w') fp.write(dest, '') fp.close()
if self.conn().generateThumbnail(program, program.hostname()): result = self.conn().transferFile(key, dest, program.hostname()) if result == -1: self.writeStub(dest) else: self.writeStub(dest)
def store(self, program, dest): """ @type program : RecordedProgram @param dest: file to save downloaded program thumbnail to """ self.conn().generateThumbnail(program, program.hostname()) result = self.conn().transferFile(program.getBareFilename() + '.640x360.png', dest, program.hostname()) if result == -1: # no recou...
return md5.new(safe_str(program.getRemoteThumbnailPath())).hexdigest()
return md5.new(safe_str(self.getKey(program))).hexdigest() def getKey(self, program): return program.getFilename() + '.640x360.png' def writeStub(self, dest): fp = open(dest, 'w') fp.write(dest, '') fp.close()
def hash(self, program): return md5.new(safe_str(program.getRemoteThumbnailPath())).hexdigest()
pass
d = { 'type':'xbmc.python.script', 'summary': 'script summary', 'name': 'MythBox', 'id': 'script.mythbox', 'profile': 'special://profile/addon_data/script.mythbox/', 'path':'/tmp/script.mythbox' } return d.get('id', 'TODO')
def getAddonInfo(self, id): ''' Returns the value of an addon property as a string id : string - id of the property that the module needs to access *Note, choices are (author, changelog, description, disclaimer, fanart. icon, id, name, path profile, stars, summary, type, version) You can use the above as keywor...
return ''
return 'TODO'
def getLocalizedString(self, id): ''' | getLocalizedString(id) -- Returns an addon's localized 'unicode string'. | | id : integer - id# for string you want to localize. | | *Note, You can use the above as keywords for arguments. | | example: | - locstr = self.Addon.getLocalizedStr...
pass
import xbmcaddon self.addon = xbmcaddon.Addon('script.mythbox')
def __init__(self, scriptPath, defaultLanguage=None, *args, **kwargs): pass
return xbmc.getLocalizedString(id)
return self.addon.getLocalizedString(id)
def get(self, id): """ Alias for getLocalizedString(...)
import xbmc.Language
def full_exes(program): for path in os.environ['PATH'].split(os.pathsep): log.debug('Checking PATH %s for %s' %(path, program)) exe = os.path.join(path, program) if is_exe(exe): yield exe
self.setFocus(self.playSkipButton)
if self.getFocusId() == self.playButton.getId(): self.setFocus(self.playSkipButton)
def renderCommBreaks(self): self.playSkipButton.setEnabled(self.program.hasCommercials()) self.firstInQueueButton.setEnabled(False) commBreaks = 'No' if self.program.isCommFlagged(): if self.program.hasCommercials(): # TODO: Only set focus on first entry to screen self.setFocus(self.playSkipButton) commBreaks = "%d" % ...
self.evictorThread = self.evictor()
def __init__(self, factory, maxAgeSecs, reapEverySecs): Pool.__init__(self, factory) self.maxAgeSecs = maxAgeSecs self.reapEverySecs = reapEverySecs self.evictorThread = self.evictor() # TODO: Don't start evictor until something is actually in the pool self.dobs = {} self.stopReaping = False self.numEvictions = 0 log....
strValue = n.childNodes[0].nodeValue
try: strValue = n.childNodes[0].nodeValue except IndexError, ie: pass
def loadStrings(self): # Determine codec for GUI so that loaded messages can be encoded for # GUI immediately language = self.langInfo.getSetting('language.charsets.gui') #log.debug("language = %s"%language) (e,d,r,w) = codecs.lookup(language)
def version(self): return 23056
def version(self): return 56
56: Protocol56()
56: Protocol56(), 23056: Protocol23056()
def version(self): return 56
self.provider.close()
def test_getPosters_When_next_provider_returns_posters_Then_cache_and_return_first_poster_and_add_remaining_to_work_queue(self): httpUrls = [ 'http://www.gstatic.com/hostedimg/1f4337d461f1431c_large', 'http://www.gstatic.com/hostedimg/50edad09a73fa0ed_large', 'http://www.gstatic.com/hostedimg/d915322b880dcaf2_large', '...
try: self.imagePathsByKey.sync() except RuntimeError, re: pass
def getPosters(self, program): posters = [] key = self.createKey('getPosters', program) if key in self.imagePathsByKey: posters = self.imagePathsByKey[key] if not posters and self.nextProvider: posters = self.nextProvider.getPosters(program) if posters: # cache returned poster self.imagePathsByKey[key] = posters # TO...
for p in httpPosters: poster = self.tryToCache(p) if poster: posters.append(poster) return posters
posters = self.cachePosters(httpPosters) return posters def cachePosters(self, httpPosters): results = [] @run_async def async_wrapper(poster): poster = self.tryToCache(poster) if poster: results.append(poster) workers = [] for p in httpPosters: workers.append(async_wrapper(p)) for w in workers: w.join() retur...
def getPosters(self, program): # If the chained provider returns a http:// style url, # cache the contents and return the locally cached file path posters = [] if self.nextProvider: httpPosters = self.nextProvider.getPosters(program) for p in httpPosters: poster = self.tryToCache(p) if poster: posters.append(poster) re...
strId = n.getAttribute("id")
strId = int(n.getAttribute("id"))
def loadStrings(self): # Determine codec for GUI so that loaded messages can be encoded for # GUI immediately language = self.langInfo.getSetting('language.charsets.gui') #log.debug("language = %s"%language) (e,d,r,w) = codecs.lookup(language)
def getFFMpegPath(self):
def getFFMpegPath(self, prompt=False):
def getFFMpegPath(self): return ''
def getFFMpegPath(self):
def getFFMpegPath(self, prompt=False):
def getFFMpegPath(self): path = os.path.join(self.getScriptDataDir(), 'ffmpeg.exe') self.requireFFMpeg(path) return path
def getFFMpegPath(self):
def getFFMpegPath(self, prompt=False):
def getFFMpegPath(self): path = os.path.join(self.getScriptDataDir(), 'ffmpeg') self.requireFFMpeg(path) return path
def renderTree(xml, path, indent):
def renderGroup(xpaths, xml): texts = [] for xpath in xpaths: subset = xml.findall(xpath) subset = [x.text for x in subset if x.text] text = ','.join(subset) if len(subset) > 1: texts.append('"%s"' % text) else: texts.append(text) return ','.join(texts) def renderHeader(groups, xpaths): if not groups: return ','.join(...
def renderTree(xml, path, indent): if indent > 8: return '' r = [] for e in xml.getchildren(): r.append('&nbsp;' * indent * 4 + '<a href="%s">%s</a> = %s<br/>\n' % ((path + urllib.quote_plus(e.tag)), e.tag, e.text)) r.append(renderTree(e, path + e.tag + '/', indent + 1)) return ''.join(r)
for e in xml.getchildren(): r.append('&nbsp;' * indent * 4 + '<a href="%s">%s</a> = %s<br/>\n' % ((path + urllib.quote_plus(e.tag)), e.tag, e.text)) r.append(renderTree(e, path + e.tag + '/', indent + 1))
for e in nodes: children = e.getchildren() filter = 'group' if children else 'xpath' link = path % filter + urllib.quote_plus(e.tag) r.append('&nbsp;' * indent * 4 + '<a href="%s">%s</a> = %s<br/>\n' % (link, e.tag, e.text)) r.append(renderTree(children, path + e.tag + '/', indent + 1))
def renderTree(xml, path, indent): if indent > 8: return '' r = [] for e in xml.getchildren(): r.append('&nbsp;' * indent * 4 + '<a href="%s">%s</a> = %s<br/>\n' % ((path + urllib.quote_plus(e.tag)), e.tag, e.text)) r.append(renderTree(e, path + e.tag + '/', indent + 1)) return ''.join(r)
texts = [] for xpath in xpaths: subset = xml.findall(xpath) texts.extend((x.text for x in subset if x.text)) output = ','.join(texts)
headeroutput = renderHeader(groups, xpaths) output = renderOutput(groups, xpaths, xml)
def get(self): url = self.request.get('url') browse = self.request.get('browse') xpaths = self.request.get_all('xpath') if not url: self.response.out.write(template.render('index.html', {'url':'http://'})) return data = urlfetch.fetch(url).content xml = ElementTree() xml.parse(StringIO(data)) texts = [] for xpath in xp...
link = 'url=%s%s' % (urllib.quote_plus(url), ''.join(['&amp;xpath=%s' % xpath for xpath in xpaths])) path = '?browse=1&amp;%s&amp;xpath=' % link
link = 'url=%s%s%s' % ( urllib.quote_plus(url), ''.join(['&amp;group=%s' % group for group in groups]), ''.join(['&amp;xpath=%s' % xpath for xpath in xpaths])) path = '?browse=1&amp;%s&amp;%%s=' % link.replace('%', '%%')
def get(self): url = self.request.get('url') browse = self.request.get('browse') xpaths = self.request.get_all('xpath') if not url: self.response.out.write(template.render('index.html', {'url':'http://'})) return data = urlfetch.fetch(url).content xml = ElementTree() xml.parse(StringIO(data)) texts = [] for xpath in xp...
'output':output,
'header':headeroutput, 'output':output.replace('\n','<br/>\n'),
def get(self): url = self.request.get('url') browse = self.request.get('browse') xpaths = self.request.get_all('xpath') if not url: self.response.out.write(template.render('index.html', {'url':'http://'})) return data = urlfetch.fetch(url).content xml = ElementTree() xml.parse(StringIO(data)) texts = [] for xpath in xp...
'browse':renderTree(xml.getroot(), path, 0)}))
'browse':renderTree(xml.getroot().getchildren(), path, 0)}))
def get(self): url = self.request.get('url') browse = self.request.get('browse') xpaths = self.request.get_all('xpath') if not url: self.response.out.write(template.render('index.html', {'url':'http://'})) return data = urlfetch.fetch(url).content xml = ElementTree() xml.parse(StringIO(data)) texts = [] for xpath in xp...
import pymbolic
def map_polynomial(self, expr): import pymbolic
result = (result+coeff)*expr.base**(exp-next_exp)
result = (result+coeff)*ev_base**(exp-next_exp)
def map_polynomial(self, expr): import pymbolic
return IdentitityMapper.map_power(expr)
return IdentityMapper.map_power(self, expr)
def map_power(self, expr): from pymbolic.primitives import Expression, Sum
qcd=PSet( Name="QCDPythia6", File=["/vols/cms02/bm409/QCD_Pythia6_*GeV.root"], Weights = PSet( CrossSection = [ 8.762e+08, 6.041e+07, 9.238e+05, 2.547e+04, 1.256e+03, 8.798e+01, 2.186e+00, 1.122e-02 ], Events = [ 6246300, 5228992, 3203440, 3132800, 3274202, 2143390, 2143921, 1184123 ], PtBin ...
from samples_cff import *
def addCutFlow(a) : a+=numComJets a+=alphaT
anal = Analysis("QCDPythia6") addCutFlow(anal) skim = SkimOp( skim_ps.ps() ) anal += skim anal.Run("../results",conf,[qcd])
for bin in range(0,len(qcd6)) : anal = Analysis("Empty") addCutFlow(anal) skim = SkimOp( skim_ps.ps() ) anal += skim anal.Run("results",conf,[qcd6[bin]])
def addCutFlow(a) : a+=numComJets a+=alphaT
def __repr__(this):
def __fix_repr__(this):
def __repr__(this): s = '%s(\n ' % findModuleClassName(this.__class__, __name__) s = '%sVs = [\n' % (s) for v in this.baseShape.Vs: s = '%s %s,\n' % (s, repr(v)) s = '%s ],\n ' % s s = '%sFs = [\n' % (s) for f in this.baseShape.Fs: s = '%s %s,\n' % (s, repr(f)) s = '%s ],\n ' % s if this.baseShape.Es != []: ...
def __new__(this, qLeft = None, axis = Vec3([1, 0, 0]), angle = 0):
def __new__(this, q = None, axis = Vec3([1, 0, 0]), angle = 0):
def __new__(this, qLeft = None, axis = Vec3([1, 0, 0]), angle = 0): """ Initialise a 3D rotation """ if isinstance(qLeft, Quat): try: qLeft = qLeft.normalise() except ZeroDivisionError: pass # will fail on assert below: t = Transform3.__new__(this, [qLeft, qLeft.conjugate()]) assert t.isRot(), "%s doesn't represent a r...
if isinstance(qLeft, Quat): try: qLeft = qLeft.normalise()
if isQuatPair(q): t = Transform3.__new__(this, q) assert t.isRot(), "%s doesn't represent a rotation" % str(q) return t elif isinstance(q, Quat): try: q = q.normalise()
def __new__(this, qLeft = None, axis = Vec3([1, 0, 0]), angle = 0): """ Initialise a 3D rotation """ if isinstance(qLeft, Quat): try: qLeft = qLeft.normalise() except ZeroDivisionError: pass # will fail on assert below: t = Transform3.__new__(this, [qLeft, qLeft.conjugate()]) assert t.isRot(), "%s doesn't represent a r...
t = Transform3.__new__(this, [qLeft, qLeft.conjugate()]) assert t.isRot(), "%s doesn't represent a rotation" % str(qLeft)
t = Transform3.__new__(this, [q, q.conjugate()]) assert t.isRot(), "%s doesn't represent a rotation" % str(q)
def __new__(this, qLeft = None, axis = Vec3([1, 0, 0]), angle = 0): """ Initialise a 3D rotation """ if isinstance(qLeft, Quat): try: qLeft = qLeft.normalise() except ZeroDivisionError: pass # will fail on assert below: t = Transform3.__new__(this, [qLeft, qLeft.conjugate()]) assert t.isRot(), "%s doesn't represent a r...
debug = True
def toPsPiecesStr(this, faceIndices = [], scaling = 1, precision = 7, margin = 1.0e5*defaultFloatMargin, pageSize = PS.PageSizeA4 ): """ Returns a string in PS format that shows the pieces of faces that can be used for constructing a physical model of the object.
this.statusBar.SetStatusText( "ERROR: Stabiliser not a subgroup of final symmetry" )
print "ERROR: Stabiliser not a subgroup of final symmetry"
def __init__(this, Vs, Fs, Es = [], Ns = [], finalSym = isometry.E, stabSym = isometry.E, name = "SymmetricShape"
s['axis_n'] = setup['axis_n']
s['axis'] = setup['axis_n']
def __init__(this, isometries = None, setup = {}): """ The algebraic group DnCn, consisting of n rotations and of n rotary inversions (reflections)
'par': 'axis',
'par': 'axis_n',
def DnC(n): if n == 1: return C2C1 D_n_C_n = MetaDnCn('D%dC%d' % (n, n), (DnCn,), { 'n' : n, 'order': 2 * n, 'initPars': [{ 'type': 'vec3', 'par': 'axis', 'lab': "%d-fold axis" % n }, { 'type': 'vec3', 'par': 'normal_r', 'lab': "normal of reflection" }] } ) D_n_C_n.subgroups = [D_n_C_n, C(n), C2C1, E] # TODO: fix mo...
if this.n % 2 == 1 and this.n > 1: isoms.append( sg(setup = {'axis': this.rotAxes['n']}) )
def realiseSubgroups(this, sg): """ realise an array of possible oriented subgroups for non-oriented sg """ assert isinstance(sg, type) if isinstance(sg, MetaD2nDn): if sg.n == this.n: # D2cDn return [this] elif sg.n > this.n: return [] else: TODO elif isinstance(sg, MetaDn): if sg.n == this.n: return [sg(setup = {'axi...
if sg == C2: return [C2(setup = {'axis': a}) for a in this.rotAxes[2]] elif sg == C3: return [C3(setup = {'axis': a}) for a in this.rotAxes[3]]
if sg == S4A4: return [this]
def realiseSubgroups(this, sg): """ realise an array of possible oriented subgroups for non-oriented sg """ assert isinstance(sg, type) #S4A4, A4, D2nDn, DnCn, C2nCn, Dn, Cn #C3, C2, E if sg == C2: return [C2(setup = {'axis': a}) for a in this.rotAxes[2]] elif sg == C3: return [C3(setup = {'axis': a}) for a in this.rot...
return [ A4(setup = {'o2axis0': o2a[0], 'o2axis1': o2a[1]}), ] elif sg == S4A4: return [this]
return [sg(setup = {'o2axis0': o2a[0], 'o2axis1': o2a[1]})] elif sg == D4D2: o2a = this.rotAxes[2] return [sg(setup = {'axis_n': o2a[0], 'axis_2': o2a[1]})] elif sg == D3C3: isoms = [] for o3 in this.rotAxes[3]: for rn in this.reflNormals: if GeomTypes.eq(rn*o3, 0): isoms.append(sg(setup = {'axis_n': o3, 'normal_r': rn...
def realiseSubgroups(this, sg): """ realise an array of possible oriented subgroups for non-oriented sg """ assert isinstance(sg, type) #S4A4, A4, D2nDn, DnCn, C2nCn, Dn, Cn #C3, C2, E if sg == C2: return [C2(setup = {'axis': a}) for a in this.rotAxes[2]] elif sg == C3: return [C3(setup = {'axis': a}) for a in this.rot...
return [ C2C1(setup = {'axis': normal}) for normal in this.reflNormals ]
return [sg(setup = {'axis': normal}) for normal in this.reflNormals]
def realiseSubgroups(this, sg): """ realise an array of possible oriented subgroups for non-oriented sg """ assert isinstance(sg, type) #S4A4, A4, D2nDn, DnCn, C2nCn, Dn, Cn #C3, C2, E if sg == C2: return [C2(setup = {'axis': a}) for a in this.rotAxes[2]] elif sg == C3: return [C3(setup = {'axis': a}) for a in this.rot...
S4A4.subgroups = [S4A4, A4,
S4A4.subgroups = [S4A4, A4, D4D2, D3C3,
def realiseSubgroups(this, sg): """ realise an array of possible oriented subgroups for non-oriented sg """ assert isinstance(sg, type) #S4A4, A4, D2nDn, DnCn, C2nCn, Dn, Cn #C3, C2, E if sg == C2: return [C2(setup = {'axis': a}) for a in this.rotAxes[2]] elif sg == C3: return [C3(setup = {'axis': a}) for a in this.rot...
A4.subgroups = [A4, C3, C2, E ]
def order(isometry): try: return __order[isometry] except KeyError: return isometry.order
'normal_r': DnxI.defaultSetup['axis_2']
'axis_2': DnxI.defaultSetup['axis_2']
def DxI(n): assert n != 0 try: return DnxIMetas[n] except KeyError: if n == 1: DnxIMetas[n] = C2xI else: D_nxI = MetaDnxI('D%dxI' % n, (DnxI,), { 'n' : n, 'order': 4 * n, 'initPars': [ { 'type': 'vec3', 'par': 'axis_n', 'lab': "%d-fold axis" % n }, { 'type': 'vec3', 'par': 'axis_2', 'lab': "axis of halfturn" } ], 'd...
this.setFaceColorsPerIsometry([dict['colors']])
this.setSymmetricFaceColors([dict['colors']])
def setBaseFaceProperties(this, dictPar = None, **kwargs): """ Define the properties of the faces for the base element.
this.___class__._name__), setup.keys()
this.__class__.__name__), setup.keys()
def checkSetup(this, setup): if this.debug: print this.__class__.__name__, 'checkSetup' if setup != {} and this.initPars == []: print "Warning: class %s doesn't handle any setup pars" % ( this.___class__._name__), setup.keys() for k in setup.keys(): found = False for p in this.initPars: found |= p['par'] == k if found:...
'normal_r': D2nDn.defaultSetup['axis_2']
'axis_2': D2nDn.defaultSetup['axis_2']
def D2nD(n): assert n != 0 try: return D2nDnMetas[n] except KeyError: D_2n_D_n = MetaD2nDn('D%dD%d' % (2*n, n), (D2nDn,), { 'n' : n, 'order': 4 * n, 'mixed': True, 'directParent': D(n), 'initPars': [ { 'type': 'vec3', 'par': 'axis_n', 'lab': "%d-fold axis" % n }, { 'type': 'vec3', 'par': 'axis_2', 'lab': "axis of ha...
r = len(v) == len(w)
try: r = len(v) == len(w) except TypeError: print 'info: comparing different types in Vec (%s)' % v.__class__.__name__ return False
def __eq__(v, w): r = len(v) == len(w) for a, b in zip(v, w): if not r: break r = r and eq(a, b, v.eqMargin) return r
class Transform():
class Transform3():
def vector(v): """Returns the vector part of v (as a Vec3)""" return Vec3(v[1:])
if isinstance(w, Transform):
if isinstance(w, Transform3):
def __mul__(v, w): if isinstance(w, Transform): # v * w = vLeft * wLeft .. wRight * vRight return Transform(v.left * w.left, w.right * v.right) elif isinstance(w, Vec) and len(w) == 3: # TODO: check kind of Transform return Vec3(v.left * Quat([0, w[0], w[1], w[2]]) * v.right) else: raise TypeError, "unsupported op typ...
return Transform(v.left * w.left, w.right * v.right)
return Transform3(v.left * w.left, w.right * v.right)
def __mul__(v, w): if isinstance(w, Transform): # v * w = vLeft * wLeft .. wRight * vRight return Transform(v.left * w.left, w.right * v.right) elif isinstance(w, Vec) and len(w) == 3: # TODO: check kind of Transform return Vec3(v.left * Quat([0, w[0], w[1], w[2]]) * v.right) else: raise TypeError, "unsupported op typ...
return Vec3(v.left * Quat([0, w[0], w[1], w[2]]) * v.right)
return Vec3((v.left * Quat([0, w[0], w[1], w[2]]) * v.right)[1:]) elif isinstance(w, Quat): assert False, 'TODO'
def __mul__(v, w): if isinstance(w, Transform): # v * w = vLeft * wLeft .. wRight * vRight return Transform(v.left * w.left, w.right * v.right) elif isinstance(w, Vec) and len(w) == 3: # TODO: check kind of Transform return Vec3(v.left * Quat([0, w[0], w[1], w[2]]) * v.right) else: raise TypeError, "unsupported op typ...
pass
return ( -v.right.conjugate() == v.left and v.right.N() == 1 )
def isRotInv(this): pass
class Rot(Transform): def __init__(this, v = None, axis = None, angle = None): Transform.__init__(this, v.conjugate(), v) class HalfTurn(Rot):
class Rot3(Transform3): def __init__(this, v = None, axis = Vec3([1, 0, 0]), angle = 0): """ Initialise a 3D rotation """ if v != None: v = v.N() Transform3.__init__(this, v, v.conjugate()) else: alpha = angle / 2 if axis != Vec3([0, 0, 0]): axis = axis.N() v = math.sin(alpha) * axis v = Quat([math.cos(alpha), v[0], v...
def isRotInv(this): pass