rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.data, self.objects = self.prepareContents(registry)
self.data, self.objects = self.prepareContents(registry, register_subdirs=changed)
def getContents(self, registry): if self.data is None: try: self.data, self.objects = self.prepareContents(registry) except: # DEBUG import traceback traceback.print_exc()
def prepareContents(self, registry):
def prepareContents(self, registry, register_subdirs=0):
def prepareContents(self, registry): # Creates objects for each file. fp = expandpath(self.filepath) data = {} objects = [] l = listdir(fp) types = self._readTypesFile() for entry in l: if not self._isAllowableFilename(entry): continue e_filepath = path.join(self.filepath, entry) e_fp = expandpath(e_filepath) if path.i...
""" Import roles / permission map from an XML file
""" Import action providers and their actions rom an XML file
def importActionProviders( context ): """ Import roles / permission map from an XML file o 'context' must implement IImportContext. o Register via Python: registry = site.portal_setup.getImportStepRegistry() registry.registerStep( 'importActionProviders' , '20040518-01' , Products.CMFSetup.actions.importActionProvi...
in_f = open(input_file)
in_f = open(input_file, 'rb')
def __init__(self, input_file): try: # Read the configuration file if win32: # Check the home dir first and then the program dir config_path = os.path.expanduser('~\\ZopeEdit.ini') global_config = os.path.join(sys.path[0] or '', 'ZopeEdit.ini') if not os.path.exists(config_path) \ and os.path.exists(global_config): con...
if self._verifyPermissions(action):
if self._verifyActionPermissions(action):
def _getDefaultView(self): ti = self.getTypeInfo() if ti is not None: actions = ti.getActions() for action in actions: if action.get('id', None) == 'view': if self._verifyActionPermissions(action): return self.restrictedTraverse(action['action']) # "view" action is not present or not allowed. # Find something that's al...
except "Unauthorized":
except Unauthorized:
def listFolderContents( self, spec=None, contentFilter=None ): # XXX """ Hook around 'contentValues' to let 'folder_contents' be protected. Duplicating skip_unauthorized behavior of dtml-in. """ items = self.contentValues(filter=contentFilter) l = [] for obj in items: id = obj.getId() v = obj try: if getSecurityManage...
def manage_editDocument(self, text_format, text, file='', REQUEST=None):
def manage_editDocument(self, text, text_format, file='', REQUEST=None):
def manage_editDocument(self, text_format, text, file='', REQUEST=None): """ A ZMI (Zope Management Interface) level editing method """ self.edit(text_format, text, file) if REQUEST is not None: REQUEST['RESPONSE'].redirect( self.absolute_url() + '/manage_edit' + '?manage_tabs_message=Document+updated' )
self.edit(text_format, text, file)
self.edit(text_format=text_format, text=text, file=file)
def manage_editDocument(self, text_format, text, file='', REQUEST=None): """ A ZMI (Zope Management Interface) level editing method """ self.edit(text_format, text, file) if REQUEST is not None: REQUEST['RESPONSE'].redirect( self.absolute_url() + '/manage_edit' + '?manage_tabs_message=Document+updated' )
if hasattr(obj, 'syndication_information'):
if hasattr(aq_base(obj), 'syndication_information'):
def enableSyndication(self, obj): """ Enable syndication for the obj """ if not self.isSiteSyndicationAllowed(): raise 'Syndication is Disabled' else: if hasattr(obj, 'syndication_information'): raise 'Syndication Information Exists' syInfo = SyndicationInformation() obj._setObject('syndication_information', syInfo) sy...
syInfo = getattr(obj, 'syndication_information',
syInfo = getattr(aq_base(obj), 'syndication_information',
def isSyndicationAllowed(self, obj=None): """ Check whether syndication is enabled for the site. This provides for extending the method to check for whether a particular obj is enabled, allowing for turning on only specific folders for syndication. """ #import pdb; pdb.set_trace() syInfo = getattr(obj, 'syndication_in...
candidates = [self.submitter_id]
candidates = [self.submitter_id] + self.assigned_to()
def _send_update_notice(self, action, actor, orig_status=None, additions=None, removals=None, file=None, fileid=None): """Send email notification about issue event to relevant parties."""
candidates.extend(self.aq_parent.supporters)
candidates.extend(self.aq_parent.managers) if not self.aq_parent.dispatching: candidates.extend(self.aq_parent.supporters)
def _send_update_notice(self, action, actor, orig_status=None, additions=None, removals=None, file=None, fileid=None): """Send email notification about issue event to relevant parties."""
from Products.CMFCore.FSPageTemplate import FSPageTemplate from os.path import join return FSPageTemplate( id, join( self.skin_path_name, filename ) )
return FSPageTemplate( id, path_join(self.skin_path_name, filename) )
def _makeOne( self, id, filename ):
from Products.PageTemplates.TALES import Undefined
def test_BadCall( self ):
self.assertEqual( script.pt_source_file() , 'file:%s/testPT.pt' % self.skin_path_name )
self.assertEqual( script.pt_source_file(), 'file:%s' % path_join(self.skin_path_name, 'testPT.pt') )
def test_pt_properties( self ):
from OFS.Folder import Folder
def setUp( self ):
return unittest.TestSuite(( unittest.makeSuite(FSPageTemplateTests), unittest.makeSuite(FSPageTemplateCustomizationTests),
return TestSuite(( makeSuite(FSPageTemplateTests), makeSuite(FSPageTemplateCustomizationTests),
def test_suite(): return unittest.TestSuite(( unittest.makeSuite(FSPageTemplateTests), unittest.makeSuite(FSPageTemplateCustomizationTests), ))
unittest.main(defaultTest='test_suite')
main(defaultTest='test_suite')
def test_suite(): return unittest.TestSuite(( unittest.makeSuite(FSPageTemplateTests), unittest.makeSuite(FSPageTemplateCustomizationTests), ))
if self._v_filesystem_objects is not None:
if ( self._v_filesystem_objects is not None and not getConfiguration().debug_mode ):
def _listFilesystemObjects( self ): """ Return a mapping of any filesystem objects we "hold". """ if self._v_filesystem_objects is not None: return self._v_filesystem_objects
start=(first_date, last_date), start_usage='range:min:max',
start=last_date, start_usage='range:max', end=first_date, end_usage='range:min',
def catalog_getevents(self, year, month): """ given a year and month return a list of days that have events """ first_date=DateTime(str(month)+'/1/'+str(year)) last_day=calendar.monthrange(year, month)[1] ## This line was cropping the last day of the month out of the ## calendar when doing the query
query+=self.portal_catalog(portal_type=self.calendar_types, review_state='published', end=(first_date, last_date), end_usage='range:min:max', sort_on='end')
def catalog_getevents(self, year, month): """ given a year and month return a list of days that have events """ first_date=DateTime(str(month)+'/1/'+str(year)) last_day=calendar.monthrange(year, month)[1] ## This line was cropping the last day of the month out of the ## calendar when doing the query
self, REQUEST, manage_tabs_message='Properties changed.')
self, REQUEST, management_view='Properties', manage_tabs_message='Properties changed.')
def manage_properties(self, default_skin='', request_varname='', allow_any=0, chosen=(), add_skin=0, del_skin=0, skinname='', skinpath='', cookie_persistence=0, REQUEST=None): ''' Changes portal_skin properties. ''' sels = self._getSelections() if add_skin: skinpath = str(skinpath) self.testSkinPath(skinpath) sels[str(...
security.declareProtected(ManageWorkspaces, 'manage_FTPstat')
def manage_FTPlist(self, REQUEST): """ FTP dir list """ # Things currently missing: recursion and globbing support # Hey, I said it was basic ;^) out = [] obs = [('..', self.aq_parent)] + self.listReferencedItems() for id, ob in obs: try: stat = marshal.loads(ob.manage_FTPstat(REQUEST)) except: pass # Skip broken objec...
return self._refs[key].dereference(self)
try: return self._refs[key].dereference(self) except KeyError: request = getattr(self, 'REQUEST', None) if request is not None: method=request.get('REQUEST_METHOD', 'GET') if (request.maybe_webdav_client and not method in ('GET', 'POST')): return webdav.NullResource.NullResource( self, key, request).__of__(self) raise ...
def __getitem__(self, key): """ Returns an object based on its unique workspace key """ # Return the referenced object wrapped in our context return self._refs[key].dereference(self)
resp.setCookie( self.request_varname, mskin, path='/' )
resp.setCookie( self.request_varname, mskin, path=portalPath )
def updateSkinCookie(self): ''' If needed, updates the skin cookie based on the member preference. ''' pm = getToolByName(self, 'portal_membership') member = pm.getAuthenticatedMember() if hasattr(aq_base(member), 'portal_skin'): mskin = member.portal_skin if mskin: req = self.REQUEST cookie = req.cookies.get(self.requ...
, path='/'
, path=portalPath
def updateSkinCookie(self): ''' If needed, updates the skin cookie based on the member preference. ''' pm = getToolByName(self, 'portal_membership') member = pm.getAuthenticatedMember() if hasattr(aq_base(member), 'portal_skin'): mskin = member.portal_skin if mskin: req = self.REQUEST cookie = req.cookies.get(self.requ...
def test_GetSize( self ): """ Test get_size returns correct value """
def testGetSize(self):
def test_GetSize( self ): """ Test get_size returns correct value """ script = FSPythonScript('test1', script_path) self.assertEqual(len(script.read()),script.get_size())
return Image(self.getId(), '', self.read())
return Image(self.getId(), '', self._readFile())
def _createZODBClone(self): return Image(self.getId(), '', self.read())
continuing_accepted = (lower(orig_status) in ['accepted',
continuing_accepted = (orig_status and lower(orig_status) in ['accepted',
def _send_update_notice(self, action, actor, orig_status=None, additions=None, removals=None, file=None, fileid=None, lower=string.lower): """Send email notification about issue event to relevant parties."""
security.declareProtected(View, 'searchMembers')
security.declareProtected(ListPortalMembers, 'searchMembers')
def listMembers(self): '''Gets the list of all members. ''' return map(self.wrapUser, self.__getPUS().getUsers())
self.assertEqual(ai.getActionExpression(), 'view')
self.assertEqual(ai.getActionExpression(), 'string:view')
def test_construction_with_Expressions(self): ai = ActionInformation(id='view' , title='View' , action=Expression( text='view') , condition=Expression( text='member') , category='global' , visible=0) self.assertEqual(ai.getId(), 'view') self.assertEqual(ai.Title(), 'View') self.assertEqual(ai.Description(), '') self.as...
return self.getOwner()[1]
return self.getOwner( info=1 )[1]
def Creator( self ): """ Return the ID of our owner. """ return self.getOwner()[1]
__FLOOR_DATE = DateTime( 1000, 0 )
__FLOOR_DATE = DateTime( 1970, 0 )
def content_type( self ): """ WebDAV needs this to do the Right Thing (TM). """ return self.Format()
try: dir_mtime = stat(self.skin_path_name)[8] except: dir_mtime = 0
def _writeFile(self, filename, stuff): # write some stuff to a file on disk # make sure the file's modification time has changed # also make sure the skin folder mod time ahs changed thePath = join(self.skin_path_name,filename) try: mtime1 = stat(thePath)[8] except: mtime1 = 0 mtime2 = mtime1 while mtime2==mtime1: f = ...
return Folder.manage_main(self, client, REQUEST, **kw)
m = Folder.manage_main.__of__(self) return m(self, client, REQUEST, **kw)
def manage_main(self, client=None, REQUEST=None, **kw): ''' ''' kw['management_view'] = 'Scripts' return Folder.manage_main(self, client, REQUEST, **kw)
folder._verifyObjectPaste(obj, validate_src=0) folder._setObject(id, obj)
if id in folder.objectIds(): obj = folder._getOb(id) if RESPONSE is not None: RESPONSE.redirect('%s/manage_main?manage_tabs_message=%s' % ( obj.absolute_url(), html_quote("An object with this id already exists") )) else: folder._verifyObjectPaste(obj, validate_src=0) folder._setObject(id, obj) if RESPONSE is not Non...
def manage_doCustomize(self, folder_path, RESPONSE=None): """Makes a ZODB Based clone with the same data.
if 'CMFCore' in CookieCrumbler.__module__:
if CookieCrumbler.__module__.find('CMFCore') >= 0:
def testCreateForms(self): # Verify the factory creates the login forms. if 'CMFCore' in CookieCrumbler.__module__: # This test is disabled in CMFCore. return self.root._delObject('cookie_authentication') manage_addCC(self.root, 'login', create_forms=1) ids = self.root.login.objectIds() ids.sort() self.assertEqual(tupl...
_bodyre = re.compile(r'<body.*?>', re.DOTALL|re.I)
_bodyre = re.compile(r'^\s*<html.*<body.*?>', re.DOTALL|re.I)
def unknown_endtag(self, tag): self.setliteral()
print self.absolute_url(), "is in a circular thread" break
raise RuntimeException, ( "%s is in a circular thread" % self.absolute_url() )
def parentsInThread(self, size=0): """ Return the list of object which are this object's parents, from the point of view of the threaded discussion. Parents are ordered oldest to newest.
self.REQUEST._hold(CleanupTemp(self))
if hasattr(self, 'REQUEST'): self.REQUEST._hold(CleanupTemp(self))
def wrapUser(self, u): ''' If possible, returns the Member object that corresponds to the given User object. ''' id = u.getId() members = self._members if not members.has_key(id): # Get a temporary member that might be # registered later via registerMemberData(). temps = self._v_temps if temps is not None and temps.has...
if not member.getProperties('email'):
if not member.getProperty('email'):
def mailPassword(self, forgotten_userid, REQUEST):
values = obj.synContentValues(obj)
values = obj.synContentValues()
def getSyndicatableContent(self, obj): """ An interface for allowing folderish items to implement an equivalent of PortalFolder.contentValues() """ if hasattr(obj, 'synContentValues'): values = obj.synContentValues(obj) else: values = PortalFolder.contentValues(obj) return values
Can also be called manually, allowing the user to change skins in the middle of a request.
Can NOT be called manually to change skins in the middle of a request! Use changeSkin for that.
def setupCurrentSkin(self, REQUEST=None): ''' Sets up _v_skindata so that __getattr__ can find it. Can also be called manually, allowing the user to change skins in the middle of a request. ''' if REQUEST is None: REQUEST = getattr(self, 'REQUEST', None) if REQUEST is None: # self is not fully wrapped at the moment. D...
return
def addMember(self, id, password, roles, domains, properties=None): '''Adds a new member to the user folder. Security checks will have already been performed. Called by portal_registration. ''' acl_users = self.acl_users if hasattr(acl_users, '_addUser'): acl_users._addUser(id, password, password, roles, domains) els...
except NoReindex, ex:
except ObjectDeleted, ex:
def __call__(self, instance, *args, **kw): ''' Invokes the method. ''' wf = getToolByName(instance, 'portal_workflow', None) if wf is None or not hasattr(wf, 'wrapWorkflowMethod'): # No workflow tool found. try: res = apply(self._m, (instance,) + args, kw) except NoReindex, ex: res = ex.getResult() else: catalog = getT...
return ti is None or ti.globalAllow() \ or contentType in self.allowed_content_types return contentType in self.allowed_content_types
if ti is None or ti.globalAllow(): return 1 if contentType in self.allowed_content_types: return 1 for t in self.listTypeInfo(): if t.getId() == contentType: return t.Type() in self.allowed_content_types return 0
def allowType( self, contentType ): """ Can objects of 'contentType' be added to containers whose type object we are? """ if not self.filter_content_types: ti = self.getTypeInfo( contentType ) return ti is None or ti.globalAllow() \ or contentType in self.allowed_content_types return contentType in self.allowed_content...
assert self.Tool.getDays() == ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
import locale old_locale = locale.getlocale(locale.LC_ALL)[0] locale.setlocale(locale.LC_ALL, 'C') try: self.assertEqual(self.Tool.getDays(), ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']) finally: locale.setlocale(locale.LC_ALL, old_locale)
def test_Days(self): assert self.Tool.getDays() == ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
def _entry_header(self, type, user, prefix="= ", suffix=""):
def _entry_header(self, type, user, date=None, prefix="= ", suffix=""):
def _entry_header(self, type, user, prefix="= ", suffix=""): """Return text for the header of a new transcript entry.""" # Ideally this would be a skin method (probly python script), but i # don't know how to call it from the product, sigh. t = string.capitalize(type) if self.action_number: lead = t + " - Entry #" + st...
(prefix, lead, str(user), DateTime().aCommon(), suffix))
(prefix, lead, str(user), date.aCommon(), suffix))
def _entry_header(self, type, user, prefix="= ", suffix=""): """Return text for the header of a new transcript entry.""" # Ideally this would be a skin method (probly python script), but i # don't know how to call it from the product, sigh. t = string.capitalize(type) if self.action_number: lead = t + " - Entry #" + st...
self.setModificationDate(DateTime(date))
self.setModificationDate(date)
def _setModificationDate(self, date): # Recent versions of CMF (1.3, maybe earlier) DefaultDublinCoreImpl # have .setModificationDate(), older use bobobase_modification_time, # which i don't know how to set, if can should be done - so trying to # set an initial collector issue mod time is a noop when using with # pre-1...
last_date=first_date + last_day
last_date = DateTime('%d/%d/%s 23:59:59' % (month, last_day , year))
def catalog_getevents(self, year, month): """ given a year and month return a list of days that have events """ year=int(year) month=int(month) first_date=DateTime(year, month, 1) last_day=calendar.monthrange(year, month)[1] ## This line was cropping the last day of the month out of the ## calendar when doing the query...
if descend_ok:
if descend_ok and hasattr(dst_folder, '_getOb'):
def _migrateObject(id, s_ob, dst_folder, conversions, skip, res): klass = s_ob.__class__ descend_ok = 1 pathname = pathOf(s_ob) base_ob = aq_base(s_ob) if skip.has_key(id): descend_ok = skip[id] if descend_ok and not hasattr(aq_base(dst_folder), id): descend_ok = 0 res.skipped.append(pathname + (descend_ok and ' (desce...
def unlock(self, object):
def unlock(self, object, message=''):
def unlock(self, object): '''Unlocks an object''' locker = self.locker(object) if not locker: raise LockingError, ("Unlocking an unlocked item: %s" % pathOf(object))
vt.checkin(object)
vt.checkin(object, message)
def unlock(self, object): '''Unlocks an object''' locker = self.locker(object) if not locker: raise LockingError, ("Unlocking an unlocked item: %s" % pathOf(object))
except AttributeError, TypeError:
except (AttributeError, TypeError):
def _guessMethodAliases(self): """ Guess and set Method Aliases. Used for upgrading old TIs. """ context = getActionContext(self) actions = self.listActions() ordered = [] _dict = {} viewmethod = ''
self._reorderPolicy( predicate_id, ndx - 1 )
self._reorderPolicy( policy_id, ndx - 1 )
def movePolicyUp( self, policy_id, REQUEST ): """ Move a caching policy up in the list. """ policy_ids = list( self._policy_ids ) ndx = policy_ids.index( policy_id ) if ndx == 0: msg = "Policy+already+first." else: self._reorderPolicy( predicate_id, ndx - 1 ) msg = "Policy+moved." REQUEST[ 'RESPONSE' ].redirect( self.a...
scale = (width, height * dvd_aspect / src_aspect)
scale = (width, height * target_aspect / src_aspect)
def preproc(self): """Do preprocessing common to all backends.""" self.infile = MediaFile(self.options['in']) width, height = get_resolution(self.options['format'], self.options['tvsys']) # Convert aspect (ratio) to a floating-point value src_aspect = ratio_to_float(self.options['aspect']) # Use anamorphic widescreen ...
scale = (width * src_aspect / dvd_aspect, height)
scale = (width * src_aspect / target_aspect, height)
def preproc(self): """Do preprocessing common to all backends.""" self.infile = MediaFile(self.options['in']) width, height = get_resolution(self.options['format'], self.options['tvsys']) # Convert aspect (ratio) to a floating-point value src_aspect = ratio_to_float(self.options['aspect']) # Use anamorphic widescreen ...
cmd += " -composite miff:- | display"
cmd += " miff:- | display"
def render(self): """Render the .mvg with ImageMagick, and display it.""" self.save(self.filename) cmd = "convert -size %sx%s " % self.size cmd += " xc:none " # Transparent (=none) canvas image cmd += " -draw @%s " % self.filename cmd += " -composite miff:- | display" print "Creating preview rendering." print cmd print...
print "Press 'q' or ESC in the image window to close the image."
def render(self): """Render the MVG image with ImageMagick, and display it.""" # TODO cmd = "convert -size %sx%s " % (self.width, self.height) cmd += " xc:none " cmd += " -draw '%s' " % ' '.join(self.data) cmd += " -composite miff:- | display" print "Running command:" print cmd print commands.getoutput(cmd)
self.insert('image %s,%s %s,%s "%s"' % \
self.insert('image %s %s,%s %s,%s "%s"' % \
def image(self, compose, (x, y), (width, height), filename): # compose may be e.g. Add, Clear, Copy, Difference, Over ... self.insert('image %s,%s %s,%s "%s"' % \ (compose, x, y, width, height, filename))
img.display() img.render(720, 480)
img.print_lines() img.render()
def push(self, context, *args, **kwargs): # context may be: clip-path, defs, gradient, graphic-context, pattern # TODO: Accept varying arguments depending on context, e.g. # push('graphic-context') # or push('pattern', id, radial, x, y, width,height) self.insert('push %s' % context)
self.txtOut.AppendText(stream.read())
try: self.txtOut.AppendText(unicode(stream.read()) except UnicodeDecodeError: pass
def OnProcessEnded(self, evt): """Print any remaining output, and destroy the process.""" # Get process exit status curExitStatus = evt.GetExitCode() # Print message to console if there was an error if curExitStatus != 0: print "ERROR:" print "The following command returned an exit status of %d:" % \ curExitStatus prin...
arglist.append(next.lstrip('[').rstrip(',]'))
if next not in "[,]": arglist.append(next)
def _parse(self, options): """Parse a string or list of options, returning a dictionary of those that match self.defdict.""" custom = {} # If options is a string, tokenize it before proceeding if options.__class__ == str: options = tokenize(options) while len(options) > 0: opt = options.pop(0).lstrip('-') if opt not in...
strAbout = "You are using the tovid GUI, version 0.24,\n" \
strAbout = "You are using the tovid GUI, version 0.27,\n" \
def OnAbout(self, evt): """Display a dialog showing information about tovidgui.""" strAbout = "You are using the tovid GUI, version 0.24,\n" \ "part of the tovid video disc authoring suite.\n\n" \ "For more information and documentation, please\n" \ "visit the tovid web site:\n\n" \ "http://tovid.org/" dlgAbout = wx.Me...
print "x,y scale: %s, %s" % (x_scale, y_scale)
def draw_on(self, drawing, frame): """Draw the scatterplot.""" assert isinstance(drawing, Drawing) width, height = self.size x_vals = self.xy_dict.keys() max_y = 0 for x in x_vals: largest = max(self.xy_dict[x]) if largest > max_y: max_y = largest x_scale = float(width) / max(x_vals) y_scale = float(height) / max_y pri...
IM_lines = [unicode(line) for line in IM_lines]
IM_lines = [unicode(line, cur_encoding) for line in IM_lines]
def ConfigAvailFonts(self): """Determine fonts that are available in both wx.Python and ImageMagick.""" # Find the shared fonts between ImageMagick and wx.Python ########################################################### # IM and wx store their available fonts differently, so we need a # dictionary that maps the wx na...
cmd += ' -gravity center -matte' cmd += self.bg_canvas
cmd += ' -gravity center -matte %s' % self.bg_canvas
def draw_background_canvas(self): """Draw background canvas. Corresp. to lines 400-411 of makemenu.""" # Generate default blue-black gradient background # TODO: Implement -background cmd = 'convert' cmd += ' -size %sx%s ' % self.options['expand'] cmd += ' gradient:blue-black' cmd += ' -gravity center -matte' cmd += sel...
>>> get_abitrate('dvd') (320, 1536)
def get_abitrate(format): """Return the range (min, max) of valid audio bitrates (in kilobits per second) for the given format, or a single value for constant-bitrate formats. For example: >>> get_abitrate('vcd') 224 >>> get_abitrate('dvd') (320, 1536) """ if format == 'vcd': return 224 elif format == 'svcd': return (...
return (320, 1536)
return (32, 1536)
def get_abitrate(format): """Return the range (min, max) of valid audio bitrates (in kilobits per second) for the given format, or a single value for constant-bitrate formats. For example: >>> get_abitrate('vcd') 224 >>> get_abitrate('dvd') (320, 1536) """ if format == 'vcd': return 224 elif format == 'svcd': return (...
drawing.scale(self.scalings[frame - self.start])
if frame < self.start: drawing.scale(self.scalings[0]) elif frame > self.end: drawing.scale(self.scalings[-1]) else: drawing.scale(self.scalings[frame - self.start])
def draw_on(self, drawing, frame): drawing.scale(self.scalings[frame - self.start])
self.frames = []
self.framefiles = []
def __init__(self, filename, (width, height)): Layer.__init__(self) self.filename = filename self.mediafile = MediaFile(filename) self.size = (width, height) # List of filenames of individual frames self.frames = [] self.rip_frames(1, 120)
self.frames.extend(self.mediafile.framefiles)
self.framefiles.extend(self.mediafile.framefiles)
def rip_frames(self, start, end): """Rip frames from the video file, from start to end frames.""" print "VideoClip: Ripping frames %s to %s" % (start, end) self.mediafile.rip_frames([start, end]) self.frames.extend(self.mediafile.framefiles)
if len(self.frames) == 0:
if len(self.framefiles) == 0:
def draw_on(self, drawing, frame): """Draw ripped video frames to the given drawing. For now, it's necessary to call rip_frames() before calling this function. Video is looped. """ assert isinstance(drawing, Drawing) if len(self.frames) == 0: print "VideoClip error: need to call rip_frames() before drawing." sys.exit(1...
if frame > len(self.frames): frame = frame % len(self.frames) filename = self.frames[frame]
if frame >= len(self.framefiles): frame = frame % len(self.framefiles) filename = self.framefiles[frame]
def draw_on(self, drawing, frame): """Draw ripped video frames to the given drawing. For now, it's necessary to call rip_frames() before calling this function. Video is looped. """ assert isinstance(drawing, Drawing) if len(self.frames) == 0: print "VideoClip error: need to call rip_frames() before drawing." sys.exit(1...
self.add_sublayer(Label(self.title), (0, 0))
self.add_sublayer(Label(self.title, fontsize=15), (0, 0))
def __init__(self, filename, (width, height), title=''): Layer.__init__(self) self.filename = filename self.size = (width, height) self.title = title or os.path.basename(filename) # Determine whether file is a video or image, and create the # appropriate sublayer filetype = get_file_type(filename) if filetype == 'video...
self.curOptions.alignment = ID_to_text('alignment', evt.GetInt())
self.curOptions.alignment = util.ID_to_text('alignment', evt.GetInt())
def OnAlignment(self, evt): """Set the text alignment according to the radiobox setting.""" self.curOptions.alignment = ID_to_text('alignment', evt.GetInt())
self.rbAlignment.SetSelection(text_to_ID(self.curOptions.alignment))
self.rbAlignment.SetSelection(util.text_to_ID(self.curOptions.alignment))
def SetOptions(self, menuOpts): """Set control values based on the provided MenuOptions.""" self.curOptions = menuOpts
self.curOptions.format = ID_to_text('format', evt.GetInt())
self.curOptions.format = util.ID_to_text('format', evt.GetInt())
def OnFormat(self, evt): # Convert integer value to text representation # (e.g., ID_FMT_DVD to 'dvd') self.curOptions.format = ID_to_text('format', evt.GetInt())
self.curOptions.aspect = ID_to_text('aspect', evt.GetInt())
self.curOptions.aspect = util.ID_to_text('aspect', evt.GetInt())
def OnAspect(self, evt): self.curOptions.aspect = ID_to_text('aspect', evt.GetInt())
self.rbResolution.SetSelection(text_to_ID(self.curOptions.format)) self.rbAspect.SetSelection(text_to_ID(self.curOptions.aspect))
self.rbResolution.SetSelection(util.text_to_ID(self.curOptions.format)) self.rbAspect.SetSelection(util.text_to_ID(self.curOptions.aspect))
def SetOptions(self, videoOpts): self.curOptions = videoOpts
makedvdOptions += "-author "
if curConfig.curDiscFormat == 'vcd' or \ curConfig.curDiscFormat == 'svcd': strAuthorCmd = "makevcd -device %s %s %s.xml" % \ (self.device, makedvdOptions, curConfig.strOutputXMLFile) else: strAuthorCmd = "makedvd -device %s %s %s.xml" % \ (self.device, makedvdOptions, curConfig.strOutputXMLFile) self.panCmdList.Enab...
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
makedvdOptions += "-burn " if curConfig.curDiscFormat == 'vcd' or \ curConfig.curDiscFormat == 'svcd': strAuthorCmd = "makevcd -device %s %s %s.xml" % \
if curConfig.curDiscFormat == 'vcd' or \ curConfig.curDiscFormat == 'svcd': strAuthorCmd = "makevcd -device %s %s %s" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
else: strAuthorCmd = "makedvd -device %s %s %s.xml" % \
else: strAuthorCmd = "makedvd -device %s %s %s" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
strAuthorCmd = "makevcd -device %s %s %s.xml" % \
strAuthorCmd = "makevcd -device %s %s \"%s.xml\"" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
strAuthorCmd = "makedvd -device %s %s %s.xml" % \
strAuthorCmd = "makedvd -device %s %s \"%s.xml\"" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
strAuthorCmd = "makevcd -device %s %s %s" % \
strAuthorCmd = "makevcd -device %s %s \"%s\"" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
strAuthorCmd = "makedvd -device %s %s %s" % \
strAuthorCmd = "makedvd -device %s %s \"%s\"" % \
def OnStart(self, evt): """Begin authoring and burning the disc.""" # Get global config (for XML filename and format) curConfig = TovidConfig()
if infile.video.spec['fps'] != options['fps']: log.info("Adjusting framerate") yuvcmd = 'yuvfps -r %s' % float_to_ratio(options['fps']) cmd = yuvcmd + ' | ' + cmd
if infile.video != None: if infile.video.spec['fps'] != options['fps']: log.info("Adjusting framerate") yuvcmd = 'yuvfps -r %s' % float_to_ratio(options['fps']) cmd = yuvcmd + ' | ' + cmd else: pass
def encode_video(infile, yuvfile, videofile, options): """Encode the yuv4mpeg stream to the given format and TV system.""" # TODO: Control over quality (bitrate/quantization) and disc split size, # corresp. to $VID_BITRATE, $MPEG2_QUALITY, $DISC_SIZE, etc. # Missing options (compared to tovid) # -S 700 -B 247 -b 2080 -...
IM_lines = [unicode(line, cur_encoding) for line in IM_lines]
IM_lines = [unicode(line, self.cur_encoding) for line in IM_lines]
def ConfigAvailFonts(self): """Determine fonts that are available in both wx.Python and ImageMagick.""" # Find the shared fonts between ImageMagick and wx.Python ########################################################### # IM and wx store their available fonts differently, so we need a # dictionary that maps the wx na...
self.level = self.INFO
self.level = self.DEBUG
def __init__(self, name): """Create a logger with the given name.""" self.name = name self.level = self.INFO
log.debug("Trying to SIGTERM pid: %s" % self.proc.pid)
def wait(self): """Wait for the command to finish running; handle keyboard interrupts. """ if not isinstance(self.proc, Popen): return try: self.proc.wait() except KeyboardInterrupt: log.debug("Trying to SIGTERM pid: %s" % self.proc.pid) os.kill(self.proc.pid, signal.SIGTERM) raise KeyboardInterrupt
"""Wait for the command to finish executing, and return a string
"""Wait for the command to finish running, and return a string
def get_output(self): """Wait for the command to finish executing, and return a string containing the command's output. If this command is piped into another, return that command's output instead. Returns an empty string if the command has not been run yet. """ if self.output is '' and self.proc is not None: self.outpu...
if self.output is '' and self.proc is not None:
if self.output is '' and isinstance(self.proc, Popen):
def get_output(self): """Wait for the command to finish executing, and return a string containing the command's output. If this command is piped into another, return that command's output instead. Returns an empty string if the command has not been run yet. """ if self.output is '' and self.proc is not None: self.outpu...
log.debug("Running: %s" % self)
def _run_redir(self, stdin=None, stdout=None): """Internal function; execute the command using the given stream redirections. stdin: File object to read input from (None for regular stdin) stdout: File object to write output to (None for regular stdout) """ log.debug("Running: %s" % self) self.output = '' self.proc =...
log.debug("Running: %s" % self)
def run(self, capture=False): """Run all Commands in the pipeline, doing appropriate stream redirection for piping. capture: False to show pipeline output on stdout, True to capture output for retrieval by get_output() """ log.debug("Running: %s" % self) self.output = '' prev_stdout = None # Run each command, pipi...
while next and next.lstrip('-') not in self.defdict:
while options and next.lstrip('-') not in self.defdict:
def _parse(self, options): """Parse a string or list of options, returning a dictionary of those that match self.defdict.""" custom = {} # If options is a string, tokenize it before proceeding if options.__class__ == str: options = tokenize(options) while len(options) > 0: opt = options.pop(0).lstrip('-') if opt not in...
self.filetype = get_type(filename)
self.filetype = get_file_type(filename)
def __init__(self, filename, (width, height)): Layer.__init__(self) self.filename = filename self.filetype = get_type(filename) self.size = (width, height)
for title in parentOpts.titles:
for titleIndex in range(len(parentOpts.titles)):
def OnTreeItemEdit(self, evt): """Update controls when a tree item's title is edited.""" if not evt.IsEditCancelled(): curItem = evt.GetItem() curOpts = self.discTree.GetPyData(curItem) curOpts.title = evt.GetLabel() # Assign outPrefix based on title curOpts.outPrefix = curOpts.title.replace(' ', '_')
if title == curText:
if parentOpts.titles[titleIndex] == curText:
def OnTreeItemEdit(self, evt): """Update controls when a tree item's title is edited.""" if not evt.IsEditCancelled(): curItem = evt.GetItem() curOpts = self.discTree.GetPyData(curItem) curOpts.title = evt.GetLabel() # Assign outPrefix based on title curOpts.outPrefix = curOpts.title.replace(' ', '_')