rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
Video(id=intid, db=mythvideo).update({'filename': tmp_filename, 'host': host})
Video(intid, db=mythvideo).update({'filename': tmp_filename, 'host': host})
def _moveVideoFiles(self, target_destination_array): """Copy files or directories to a destination directory. If the -F filename option is set then rename TV series during the move process. The move will be interactive for identifying a movie's IMDB number or TV series if the -i option was also set. If there is a probl...
meta_dict = Video(id=intid, db=mythvideo)
meta_dict = Video(intid, db=mythvideo)
def _findMissingInetref(self): '''Find any video file without a Mythdb record or without an inetref number return None if there are no new video files return a array of dictionary information on each video file that qualifies for processing ''' directories=self.config['mythvideo']
Video(id=vidintid, db=mythvideo).update(repair)
Video(vidintid, db=mythvideo).update(repair)
def _checkValidGraphicFile(self, filename, graphicstype=u'', vidintid=False): '''Verify that a graphics file is not really an HTML file return True if it is a graphics file return False if it is an HTML file ''' # Verify that the graphics file is NOT HTML instead of the intended graphics file try: p = subprocess.Popen(...
vidrec = Video(id=intid, db=mythvideo)
vidrec = Video(intid, db=mythvideo)
def _getMiroVideometadataRecords(self): """Fetches all videometadata records with an inetref of '99999999' and a category of 'Miro'. If the videometadata record has a host them it must match the lower-case of the locahostname. aborts if processing failed return and array of matching videometadata dictionary records """...
Video(id=intid, db=mythvideo).update(changed_fields)
Video(intid, db=mythvideo).update(changed_fields)
def updateMiroVideo(self, program): '''Update the information in a Miro/MythVideo record return nothing ''' global localhostname, graphicsDirectories
Video(id=intid, db=mythvideo).update({'filename': filename, u'host': u''})
Video(intid, db=mythvideo).update({'filename': filename, u'host': u''})
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
Video(id=intid, db=mythvideo).update({'filename': filename, u'host': localhostname.lower()})
Video(intid, db=mythvideo).update({'filename': filename, u'host': localhostname.lower()})
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
vim = Video(id=intid, db=mythvideo)
vim = Video(intid, db=mythvideo)
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
Video(id=intid, db=mythvideo).update({'inetref': inetref})
Video(intid, db=mythvideo).update({'inetref': inetref})
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
Video(id=intid, db=mythvideo).update({'inetref': inetref, 'title': tmp_dict['title']})
Video(intid, db=mythvideo).update({'inetref': inetref, 'title': tmp_dict['title']})
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
Video(id=intid, db=mythvideo).update(available_metadata)
Video(intid, db=mythvideo).update(available_metadata)
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
self._addCastGenreCountry( genres_cast[key], Video(id=intid, db=mythvideo), key)
self._addCastGenreCountry( genres_cast[key], Video(intid, db=mythvideo), key)
def processMythTvMetaData(self): '''Check each video file in the mythvideo directories download graphics files and meta data then update MythTV data base meta data with any new information. ''' # Verify that the proper fields are present db_version = mythdb.settings.NULL.DBSchemaVer field_names = mythvideo.tablefields[...
tmp = str(self[data]).replace('/','-')
tmp = unicode(self[data]).replace('/','-')
def formatPath(self, path, replace=None): """ Recorded.formatPath(path, replace=None) -> formatted path string 'path' string is formatted as per mythrename.pl """ for (tag, data) in (('T','title'), ('S','subtitle'), ('R','description'), ('C','category'), ('U','recgroup'), ('hn','hostname'), ('c','chanid') ): tmp = str(...
"""Takes an element tree Element ('categories') and create a string of comma seperated film
"""Takes an element tree Element ('categories') and create a string of comma separated film
def getCategories(self, categories_et): """Takes an element tree Element ('categories') and create a string of comma seperated film categories return comma seperated sting of film category names
return comma seperated sting of film category names
return comma separated string of film category names
def getCategories(self, categories_et): """Takes an element tree Element ('categories') and create a string of comma seperated film categories return comma seperated sting of film category names
"""Takes an element tree Element ('studios') and create a string of comma seperated film
"""Takes an element tree Element ('studios') and create a string of comma separated film
def getStudios(self, studios_et): """Takes an element tree Element ('studios') and create a string of comma seperated film studios names return comma seperated sting of film studios names
return comma seperated sting of film studios names
return comma separated string of film studios names
def getStudios(self, studios_et): """Takes an element tree Element ('studios') and create a string of comma seperated film studios names return comma seperated sting of film studios names
"""Takes an element tree Element ('countries') and create a string of comma seperated film
"""Takes an element tree Element ('countries') and create a string of comma separated film
def getProductionCountries(self, countries_et): """Takes an element tree Element ('countries') and create a string of comma seperated film countries return comma seperated sting of countries associated with the film
return comma seperated sting of countries associated with the film
return comma separated string of countries associated with the film
def getProductionCountries(self, countries_et): """Takes an element tree Element ('countries') and create a string of comma seperated film countries return comma seperated sting of countries associated with the film
TMDB_movies.append({'name': "%s (%s)" % (movie['alternative_name'], movie['released'][:4]), u'sid': movie[u'imdb']})
TMDB_movies.append({'name': "%s (%s)" % (movie['alternative_name'], movie['released'][:4]), u'sid': movie[u'id']})
def _getTmdbIMDB(self, title, watched=False, IMDB=False, rtnyear=False): '''Find and exact match of the movie name with what's on themoviedb.com If IMDB is True return an imdb# If rtnyear is True return IMDB# and the movie year in a dictionary return False (no matching movie found) return imdb# and/or tmdb# ''' global ...
if movie.has_key('year'): temp = {imdb_access.get_imdbID(movie): u"%s (%s)" % (movie['title'], movie['year'])} else: temp = {imdb_access.get_imdbID(movie): movie['title']}
try: if movie.has_key('year'): temp = {imdb_access.get_imdbID(movie): u"%s (%s)" % (movie['title'], movie['year'])} else: temp = {imdb_access.get_imdbID(movie): movie['title']} except Exception: return False
def _getTmdbIMDB(self, title, watched=False, IMDB=False, rtnyear=False): '''Find and exact match of the movie name with what's on themoviedb.com If IMDB is True return an imdb# If rtnyear is True return IMDB# and the movie year in a dictionary return False (no matching movie found) return imdb# and/or tmdb# ''' global ...
if filel.endswith('mirobridge_coverart.jpg'): continue if filel.endswith('mirobridge_banner.jpg'): continue if filel.endswith('mirobridge_fanart.jpg'): continue
def _graphicsCleanup(self): '''Match the graphics in the mythtv graphics directories with the ones specified by the mythvideometa records. Remove any graphics that are not referenced at least once. Print a report. ''' global localhostname num_total = 0 num_deleted = 1 num_new_total = 2 stats = {'coverfile': [0,0,0], 'b...
airdate = date(*[int(a) for a in self.airdate.split('-')])
def formatPath(self, path, replace=None): """ Program.formatPath(path, replace=None) -> formatted path string 'path' string is formatted as per mythrename.pl syntax """ for (tag, data) in (('T','title'), ('S','subtitle'), ('R','description'), ('C','category'), ('U','recgroup'), ('hn','hostname'), ('c','chanid') ): tmp ...
path = path.replace('%o'+tag, airdate.strftime(format))
path = path.replace('%o'+tag, self.airdate.strftime(format))
def formatPath(self, path, replace=None): """ Program.formatPath(path, replace=None) -> formatted path string 'path' string is formatted as per mythrename.pl syntax """ for (tag, data) in (('T','title'), ('S','subtitle'), ('R','description'), ('C','category'), ('U','recgroup'), ('hn','hostname'), ('c','chanid') ): tmp ...
self[data].strftime.mythformat())
self[data].mythformat())
def formatJob(self, cmd): """ Program.formatPath(cmd) -> formatted command string 'cmd' string is formatted as per MythJobQueue syntax """ for tag in ('chanid','title','subtitle','description','hostname', 'category','recgroup','playgroup','parentid','findid', 'recstatus','rectype'): cmd = cmd.replace('%%%s%%' % tag.upp...
MythDB.searchOldRecorded.dbclass = delOldRecorded
MythDB.searchOldRecorded.handler = delOldRecorded
def delete(self): """ Delete video entry from database. """ DBDataWrite.delete(self)
c.execute("""UPDATE settings SET data=%s WHERE value=%s AND hostname=%s""", (value, key, self._host))
query = """UPDATE settings SET data=%s WHERE value=%s AND""" dat = [value, key] if self._host == 'NULL': query += ' hostname IS NULL' else: query += ' hostname=%s' dat.append(self._host) c.execute(query, dat)
def __setitem__(self, key, value): if key not in self._db.settings[self._host]: self.__getitem__(key) c = self._db.cursor(self._log) if key not in self._db.settings[self._host]: c.execute("""INSERT INTO settings (value,data,hostname) (%s,%s,%s)""", (key, value, self._host)) else: c.execute("""UPDATE settings SET data=%...
Video(id=record[u'intid'], db=mythvideo).delete()
Video(record[u'intid'], db=mythvideo).delete()
def updateMythVideo(items): '''Add and delete MythVideo records for played Miro Videos. Add and delete symbolic links to Miro Videos, to coverart/Miro icons, banners and Miro screenshots and fanart. NOTE: banner and fanart graphics were provided with the script and are used only if present. Abort if processing failed r...
command += " -dvd-video -V " + quoteFilename(title) + " "
command += " -dvd-video -V '" + title.replace("'", "'\\''") + "' "
def BurnDVDISO(title): write( "Burning ISO image to %s" % dvddrivepath) checkCancelFlag() finished = False tries = 0 while not finished and tries < 10: f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK) drivestatus = ioctl(f,CDROM.CDROM_DRIVE_STATUS, 0) os.close(f); if drivestatus == CDROM.CDS_DISC_OK or drivesta...
command += " -Z " + dvddrivepath + " -dvd-video -V " + quoteFilename(title) + " "
command += " -Z " + dvddrivepath + " -dvd-video -V '" + title.replace("'", "'\\''") + "' "
def BurnDVDISO(title): write( "Burning ISO image to %s" % dvddrivepath) checkCancelFlag() finished = False tries = 0 while not finished and tries < 10: f = os.open(dvddrivepath, os.O_RDONLY | os.O_NONBLOCK) drivestatus = ioctl(f,CDROM.CDROM_DRIVE_STATUS, 0) os.close(f); if drivestatus == CDROM.CDS_DISC_OK or drivesta...
'Movies_Action_adventure': 'directories/film_genres/action_adventure', 'Movies_Drama': 'directories/film_genres/drama', 'Movies_Sci_fi_fantasy': 'directories/film_genres/scifi', 'Movies_Thriller': 'directories/film_genres/thriller', 'Movies_Comedy': 'directories/film_genres/comedy', 'Movies_Classics': 'directories/film...
'Movies_Action_adventure': 'directories/film_genres/action_adventure', 'Movies_Drama': 'directories/film_genres/drama', 'Movies_Sci_fi_fantasy': 'directories/film_genres/scifi', 'Movies_Thriller': 'directories/film_genres/thriller', 'Movies_Comedy': 'directories/film_genres/comedy', 'Movies_Classics': 'directories/film...
def __init__(self, apikey, mythtv = True, interactive = False, select_first = False, debug = False, custom_ui = None, language = None, search_all_languages = False, ): """apikey (str/unicode): Specify the target site API key. Applications need their own key in some cases
except: sys.stderr.write(u"! Error: Unknown error during a Movie (%s) information lookup\n" % tmdb_id)
except Exception, e: sys.stderr.write(u"! Error: Unknown error during a Movie (%s) information lookup\nError(%s)\n" % (tmdb_id, e))
def movieData(tmdb_id): '''Get Movie data by IMDB or TMDB number and return the details ''' try: return displayMovieData(self.searchTMDB(tmdb_id)) except TmdbMovieOrPersonNotFound, msg: sys.stderr.write(u"%s\n" % msg) return None except TmdHttpError, msg: sys.stderr.write(self.error_messages['TmdHttpError'] % msg) sys....
except: sys.stderr.write(u"! Error: Unknown error during a Movie Trailer search (%s)\n" % title)
except Exception, e: sys.stderr.write(u"! Error: Unknown error during a Movie Trailer search (%s)\nError(%s)\n" % (title, e))
def movieData(tmdb_id): '''Get Movie data by IMDB or TMDB number and return the details ''' try: return displayMovieData(self.searchTMDB(tmdb_id)) except TmdbMovieOrPersonNotFound, msg: sys.stderr.write(u"%s\n" % msg) return None except TmdHttpError, msg: sys.stderr.write(self.error_messages['TmdHttpError'] % msg) sys....
pass
dirname = record.dirname
def getStorageGroups(): '''Populate the storage group dictionary with the host's storage groups. return False if there is an error ''' records = mythdb.getStorageGroup(hostname=localhostname) if records: for record in records: if record.groupname in storagegroupnames.keys(): try: dirname = unicode(record.dirname, 'utf8...
try: dbconn = self._processPage(ip, port, pin)
xml = MythXMLConn(backend=ip, port=port) dbconn = xml.getConnectionInfo(pin) if self._check_dbconn(dbconn):
def _listenUPNP(self, pin, timeout): # open outbound socket
except: continue
def _listenUPNP(self, pin, timeout): # open outbound socket
return dbconn def _processPage(self, ip, port, pin): dbconn = {'SecurityPin':pin} up = urlopen('http://%s:%s/Myth/GetConnectionInfo?Pin=%s' \ % (ip, port, pin)) config = etree.fromstring(up.read()) up.close() conv = {'Host':'DBHostName', 'Port':'DBPort', 'UserName':'DBUserName','Password':'DBPassword', 'Name':'D...
def _listenUPNP(self, pin, timeout): # open outbound socket
def __init__(self, backend=None, db=None):
def __init__(self, backend=None, db=None, port=None): if backend and port: self.host, self.port = backend, int(port) return
def __init__(self, backend=None, db=None): db = MythDBBase(db) self.log = MythLog('Python XML Connection', db=db) if backend is None: # use master backend backend = db.settings.NULL.MasterServerIP if re.match('(?:\d{1,3}\.){3}\d{1,3}',backend): # process ip address c = db.cursor(self.log) if c.execute("""SELECT hostnam...
AND data=%s""", self.host) == 0:
AND data=%s""", backend) == 0:
def __init__(self, backend=None, db=None): db = MythDBBase(db) self.log = MythLog('Python XML Connection', db=db) if backend is None: # use master backend backend = db.settings.NULL.MasterServerIP if re.match('(?:\d{1,3}\.){3}\d{1,3}',backend): # process ip address c = db.cursor(self.log) if c.execute("""SELECT hostnam...
self.port = self.db.settings[self.host].BackendStatusPort
self.port = int(db.settings[self.host].BackendStatusPort)
def __init__(self, backend=None, db=None): db = MythDBBase(db) self.log = MythLog('Python XML Connection', db=db) if backend is None: # use master backend backend = db.settings.NULL.MasterServerIP if re.match('(?:\d{1,3}\.){3}\d{1,3}',backend): # process ip address c = db.cursor(self.log) if c.execute("""SELECT hostnam...
self.port = db.settings[self.host].BackendStatusPort
self.port = int(db.settings[self.host].BackendStatusPort)
def __init__(self, backend=None, db=None): db = MythDBBase(db) self.log = MythLog('Python XML Connection', db=db) if backend is None: # use master backend backend = db.settings.NULL.MasterServerIP if re.match('(?:\d{1,3}\.){3}\d{1,3}',backend): # process ip address c = db.cursor(self.log) if c.execute("""SELECT hostnam...
self.port = db.setting[self.host].BackendStatusPort
self.port = int(db.setting[self.host].BackendStatusPort)
def __init__(self, backend=None, db=None): db = MythDBBase(db) self.log = MythLog('Python XML Connection', db=db) if backend is None: # use master backend backend = db.settings.NULL.MasterServerIP if re.match('(?:\d{1,3}\.){3}\d{1,3}',backend): # process ip address c = db.cursor(self.log) if c.execute("""SELECT hostnam...
print 'opening %s' % url
def _query(self, path=None, **keyvars): """ obj._query(path=None, **keyvars) -> xml string
return etree.fromstring(self._query(path, **keyvars)).getroot()
xmlstr = self._query(path, **keyvars) if xmlstr.find('xmlns') >= 0: ind1 = xmlstr.find('xmlns') ind2 = xmlstr.find('"', ind1+7) + 1 xmlstr = xmlstr[:ind1] + xmlstr[ind2:] return etree.fromstring(xmlstr) def getConnectionInfo(self, pin=0): """Return dbconn dict from backend connection info.""" dbconn = {'SecurityPin':p...
def _queryTree(self, path=None, **keyvars): """obj._queryTree(path=None, **keyvars) -> xml element tree""" return etree.fromstring(self._query(path, **keyvars)).getroot()
if val.type == 'datetime':
if (val.type == 'datetime') and (data[key] is not None):
def _process(self, data): data = DictData._process(self, data) for key, val in self._db.tablefields[self._table].items(): if val.type == 'datetime': data[key] = datetime.duck(data[key]) return data
try: if IMDB: results = self.config['tmdb_api'].searchTMDB(IMDB) else: results = self.config['tmdb_api'].searchTitle(tmp_title) except TmdbMovieOrPersonNotFound, e: results = [[]] except Exception, errormsg: self._displayMessage(u"themoviedb.com error for Movie(%s) invalid data error (%s)" % (title, errormsg)) return F...
user_tmdb = False while True: try: if IMDB: results = self.config['tmdb_api'].searchIMDB(IMDB) elif user_tmdb: results = self.config['tmdb_api'].searchTMDB(user_tmdb) if rtnyear: if results.has_key('releasedate'): return {'name': "%s (%s)" % (results['title'], results['releasedate'][:4]), u'sid': results[u'inetref']} ...
def _getTmdbIMDB(self, title, watched=False, IMDB=False, rtnyear=False): '''Find and exact match of the movie name with what's on themoviedb.com If IMDB is True return an imdb# If rtnyear is True return IMDB# and the movie year in a dictionary return False (no matching movie found) return imdb# and/or tmdb# ''' global ...
if len(results[0]) and self.config['interactive']: if results[0]['id'] == '99999999': return results[0]['id']
def _getTmdbIMDB(self, title, watched=False, IMDB=False, rtnyear=False): '''Find and exact match of the movie name with what's on themoviedb.com If IMDB is True return an imdb# If rtnyear is True return IMDB# and the movie year in a dictionary return False (no matching movie found) return imdb# and/or tmdb# ''' global ...
raise ValueError print match.groups()
raise ValueError("time data '%s' does not match ISO 8601 format" \ % isotime)
def fromIso(cls, isotime, sep='T'): match = cls._reiso.match(isotime) if match is None: raise ValueError
return cls.strptime(rfctime, '%a, %d %b %Y %H:%M:%S %Z')
return cls.strptime(rfctime, '%a, %d %b %Y %H:%M:%S %Z').strip()
def fromRfc(cls, rfctime): return cls.strptime(rfctime, '%a, %d %b %Y %H:%M:%S %Z')
try: return cls.fromtimestamp(t) except: pass try: return cls.frommythtime(t) except: pass try: return cls.fromIso(t) except: pass try: return cls.fromRfc(t) except: raise ValueError("time data '%s' does not match" % t +\ "supported formats")
for func in [cls.fromtimestamp, cls.frommythtime, cls.fromIso, cls.fromRfc]: try: return func(t) except: pass raise ValueError("time data '%s' does not match supported formats"%t)
def duck(cls, t): try: # existing modified datetime t.mythformat return t except: pass try: # existing built-in datetime return cls.fromIso(t.isoformat()) except: pass try: # epoch time return cls.fromtimestamp(t) except: pass try: # myth time (iso time with integer characters only) return cls.frommythtime(t) except: p...
userrating, length, coverfile
userrating, length, coverfile, subtitle
def getFileInformation(file, folder): outputfile = os.path.join(folder, "info.xml") impl = xml.dom.minidom.getDOMImplementation() infoDOM = impl.createDocument(None, "fileinfo", None) top_element = infoDOM.documentElement # if the jobfile has amended file details use them details = file.getElementsByTagName("details")...
node.appendChild(infoDOM.createTextNode(unicode(record[9], "UTF-8")))
def getFileInformation(file, folder): outputfile = os.path.join(folder, "info.xml") impl = xml.dom.minidom.getDOMImplementation() infoDOM = impl.createDocument(None, "fileinfo", None) top_element = infoDOM.documentElement # if the jobfile has amended file details use them details = file.getElementsByTagName("details")...
def _build_tf(p, translation_only=False):
def _build_tf(p, translation_only=False, fixed_scale=False):
def _build_tf(p, translation_only=False): if np.sum(np.isnan(p) + np.isinf(p)) != 0: H = np.eye(3) else: theta,a,b,tx,ty = p C = np.cos(theta) S = np.sin(theta) H = np.array([[a*C, -b*S, tx], [a*S, b*C, ty], [0, 0, 1.]]) if translation_only: H[:2, :2] = np.eye(2) return H
M = _build_tf(p, translation_only=translation_only) T = transform.homography(B, M, order=2)
M = _build_tf(p, translation_only=translation_only, fixed_scale=fixed_scale) try: T = transform.homography(B, M, order=2) except np.linalg.LinAlgError: raise RuntimeError('Could not invert transformation matrix. ' 'This may be because too many levels of ' 'downscaling was requested (%d).' % levels)
def cost(p, A, B): M = _build_tf(p, translation_only=translation_only) T = transform.homography(B, M, order=2) H = joint_hist(A, T, win_size=win_size, std=std, fast=fast) S = mutual_info(H) return -S
standard_form=True):
standard_form=False):
def solve(images, tf_matrices, scale, x0=None, tol=1e-10, iter_lim=None, damp=1e-1, method='CG', operator='bilinear', norm=1, standard_form=True): """Super-resolve a set of low-resolution images by solving a large, sparse set of linear equations. This method approximates the camera with a downsampling operator, using ...
def A(x, m, n): return op * x def AT(x, m, n): return op.T * x
def A(x, m, n): return op * x
lsqr(A, AT, np.prod(oshape), b, atol=atol, btol=btol,
lsqr(op, b, atol=atol, btol=btol,
def sr_gradient(x, norm=norm): # Careful! Mixture of sparse and dense operators. #Axb = op * x - b #nrm_sq = np.dot(Axb, Axb) # Dense #Axbop = (op.T * Axb).T # Sparse #return nrm_sq * Axbop Axb = op * x - b L = len(x) if norm == 1: xmx0 = x - x0.flat term1 = np.linalg.norm(Axb, 1) * np.sign(Axb.T) * op term2 = damp * n...
tmp[..., :3] = s
print tmp.shape, s.shape tmp[..., :3] = s[..., :3]
def with_transform(images, matrices, weights=None, order=1, oshape=None, save_tiff=False, method='interpolate'): """Stack images after performing coordinate transformations. Parameters ---------- images : list of ndarray Images to be stacked. matrices : list of (3,3) ndarray Coordinate transformation matrices. weights...
max_iter=None, T=None, LO_RANSAC=None):
max_iter=None, T=None, LO_RANSAC=None, min_iter=100):
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
T is set to `confidence`.
T is set to 1. Note that `T` must be large enough to *increment* the error when a point moves from being an inlier to an outlier, otherwise outliers are preferred by RANSAC.
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
T = confidence
T = 1
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
100)
min_iter)
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
ip = np.sum(inliers) / float(L) new_max = np.log(0.01) / np.log(1 - ip**model.ndp) if new_max < max_iter and new_max > 100: max_iter = new_max inliers_found = np.sum(inliers)
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
best_set, best_err = self(data, confidence, max_iter=10, T=T, LO_RANSAC=inliers) elif LO_RANSAC is not None: return best_set, best_err
new_best_set, new_best_err = self(data, confidence, max_iter=10, T=T, LO_RANSAC=inliers) if new_best_err < best_err: best_err = new_best_err best_set = new_best_set ip = np.sum(best_set) / float(L) new_max = np.log(0.1) / np.log(1 - ip**model.ndp) if new_max < max_iter and new_max > min_iter: max_iter = new_max log.d...
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
np.savetxt('/tmp/ransac.txt', data[best_set,...])
def __call__(self, data=None, inliers_required=None, confidence=None, max_iter=None, T=None, LO_RANSAC=None): """Execute RANSAC.
:math:`mathbf{b}` is a stacked vector of all the low-resolution
:math:`\mathbf{b}` is a stacked vector of all the low-resolution
def solve(images, tf_matrices, scale, x0=None, tol=1e-10, iter_lim=None, damp=1e-1, method='CG', operator='bilinear'): """Super-resolve a set of low-resolution images by solving a large, sparse set of linear equations. This method approximates the camera with a downsampling operator, using bilinear interpolation. The...
def get_end_balance(self, cursor, user, ids, name, arg, context=None):
def get_end_balance(self, cursor, user, ids, name, context=None):
def get_end_balance(self, cursor, user, ids, name, arg, context=None): statements = self.browse(cursor, user, ids, context=context) res = {} for statement in statements: res[statement.id] = statement.start_balance for line in statement.lines: res[statement.id] += line.amount return res
self.assertRaises(Exception, test_view('account_statement'))
test_view('account_statement')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('account_statement'))
def __init__(self, local, remote, cache_prefix=QUEDED_REMOTE_STORAGE_CACHE_KEY_PREFIX):
def __init__(self, local, remote, cache_prefix=QUEUED_REMOTE_STORAGE_CACHE_KEY_PREFIX):
def __init__(self, local, remote, cache_prefix=QUEDED_REMOTE_STORAGE_CACHE_KEY_PREFIX): self.local_class = local self.local = get_storage_class(self.local_class)() self.remote_class = remote self.remote = get_storage_class(self.remote_class)() self.cache_prefix = cache_prefix
def open(self, name, **kwargs): return self.local.open(name, **kwargs)
def open(self, name, *args, **kwargs): return self.get_storage(name).open(name, *args, **kwargs)
def open(self, name, **kwargs): return self.local.open(name, **kwargs)
wi = ones([self.nelems()],dtype=Int) wi[unselected] = 0
wi=range(self.nelems()) wi = delete(wi, selected)
def unselect(self, selected): """Return a mesh without the selected elements.
dist[okE[closer]] = distF[closer]
dist[okF[closer]] = distF[closer]
def distanceOfPoints(self,X,return_points=False): """Find the distances of points X to the TriSurface. The distance of a point is either: - the closest perpendicular distance to the facets; - the closest perpendicular distance to the edges; - the closest distance to the vertices. X is a (nX,3) shaped array of points....
points[okE[closer]] = res[2][closer]
points[okF[closer]] = res[2][closer]
def distanceOfPoints(self,X,return_points=False): """Find the distances of points X to the TriSurface. The distance of a point is either: - the closest perpendicular distance to the facets; - the closest perpendicular distance to the edges; - the closest distance to the vertices. X is a (nX,3) shaped array of points....
pf.canvas.setPerspective(state)
pf.canvas.camera.setPerspective(state)
def perspective(state=True): pf.canvas.setPerspective(state) pf.canvas.update() toolbar.updatePerspectiveButton() pf.GUI.processEvents()
self.coeffs = self.compute_coefficients()
self.compute_coefficients()
def __init__(self,coords,endcond=['notaknot','notaknot'],closed=False): """Create a natural spline through the given points.
a = toolbar.addAction(iconset,text,func)
a = toolbar.addAction(iconset,tooltip,func)
def addButton(toolbar,tooltip,icon,func,repeat=False,toggle=False,checked=False,icon0=None): """Add a button to a toolbar. - `toolbar`: the toolbar where the button will be added - `tooltip`: the text to appears as tooltip - `icon`: name of the icon to be displayed on the button, - `func`: function to be called when ...
writeElems(fil,mesh.elems,mesh.eltype,nofs=1)
writeElems(fil,mesh.elems,eltype,nofs=1)
def exportMesh(filename,mesh,eltype=None,header=''): """Export a finite element mesh in Abaqus .inp format. This is a convenience function to quickly export a mesh to Abaqus without having to go through the whole setup of a complete finite element model. This just writes the nodes and elements specified in the mesh to...
mesh = S.toMesh() fe_abq.exportMesh(fn,mesh,eltype='S3',header="Abaqus model generated by pyFormex from input file %s" % os.path.basename(fn))
fe_abq.exportMesh(fn,S,eltype='S3',header="Abaqus model generated by pyFormex from input file %s" % os.path.basename(fn))
def export_surface(): S = selection.check(single=True) if S: types = [ "Abaqus INP files (*.inp)" ] fn = askNewFilename(GD.cfg['workdir'],types) if fn: print("Exporting surface model to %s" % fn) updateGUI() mesh = S.toMesh() fe_abq.exportMesh(fn,mesh,eltype='S3',header="Abaqus model generated by pyFormex from input fi...
dialog.acceptData() globals().update(dialog.results) if Explain: explain() dialog.hide() method[Illusion]() dialog.show()
if dialog: dialog.acceptData() globals().update(dialog.results) if Explain: explain() dialog.hide() method[Illusion]() dialog.show()
def show(): """Show the illusion""" dialog.acceptData() globals().update(dialog.results) if Explain: explain() dialog.hide() method[Illusion]() dialog.show()
print ill,method._order
def next(): """Show the next illusion""" dialog.acceptData() ill = dialog.results['Illusion'] print ill,method._order i = (method._order.index(ill) + 1) % len(method._order) print method._order[i] dialog.updateData({'Illusion':method._order[i]}) show()
print method._order[i]
def next(): """Show the next illusion""" dialog.acceptData() ill = dialog.results['Illusion'] print ill,method._order i = (method._order.index(ill) + 1) % len(method._order) print method._order[i] dialog.updateData({'Illusion':method._order[i]}) show()
Illusion = None Explain = False print Illusion,Explain
pass
def openDialog(): """Create and display the dialog""" global dialog,explanation data_items = [ I('Illusion',Illusion,choices=method.keys()), I('Explain',Explain,text='Show explanation'), ] dialog = widgets.NewInputDialog( data_items, caption='Optical illusions', actions = [('Done',close), ('Next',next), ('Explain',exp...
self.setProp(prop)
self.setProp(kargs['prop'])
def __init__(self,*args,**kargs): """Create a new surface.""" Mesh.__init__(self) self.edges = self.faces = None self.areas = self.normals = None self.econn = self.conn = self.eadj = self.adj = None if hasattr(self,'edglen'): del self.edglen if len(args) == 0: return # an empty surface if len(args) == 1: # argument ...
family = GD.cfg.get('gui/fontfamily',None) size = GD.cfg.get('gui/fontsize',None)
family = GD.cfg['gui/fontfamily'] size = GD.cfg['gui/fontsize']
def setAppearence(self): style = GD.cfg['gui/style'] font = GD.cfg['gui/font'] family = GD.cfg.get('gui/fontfamily',None) size = GD.cfg.get('gui/fontsize',None) print style,font,family,size self.setStyle(style) self.setFont(font) if family: self.setFontFamily(family) if size: self.setFontSize(size)
self.setStyle(style) self.setFont(font)
if style: self.setStyle(style) if font: self.setFont(font)
def setAppearence(self): style = GD.cfg['gui/style'] font = GD.cfg['gui/font'] family = GD.cfg.get('gui/fontfamily',None) size = GD.cfg.get('gui/fontsize',None) print style,font,family,size self.setStyle(style) self.setFont(font) if family: self.setFontFamily(family) if size: self.setFontSize(size)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
def __init__(self,items,caption=None,parent=None,flags=None,actions=None,default=None,scroll=False,store=None,prefix='',autoprefix=False,flat=None,modal=None): """Create a dialog asking the user for the value of items.""" if parent is None: parent = pf.GUI QtGui.QDialog.__init__(self,parent) #self.setMaximumSize(*maxSi...
def cselect(self,selected,compact=True)):
def cselect(self,selected,compact=True):
def cselect(self,selected,compact=True)): """Return a mesh without the selected elements.
"
"""
def splitRandom(self,n,compact=True): """Split a mesh in n parts, distributing the elements randomly.
if color:
if color is not None:
def drawGL(self,canvas=None,mode=None,color=None,**kargs): """Draw the geometry on the specified canvas.
print GD.cfg['help/links'] print GD.cfg['help/docs']
def links(link): help('http://'+link)
LinksMenuData = [ (k,links,{'data':v}) for k,v in GD.cfg['help/links'].items() ]
LinksMenuData = [ (k,links,{'data':v}) for k,v in GD.cfg['help/links'] ]
def links(link): help('http://'+link)
if inter:
if intersection_curve:
def boolean(self,surf,op,intersection_curve=False,check=False,verbose=False): """Perform a boolean operation with another surface.
warnings.warn("\n"*'='*60+"\nThe syntax of InputDialog items will change in version 0.9.\nThe new syntax is already available with the classname 'NewInputDialog'\nAfter the change, the old syntax will still be available for some time as 'OldInputDialog'.\n We advice you to move to the new syntax as soon as possible.")
warnings.warn("\n"+'='*60+"\nThe syntax of InputDialog items will change in version 0.9.\nThe new syntax is already available with the classname 'NewInputDialog'\nAfter the change, the old syntax will still be available for some time as 'OldInputDialog'.\n We advice you to move to the new syntax as soon as possible.")
def __init__(self,*args,**kargs): import warnings warnings.warn("\n"*'='*60+"\nThe syntax of InputDialog items will change in version 0.9.\nThe new syntax is already available with the classname 'NewInputDialog'\nAfter the change, the old syntax will still be available for some time as 'OldInputDialog'.\n We advice you...
conn_elems = self.actors[closest_actor].connectedElements(closest_elem,self.selection.get(closest_actor))
conn_elems = self.actors[closest_actor].data.connectedElements(closest_elem,self.selection.get(closest_actor))
def pick(self,mode='actor',single=False,func=None,filter=None): """Interactively pick objects from the viewport.
k = elems[je][0]
k = elems[0][0]
def closedLoop(elems): """Check if a set of line elements form a closed curve. elems is a connection table of line elements, such as obtained from the fuse() method on a plex-2 Formex. The return value is a tuple of: - return code: - 0: the segments form a closed loop - 1: the segments form a single non-closed path...
print("No match found") break
w = where(elems == k) if w[0].size == 0: break else: j,k = k,j reverse_table(srt,ie)
def closedLoop(elems): """Check if a set of line elements form a closed curve. elems is a connection table of line elements, such as obtained from the fuse() method on a plex-2 Formex. The return value is a tuple of: - return code: - 0: the segments form a closed loop - 1: the segments form a single non-closed path...
ie += 1
def closedLoop(elems): """Check if a set of line elements form a closed curve. elems is a connection table of line elements, such as obtained from the fuse() method on a plex-2 Formex. The return value is a tuple of: - return code: - 0: the segments form a closed loop - 1: the segments form a single non-closed path...
adj = concatenate([where(inv>=0,self[:,0][inv],inv),where(inv>=0,self[:,1][inv],inv)],axis=1)
adj = concatenate([where(inv>=0,self[:,i][inv],inv) for i in range(self.nplex())],axis=1)
def adjacency(self,kind='e'): """Return a table of adjacent items.
atol = res['Shift'], atol = res['Nodes per box'],
shift = res['Shift'], nodesperbox = res['Nodes per box'],
def fuseMesh(): """Fuse the nodes of a Mesh""" if not selection.check(): selection.ask() if not selection.names: return meshes = [ named(n) for n in selection.names ] res = askItems([ ('Relative Tolerance',1.e-5), ('Absolute Tolerance',1.e-5), ('Shift',0.5), ('Nodes per box',1)]) if not res: return before = [ m.nco...
def pointsAt(self,u=None): if u is None: u = self.knots ctrl = self.control.astype(double) knots = self.knots.astype(double) u = u.astype(double) try: pts = nu.bspeval(self.order-1,ctrl.transpose(),knots,u) except: print "SOME ERROR OCCURRED" return pts
def drawGL(self,mode,color=None): fgcolor(self.color) nurb = GLU.gluNewNurbsRenderer() GLU.gluNurbsProperty(nurb,GLU.GLU_SAMPLING_TOLERANCE,self.samplingTolerance) GLU.gluBeginCurve(nurb) GLU.gluNurbsCurve(nurb,self.knots,self.control,GL.GL_MAP1_VERTEX_3) GLU.gluEndCurve(nurb)