rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
cmds += __shred_sqlite_char_columns('moz_places', cols)
cmds += __shred_sqlite_char_columns('moz_places', cols, places_suffix)
def delete_mozilla_url_history(path): """Delete URL history in Mozilla places.sqlite (Firefox 3 and family)""" # delete the URLs in moz_places places_suffix = "where id in (select " \ "moz_places.id from moz_places " \ "left join moz_inputhistory on moz_inputhistory.place_id = moz_places.id " \ "left join moz_bookmark...
pathname2 = pathname
pathname2 = pathname1
def wipe_name(pathname1): """Wipe the original filename and return the new pathname""" # reference http://en.wikipedia.org/wiki/Comparison_of_file_systems#Limits (dir, file) = os.path.split(pathname1) maxlen = 226 - len(dir) # first, rename to a long name i = 0 while True: try: pathname2 = os.path.join(dir, __random_st...
if os.path.exists(appicon_path):
if appicon_path and os.path.exists(appicon_path):
def about(self, __event): """Create and show the about dialog""" gtk.about_dialog_set_url_hook(lambda dialog, link: open_url(link)) dialog = gtk.AboutDialog() dialog.set_comments(_("Program to clean unnecessary files")) dialog.set_copyright("Copyright (C) 2010 Andrew Ziem") try: dialog.set_license(open(license_filename...
args = ['df', '-B', '1', pathname] (rc, stdout, stderr) = General.run_external(args) if 0 != rc: return None line = stdout.split('\n')[1] match = re.search("^[/a-z0-9]+\s+[0-9]+\s+[0-9]+([0-9]+)", line) if not match: return None return int(match.groups(0)[0])
mystat = os.statvfs(pathname) return mystat.f_bfree * mystat.f_bsize
def free_space(pathname): """Return free space in bytes""" if 'nt' == os.name: import ctypes free_bytes = ctypes.c_int64() ctypes.windll.kernel32.GetDiskFreeSpaceExW(unicode(pathname), \ ctypes.byref(free_bytes), None, None) return free_bytes.value args = ['df', '-B', '1', pathname] (rc, stdout, stderr) = General.run_e...
try: print u"info: removing '%s'" % path except: p = re.compile('[\x7f-\xff]') print r"info: removing '%s'" % p.sub('?', path)
def delete(path, shred = False): """Delete path that is either file, directory, link or FIFO""" from Options import options try: print u"info: removing '%s'" % path except: p = re.compile('[\x7f-\xff]') print r"info: removing '%s'" % p.sub('?', path) is_special = False if 'posix' == os.name: # With certain (relatively ...
self.ui.update_progress_bar("Please wait. Running deep scan.")
self.ui.update_progress_bar(_("Please wait. Running deep scan."))
def run(self): """Perform the main cleaning process""" count = 0 self.deepscans = {} for operation in self.operations: self.ui.update_progress_bar(1.0 * count / len(self.operations)) name = backends[operation].get_name() if self.really_delete: # TRANSLATORS: %s is replaced with Firefox, System, etc. msg = _("Please wai...
pathname = model[0][0]
pathname = model[_iter][0]
def remove_drive_cb(button): """Callback for removing a drive""" treeselection = treeview.get_selection() (model, _iter) = treeselection.get_selected() if None == _iter: # nothing selected return pathname = model[0][0] liststore.remove(_iter) pathnames.remove(pathname) options.set_list('shred_drives', pathnames)
options.set(pathname, hash, 'hashpath')
options.set(pathname, myhash, 'hashpath')
def __scan(self): """Look for files and act accordingly""" changes = [] for pathname in sorted(list_cleanerml_files(local_only = True)): pathname = os.path.abspath(pathname) (status, myhash) = self.__recognized(pathname) if NEW == status or CHANGED == status: changes.append([ pathname, status, myhash ]) if len(changes)...
file = os.path.expandvars('$SystemRoot\\memory.dmp')
file = os.path.expandvars('$windir\\memory.dmp')
def get_commands(self, option_id): # cache if 'posix' == os.name and 'cache' == option_id: dirname = os.path.expanduser("~/.cache/") for filename in children_in_directory(dirname, True): yield Command.Delete(filename)
for file in glob.iglob(os.path.expandvars('%SystemRoot\\Minidump\\*.dmp')):
for file in glob.iglob(os.path.expandvars('$windir\\Minidump\\*.dmp')):
def get_commands(self, option_id): # cache if 'posix' == os.name and 'cache' == option_id: dirname = os.path.expanduser("~/.cache/") for filename in children_in_directory(dirname, True): yield Command.Delete(filename)
type = self.config.get(section, option + '_type') path = self.config.get(section, option + '_path') values.append( ( type, path ) )
wl_type = self.config.get(section, option + '_type') wl_path = self.config.get(section, option + '_path') values.append( ( wl_type, wl_path ) )
def get_whitelist_paths(self): """Return the whitelist of paths""" section = "whitelist/paths" if not self.config.has_section(section): return [] myoptions = [] for option in sorted(self.config.options(section)): pos = option.find('_') if -1 == pos: continue myoptions.append(option[0:pos]) values = [] for option in set...
self.config = ConfigParser.SafeConfigParser()
def restore(self): """Restore saved options from disk""" self.config = ConfigParser.SafeConfigParser() try: self.config.read(Common.options_file) except: traceback.print_exc() if not self.config.has_section("bleachbit"): self.config.add_section("bleachbit") if not self.config.has_section("hashpath"): self.config.add_se...
self.run_deep_scan()
for dummy in self.run_deep_scan(): yield dummy
def run(self): """Perform the main cleaning process which has these phases 1. General cleaning 2. Deep scan 3. Memory 4. Free disk space""" self.deepscans = {} # prioritize self.delayed_ops = [] for operation in self.operations: delayables = ['free_disk_space', 'memory'] for delayable in delayables: if operation not in...
result[r[uniqueKey]] = int(r.get('score', 0) * 1000)
result[int(r[uniqueKey])] = int(r.get('score', 0) * 1000)
def _apply_index(self, request, cid=''): """Apply query specified by request, a mapping containing the query.
'Change history\n' '**************\n' + '\n' +
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
'**********************\n'
'======================\n'
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
post-processing happends to either
post-processing happens to either
def raw_query(self, **params): """ Issue a query against a SOLR server.
memory.MemoryAccess( flags= memory.MEMORY_GET_SINGLETON | memory.MEMORY_UNIT_TEST_MODE, options.memory_dat)
memory.MemoryAccess( memory.MEMORY_GET_SINGLETON | memory.MEMORY_UNIT_TEST_MODE, options.memory_dat)
def setup_std_options(options): if options.memory_dat is not None: memory.MemoryAccess( flags= memory.MEMORY_GET_SINGLETON | memory.MEMORY_UNIT_TEST_MODE, options.memory_dat) if options.cmos_dat is not None: cmos.CmosAccess( flags= cmos.CMOS_GET_SINGLETON | cmos.CMOS_UNIT_TEST_MODE, options.cmos_dat) options.password...
cmos.CmosAccess( flags= cmos.CMOS_GET_SINGLETON | cmos.CMOS_UNIT_TEST_MODE, options.cmos_dat)
cmos.CmosAccess( cmos.CMOS_GET_SINGLETON | cmos.CMOS_UNIT_TEST_MODE, options.cmos_dat)
def setup_std_options(options): if options.memory_dat is not None: memory.MemoryAccess( flags= memory.MEMORY_GET_SINGLETON | memory.MEMORY_UNIT_TEST_MODE, options.memory_dat) if options.cmos_dat is not None: cmos.CmosAccess( flags= cmos.CMOS_GET_SINGLETON | cmos.CMOS_UNIT_TEST_MODE, options.cmos_dat) options.password...
fcb = None
fcb = ctypes.cast(None, FREE_CALLBACK)
def registerCallback(self, callback, userdata, freecb): cb = WRITE_CALLBACK(callback) # append callback to array that has same lifetime as object so python # doesnt garbage collect it from under us self._callbacks.append(cb) fcb = None if freecb is not None: fcb = FREE_CALLBACK(freecb) self._callbacks.append(fcb) DLL.c...
def from_param(cls,obj): if obj is None: return None from ctypes import _CFuncPtr return _CFuncPtr.from_param(obj) FREE_CALLBACK.from_param = classmethod(from_param)
#typedef int (*cmos_write_callback)(const struct cmos_access_obj *, bool, void *);
ver = "".join([ c for c in self.hdr.biosVersion if c.isalnum() ])
ver = "".join([ chr(c) for c in self.hdr.biosVersion if chr(c).isalnum() ])
def biosVersion(self): ver = "" if self.hdr.headerMajorVer < 2: ver = "".join([ c for c in self.hdr.biosVersion if c.isalnum() ]) else: ver = "%d.%d.%d" % struct.unpack("BBB", self.hdr.biosVersion) return ver
ver = "%d.%d.%d" % struct.unpack("BBB", self.hdr.biosVersion)
ver = "%d.%d.%d" % (self.hdr.biosVersion[0], self.hdr.biosVersion[1], self.hdr.biosVersion[2])
def biosVersion(self): ver = "" if self.hdr.headerMajorVer < 2: ver = "".join([ c for c in self.hdr.biosVersion if c.isalnum() ]) else: ver = "%d.%d.%d" % struct.unpack("BBB", self.hdr.biosVersion) return ver
("biosVersion", ctypes.c_char * 3),
("biosVersion", ctypes.c_uint8 * 3),
# current HDR def leaves room for 12 system ids
if len(ver) = 0:
if len(ver) == 0:
def biosVersion(self): ver = "" if self.hdr.headerMajorVer < 2: ver = "".join([ chr(c) for c in self.hdr.biosVersion if chr(c).isalnum() ]) if len(ver) = 0: ver = "unknown" else: ver = "%d.%d.%d" % (self.hdr.biosVersion[0], self.hdr.biosVersion[1], self.hdr.biosVersion[2]) return ver
myStockasDict = stocks[0] vol = myStockasDict['volume'] return vol
if len(stocks) > 0: myStockasDict = stocks[0] return myStockasDict['volume'] return None
def getVolumePerDay(self, symbol, timestamp): # Call with startTime = endTime = desired timestamp to get just that timestamp #print "VolPerDay timestamp: %d" % timestamp stocks = self.strategyData.getStocks(timestamp, timestamp+1, symbol, self.isTable) myStockasDict = stocks[0] #Grab the first dictionary in the list vo...
def calcEffect(self, maxVol, share):
def calcEffect(self, maxVol, shares):
def calcEffect(self, maxVol, share): return float(shares)/maxVol * self.maxEffect
print stocks
def getVolumePerDay(self, symbol, timestamp): # Call with startTime = endTime = desired timestamp to get just that timestamp stocks = self.strategyData.getStocks(timestamp, timestamp, symbol, self.isTable) print stocks myStockasDict = stocks[0] #Grab the first dictionary in the list vol = myStockasDict['volume'] # Get ...
endIndex= self.timestamps.searchsorted(endTS)
endIndex= min (self.timestamps.searchsorted(endTS), size(self.timestamps))
def getMatrixBetweenTS (self, stocksList, dataItem, beginTS=None, endTS=None, exact=False): ''' @summary: includes beginTS and endTS. This uses the getMatrixBetweenIndex function. @param stocksList: The list of stock names for which you want the data. @param dataItem: The dataItem that you want ex, open , close @param ...
self.strategyData = StrategyData.StrategyData("someRandomStringToNotBreakTheCode", self.dataAccess, self.isTable)
def __init__(self, cash, stocks, startTime, endTime, interval, minCom, comPerShare, isTable, maxEffect, arrayFile, listOfStocksFile): # strategy contains a reference to the strategy method specified in the command line
print "Not enough cash to buy stock."
print "Apparently not enough cash. I don't believe this. Current cash: " + str (self.portfolio.currCash) + " total cost: "+ str (cost)+ ", cost of one share: "+str (self.dataAccess.getStockDataItem(newOrder['symbol'], 'adj_open', ts))
def buyStock(self, newOrder): ''' @summary: function takes in an instance of OrderDetails, executes the changes to the portfolio and adds the order to the order table @param newOrder: an instance of OrderDetails representing the new order @warning: The Order should not be added to the order table before calling this fu...
timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 self.currTimestamp = timestamps[ctr] ctr2= ctr while (timestamps[ctr2]< self.endTime): ctr2+=1 if (ctr2>= len(timestamps)): break if (ctr2>= len (timestamps)): self.endTime= time...
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
print "Simulation timer started at "+ str(self.currTimestamp)
print "Simulation timer started."
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
self.currTimestamp = self.startTime
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
beforeExec=time.clock()
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
afterExec= time.clock()
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
beforeAddOrders= time.clock()
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
afterAddOrders= time.clock()
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
portValue= float (0.0)
portValue = self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp)
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
portValue = (self.portfolio.calcPortfolioValue(self.currTimestamp, self.dataAccess)) portfolioValList.append(portValue)
portValue = self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp)
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
portValue = float (self.portfolio.calcPortfolioValue(self.currTimestamp, self.dataAccess)) portfolioValList.append(portValue)
portValue = self.portfolio.currCash + self.strategyData.calculatePortValue(self.portfolio.currStocks,self.currTimestamp)
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
print "Exec function took: " + str(afterExec - beforeExec) print "Time for addorders: " + str(afterAddOrders - beforeAddOrders)
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
ctr+=1 self.currTimestamp= timestamps[ctr]
self.currTimestamp += self.interval self.strategyData.currTimestamp = self.currTimestamp
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
fig = Figure() canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.plot (portfolioValList) ax.set_title('Portfolio value') ax.grid(True) ax.set_xlabel('time') ax.set_ylabel('$') canvas.print_figure('portfolio')
self.strategyData.close()
def run(self): ''' @summary: Run the simulation ''' optimizer= Optimizer.Optimizer(self.listOfStocks) #optimizer= curveFittingOptimizer.Optimizer(self.listOfStocks) timestamps= list(self.dataAccess.getTimestampArray()) portfolioValList= list() ctr=0 while (timestamps[ctr]< self.startTime): ctr+=1 #while loop done s...
if len(args) != 1:
if len(args) != 3 and len(args) != 2:
def main(): global cash,comPerShare,minCom,startTime,endTime,timeStep,maxEffect,decayCycles,noisy,timersActive,mtm,isTable,arrayFile,listOfStocksFile # NOTE: the OptionParser class is currently not necessary, as we can just access sys.argv[1:], but if we # want to implement optional arguments, this will make it conside...
if len(args) == 3: stratName = args[2] else: stratName = "strategyMain"
def main(): global cash,comPerShare,minCom,startTime,endTime,timeStep,maxEffect,decayCycles,noisy,timersActive,mtm,isTable,arrayFile,listOfStocksFile # NOTE: the OptionParser class is currently not necessary, as we can just access sys.argv[1:], but if we # want to implement optional arguments, this will make it conside...
mySim.strategyData.timestampIndex = mySim.times
def main(): global cash,comPerShare,minCom,startTime,endTime,timeStep,maxEffect,decayCycles,noisy,timersActive,mtm,isTable,arrayFile,listOfStocksFile # NOTE: the OptionParser class is currently not necessary, as we can just access sys.argv[1:], but if we # want to implement optional arguments, this will make it conside...
pass
mySim.times = mySim.strategyData.timestampIndex
def main(): global cash,comPerShare,minCom,startTime,endTime,timeStep,maxEffect,decayCycles,noisy,timersActive,mtm,isTable,arrayFile,listOfStocksFile # NOTE: the OptionParser class is currently not necessary, as we can just access sys.argv[1:], but if we # want to implement optional arguments, this will make it conside...
endIndex= len(self.timestamps) if (self.timestamps[endIndex]>endTS): endIndex = endIndex -1
endIndex= len(self.timestamps)-1
def getMatrixBetweenTS (self, stocksList, dataItem, beginTS=None, endTS=None, exact=False): ''' @summary: includes beginTS and endTS. This uses the getMatrixBetweenIndex function. @param stocksList: The list of stock names for which you want the data. @param dataItem: The dataItem that you want ex, open , close @param ...
endIndex= self.timestamps.searchsorted(endTS) - 1
endIndex= self.timestamps.searchsorted(endTS) if ((self.timestamps[endIndex]>endTS) and (endIndex > beginIndex)): endIndex = endIndex -1
def getMatrixBetweenTS (self, stocksList, dataItem, beginTS=None, endTS=None, exact=False): ''' @summary: includes beginTS and endTS. This uses the getMatrixBetweenIndex function. @param stocksList: The list of stock names for which you want the data. @param dataItem: The dataItem that you want ex, open , close @param ...
raise TypeError("Not an existing close type '%s'." % str(newOrder.order_type))
raise TypeError("Not an existing close type '%s'." % str(closeType))
def removePosition(self, symbol, shares, closeType): ''' symbol: the representation of the shares to be removed shares: the number of shares to remove closeType: removal order "lifo" or "fifo" Removes/modifies positions until the total number of shares have been removed NOTE: Method assumes that verification of valid s...
raise TypeError("Not an existing close type '%s'." % str(newOrder.order_type))
raise TypeError("Not an existing close type '%s'." % str(closeType))
def removePosition(self, symbol, shares, closeType, isTable = True): ''' symbol: the representation of the shares to be removed shares: the number of shares to remove closeType: removal order "lifo" or "fifo" Removes/modifies positions until the total number of shares have been removed NOTE: Method assumes that verific...
@return: a 2D numpy array such that: No. or rows = (endTS- beginTS +1) becuase both timestamps are included. No. of cols.= len (@param stocksList )
@return: a 2D numpy array such that: No. or rows is = (endTS- beginTS +1) when both beginTS and endTs are found-becuase both timestamps are included. If either beginTS or endTS are not found then the No. or rows might be less than that. No. of cols.= len (@param stocksList )
def getMatrixBetweenTS (self, stocksList, dataItem, beginTS=None, endTS=None, exact=False): ''' @summary: includes beginTS and endTS. This uses the getMatrixBetweenIndex function. @param stocksList: The list of stock names for which you want the data. @param dataItem: The dataItem that you want ex, open , close @param ...
endIndex= len(self.timestamps) -1
endIndex= len(self.timestamps) if (self.timestamps[endIndex]>endTS): endIndex = endIndex -1
def getMatrixBetweenTS (self, stocksList, dataItem, beginTS=None, endTS=None, exact=False): ''' @summary: includes beginTS and endTS. This uses the getMatrixBetweenIndex function. @param stocksList: The list of stock names for which you want the data. @param dataItem: The dataItem that you want ex, open , close @param ...
raise NotImplementedError
v = ny.log(self._data) name = name or 'log(%s,%s)' % (self.name,lag) return self.clone(self._date,v,name)
def log(self, name = None, **kwargs): raise NotImplementedError
func = _functions.get(func,None) or func
def _rollapply(self, func, window = 20, **kwargs):
for c in range(self.count()): yield data[:,c]
if data: for c in range(self.count()): yield data[:,c] else: raise StopIteration
def series(self): data = self.values() for c in range(self.count()): yield data[:,c]
if data:
if len(data):
def series(self): '''Generator of single series.''' data = self.values() if data: for c in range(self.count()): yield data[:,c] else: raise StopIteration
def __init__(self, list): assert len(list) > 0, "Sequece must not be empty"
def __init__(self, L, types=None): """ L - list of rows types - list of types of row, for example [int, str, bool, int] if types is None, then this list is derived from first row of sequence """ self.L = L if types is None: if len(L) == 0: raise ValueError("If arg. types is None, then sequece must not be empty") row ...
def __init__(self, list): assert len(list) > 0, "Sequece must not be empty" gtk.GenericTreeModel.__init__(self) self.L = list
self.L = list
def __init__(self, list): assert len(list) > 0, "Sequece must not be empty" gtk.GenericTreeModel.__init__(self) self.L = list
if type(self.L[0]) in [list, tuple]: return len(self.L[0]) else: return 1
return len(self.__types)
def on_get_n_columns(self): if type(self.L[0]) in [list, tuple]: return len(self.L[0]) else: return 1
if type(self.L[0]) in [list, tuple]: return type(self.L[0][index]) else: return type(self.L[0])
return self.__types[index]
def on_get_column_type(self, index): if type(self.L[0]) in [list, tuple]: return type(self.L[0][index]) else: return type(self.L[0])
d = gtk.Dialog()
H = Header()
def on_expose(self, window, event): a = event.area f = a[1]/self.h k = a[3]/self.h print a, f, k y = f*self.h for i in xrange(f, f+k+1): x = 0 for j, (w, renderer) in enumerate(self.columns): r = gtk.gdk.Rectangle(x, y, w, self.h) background_area = r cell_area = r expose_area = cell_area renderer.set_property("text", s...
c = sqlite.connect('pylocate/test')
c = sqlite.connect('test')
def on_expose(self, window, event): a = event.area f = a[1]/self.h k = a[3]/self.h print a, f, k y = f*self.h for i in xrange(f, f+k+1): x = 0 for j, (w, renderer) in enumerate(self.columns): r = gtk.gdk.Rectangle(x, y, w, self.h) background_area = r cell_area = r expose_area = cell_area renderer.set_property("text", s...
(150, gtk.CellRendererText())
(150, renderer)
def on_expose(self, window, event): a = event.area f = a[1]/self.h k = a[3]/self.h print a, f, k y = f*self.h for i in xrange(f, f+k+1): x = 0 for j, (w, renderer) in enumerate(self.columns): r = gtk.gdk.Rectangle(x, y, w, self.h) background_area = r cell_area = r expose_area = cell_area renderer.set_property("text", s...
sw.add_with_viewport(v)
sw.add_with_viewport(vbox)
def on_expose(self, window, event): a = event.area f = a[1]/self.h k = a[3]/self.h print a, f, k y = f*self.h for i in xrange(f, f+k+1): x = 0 for j, (w, renderer) in enumerate(self.columns): r = gtk.gdk.Rectangle(x, y, w, self.h) background_area = r cell_area = r expose_area = cell_area renderer.set_property("text", s...
class GridView(gtk.DrawingArea):
class DrawGrid(gtk.DrawingArea):
def get_item(self, row, col): return self.get_row(row)[col]
self.left_pix = x self.queue_draw()
if self.left_pix != x: self.left_pix = x self.queue_draw()
def set_h_scroll(self, x): self.left_pix = x self.queue_draw()
if self.gc is None: gc = self.get_style().bg_gc[gtk.STATE_NORMAL] self.gc = gtk.gdk.GC(self.window) self.gc.copy(gc) self.gc.set_rgb_fg_color(gtk.gdk.Color(0xffff, 0xffff, 0xffff)) gobject.type_register(GridView)
gobject.type_register(DrawGrid)
def do_expose_event(self, event): t = self.top_pix / self.h b = (self.top_pix + self.allocation.height) / self.h print t, b, b-t+1 self.draw_area(t, b)
self.highlight = [None, 0, None]
self.highlight = [None, 0, None, 0]
def __init__(self, grid_view = None): gtk.Container.__init__(self) self.grid_view = grid_view self.columns = [] self.height = 45 self.highlight = [None, 0, None] self.dragging = False self.drag_dist = 10 self.last_x = None self.gc = None self._changed = False self.total_width = 0
def _do_layout(self, scroll=0):
def _do_layout(self):
def _do_layout(self, scroll=0): y = 0 x = scroll h = self.height for w, button in self.columns: R = gdk.Rectangle(x, y, w, h) button.size_allocate(R) x += w
x = scroll
x = - self.x_scroll
def _do_layout(self, scroll=0): y = 0 x = scroll h = self.height for w, button in self.columns: R = gdk.Rectangle(x, y, w, h) button.size_allocate(R) x += w
self._do_layout(-x)
if x != self.x_scroll: self.x_scroll = x self._do_layout()
def set_scroll(self, x):
self.columns[index].set_size_request(width, self.height)
self.columns[index] = (width, self.columns[index][1])
def set_column_width(self, index, width): self.columns[index].set_size_request(width, self.height)
self.on_end_drag(self.highlight[0], None)
self.on_end_drag(self.highlight[0], True)
def event(self, button, event): if self.dragging: if event.type == gtk.gdk.MOTION_NOTIFY: button = self.highlight[0] x = int(event.x) button.set_size_request(x, self.height) self._do_layout() try: self.on_dragging(self.highlight[0], self.highlight[2] + x) finally: return True elif event.type == gtk.gdk.BUTTON_RELEASE: ...
self.draw_line(x) pass def on_end_drag(self, button, x):
def on_dragging(self, button, x): self.draw_line(x) pass
self.grid_view.set_width(button.index, button.allocation.width)
self.draw_line(x) self.set_column_width(button.index, x - button.allocation.x) self._do_layout()
def on_end_drag(self, button, x): try: self.grid_view.set_width(button.index, button.allocation.width) except: import traceback traceback.print_exc() self.draw_line(-100) self.last_x = None pass
v = GridView(columns, l)
v = DrawGrid(columns, l)
def do_set_scroll_adjustments(self, hadjustment, vadjustment): self.hadjustment = hadjustment self.vadjustment = vadjustment
m.addFieldModel(FieldModel(u'Back', True, True))
m.addFieldModel(FieldModel(u'Back', False, False))
def LingwoModel(): m = Model(u'Lingwo') m.addFieldModel(FieldModel(u'Front', True, True)) m.addFieldModel(FieldModel(u'Back', True, True)) m.addFieldModel(FieldModel(u'Lingwo ID', True, True)) m.addCardModel(CardModel(u'Forward', u'%(Front)s', u'%(Back)s')) m.addCardModel(CardModel(u'Reverse', u'%(Back)s', u'%(Front)s'...
res['id'] = fact.id
res['id'] = str(fact.id)
def _output_fact(self, fact): res = dict(zip(fact.keys(), fact.values())) res['id'] = fact.id return res
fact[key] = fields[key]
fact[key] = unicode(fields[key])
def add_fact(self, deck_id, fields): deck = self._open_deck(deck_id)
newFact = deck.s.query(Fact).get(fact['id'])
newFact = deck.s.query(Fact).get(int(fact['id']))
def save_fact(self, deck_id, fact): deck = self._open_deck(deck_id) try: newFact = deck.s.query(Fact).get(fact['id']) for key in newFact.keys(): newFact[key] = fact[key]
deck.deleteFact(fact_id)
deck.deleteFact(int(fact_id))
def delete_fact(self, deck_id, fact_id): deck = self._open_deck(deck_id) try: deck.deleteFact(fact_id) deck.save() finally: deck.close()
path = self._get_path(path) if os.path.exists(path):
full_path = self._get_path(path) if os.path.exists(full_path):
def create_deck(self, path): path = self._get_path(path) if os.path.exists(path): raise HTTPBadRequest('"%s" already exists' % path)
deck = anki.DeckStorage.Deck(path)
deck = anki.DeckStorage.Deck(full_path)
def create_deck(self, path): path = self._get_path(path) if os.path.exists(path): raise HTTPBadRequest('"%s" already exists' % path)
path = self._get_path(path) if not os.path.exists(path):
full_path = self._get_path(path) if not os.path.exists(full_path):
def _open_deck(self, path): path = self._get_path(path) if not os.path.exists(path): raise HTTPBadRequest('"%s" doesn\'t exist' % path)
return anki.DeckStorage.Deck(path)
return anki.DeckStorage.Deck(full_path)
def _open_deck(self, path): path = self._get_path(path) if not os.path.exists(path): raise HTTPBadRequest('"%s" doesn\'t exist' % path)
return len(self._lookup)-1, (pos, elem), len(elem.nodeValue)-1
return len(self._lookup)-1, (pos, elem), len(elem.nodeValue)
def _find(self, index): res = None i = 0 for (pos, elem) in self._lookup: if index < pos: res = (pos, elem) break i += 1 if res is None: # we return the last element on the last character return len(self._lookup)-1, (pos, elem), len(elem.nodeValue)-1
elif which == ElementString._SPLIT_START and localIndex == len(elem.nodeValue)-1: lookupIndex, (pos, elem), localIndex = self._find(index+1)
def _splitEndPoint(self, index, which): lookupIndex, (pos, elem), localIndex = self._find(index) if which == ElementString._SPLIT_END and localIndex == 0: # we really want the previous element because we are past the edge lookupIndex, (pos, elem), localIndex = self._find(index-1) elif which == ElementString._SPLIT_STAR...
if localIndex == len(elem.nodeValue) - 1:
if localIndex == len(elem.nodeValue):
def walkUpParent(elem): while elem.parentNode.tagName == 'word': if which == ElementString._SPLIT_START and elem == elem.parentNode.firstChild: elem = elem.parentNode elif which == ElementString._SPLIT_END and elem == elem.parentNode.lastChild: elem = elem.parentNode else: break return elem
print seg
if not re.search(r'\w', seg): continue
def _doSegment(self): if not self._elemStr.is_empty(): raw_text = str(self._elemStr) segments = self._tokenize(raw_text) endIndex = 0 for seg in segments: #if not re.match(r'\w', seg): # # if this segment has no "word" characters in it, we don't # # really want it # continue print seg startIndex = raw_text.fin...
print startIndex, endIndex
def _doSegment(self): if not self._elemStr.is_empty(): raw_text = str(self._elemStr) segments = self._tokenize(raw_text) endIndex = 0 for seg in segments: #if not re.match(r'\w', seg): # # if this segment has no "word" characters in it, we don't # # really want it # continue print seg startIndex = raw_text.fin...
def main(): fd = open('text1-clean.txt', 'rt') doc = html5lib.parse(fd, treebuilder="dom")
def parse(fd): return html5lib.parse(fd, treebuilder='dom') def parseString(s): from StringIO import StringIO return parse(StringIO(s)) def segmentDocument(doc):
def main(): fd = open('text1-clean.txt', 'rt') doc = html5lib.parse(fd, treebuilder="dom") #buildOuter(doc.getElementsByTagName('body')[0]) #segmentSentences(s) sent_segmenter = SentenceSegmenter() sent_segmenter.run(doc.getElementsByTagName('body')[0]) #word_segmenter = WordSegmenter() #for sent in doc.getElementsByT...
word_segmenter = WordSegmenter() for sent in doc.getElementsByTagName('s'): word_segmenter.run(sent) def main(): doc = parse(open('text1-clean.txt', 'rt')) segmentDocument(doc)
def main(): fd = open('text1-clean.txt', 'rt') doc = html5lib.parse(fd, treebuilder="dom") #buildOuter(doc.getElementsByTagName('body')[0]) #segmentSentences(s) sent_segmenter = SentenceSegmenter() sent_segmenter.run(doc.getElementsByTagName('body')[0]) #word_segmenter = WordSegmenter() #for sent in doc.getElementsByT...
return hashlib.sha1(':'.join([language, pos, headword])).hexdigest()
return hashlib.sha1((unicode(language)+':'+pos+':'+headword).encode('utf-8')).hexdigest()
def hash(cls, language, pos, headword): import hashlib return hashlib.sha1(':'.join([language, pos, headword])).hexdigest()
for field in form.fields.items():
for field in form.cleaned_data.items():
def content_edit(request): new = bool(request.REQUEST.get("new")) path = request.GET["path"] absPath = os.path.join(settings.SIMPLECONTENT_ROOT, path) template = templateManager.getFromFile(absPath) if not new else None parent = template.getParent() if template else request.REQUEST["parent"] connections = BlockConnect...
if self._holds[observable, notification]["notifications"] and self._holds[observable, notification]["notifications"][-1] != n:
if not self._holds[observable, notification]["notifications"] or self._holds[observable, notification]["notifications"][-1] != n:
def postNotification(self, notification, observable, data=None): """ Post a notification to all objects observing **notification** in **observable**.
if self._holds[observable]["notifications"] and self._holds[observable]["notifications"][-1] != n:
if not self._holds[observable]["notifications"] or self._holds[observable]["notifications"][-1] != n:
def postNotification(self, notification, observable, data=None): """ Post a notification to all objects observing **notification** in **observable**.
self._holds[key] = dict(holdCount=0, notifications=set())
self._holds[key] = dict(holdCount=0, notifications=[])
def holdNotificationsForObservable(self, observable, notification=None): """ Hold all notifications posted to all objects observing **notification** in **observable**.
def disableNotificationsForObservable(self, observable, notification=None): """ Disable all notifications posted to all objects observing **notification** in **observable**.
def disableNotificationsForObservable(self, observable, notification=None, observer=None): """ Disable all posts of **notification** from **observable** posted to **observer** observing.
def disableNotificationsForObservable(self, observable, notification=None): """ Disable all notifications posted to all objects observing **notification** in **observable**.