rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
parser.add_option("-p", "--nostore", dest="store_msg",
parser.add_option("-s", "--nostore", dest="store_msg",
def _read_amqp_config(galaxy_config): """Read connection information on the RabbitMQ server from Galaxy config. """ config = ConfigParser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in config.options("galaxy_amqp"): amqp_config[option] = config.get("galaxy_amqp", option) return amqp_config
else: return i
def search_connections (c): i=0 #seraching for a specific box in memory for connections in memory_connections: if c==connections: return i i+=1 #return -1 if not if i==len(memory_connections): return -1 else: return i
sleep(0.1)
sleep(0.01)
def create(self): b1 = search_box(self.box_orig) b2 = search_box(self.box_dest)
print t1 print print "------" print print t2
def create(self): b1 = search_box(self.box_orig) b2 = search_box(self.box_dest)
sleep(0.1)
sleep(0.01)
def delete(self): b1 = search_box(self.box_orig) b2 = search_box(self.box_dest) if (b1 > -1) & (b2 > -1): #get the state before removing the connection self.snd.send_pd("pd-new menusave ; ") sleep(0.1) t1 = self.snd.get_file() #try to remove the connection command = Connection.canvas + "disconnect " + str(b1) + " " + ...
print t1 print print "------" print print t2
def delete(self): b1 = search_box(self.box_orig) b2 = search_box(self.box_dest) if (b1 > -1) & (b2 > -1): #get the state before removing the connection self.snd.send_pd("pd-new menusave ; ") sleep(0.1) t1 = self.snd.get_file() #try to remove the connection command = Connection.canvas + "disconnect " + str(b1) + " " + ...
memory_box.pop(i)
memory_connections.pop(i)
def delete(self): b1 = search_box(self.box_orig) b2 = search_box(self.box_dest) if (b1 > -1) & (b2 > -1): #get the state before removing the connection self.snd.send_pd("pd-new menusave ; ") sleep(0.1) t1 = self.snd.get_file() #try to remove the connection command = Connection.canvas + "disconnect " + str(b1) + " " + ...
command = "symbolatom " + str(s.x) + " " + str(s.y) + " 10 0 0 0 - - pyata ;"
command = "obj " + str(s.x) + " " + str(s.y) + " sym ;"
def debug_symbol(): pd = Communication(False) pd.init_pd() s = Symbol(10, 10, 0) command = "symbolatom " + str(s.x) + " " + str(s.y) + " 10 0 0 0 - - pyata ;" print command pd.send_pd(command) sleep(2) command = s.set("mesa") print command pd.send_pd(command) sleep(2) pd.finish_pd()
def debug_number(): pd = Communication(False) pd.init_pd() n = Number(10, 10, 0) command = "floatatom " + str(n.x) + " " + str(n.y) + " 5 0 0 0 - - pyata ;" print command pd.send_pd(command) sleep(2) command = n.increment() print command pd.send_pd(command) sleep(2) print n.get_value() command = n.increment() pri...
def debug_message(): pd = Communication(False) pd.init_pd() m = Message(10, 10, "alo", 0) command = "msg " + str(m.x) + " " + str(m.y) + " " + m.text + " ; " print command pd.send_pd(command) sleep(2) command = m.click() print command pd.send_pd(command) sleep(2) command = "editmode 1 ;" print command pd.send_pd(co...
if user:
if Transaction().user:
def check_root(self, ids): "Check Root" account_obj = self.pool.get('analytic_account.account')
self.assertRaises(Exception, test_view('analytic_account'))
test_view('analytic_account')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('analytic_account'))
print '''Usage: %s [-s||-f|-h]
print '''Usage: %s [-s|-f|-h]
def notify_dbus(args): args = args.split(':') return [NOTIFIER_DBUS, '-i', 'gtk-dialog-info', '-t', '5000', ':'.join(args[1:]), args[0]]
''' % sys.argv[0]
''' % (sys.argv[0], sys.argv[0])
def notify_dbus(args): args = args.split(':') return [NOTIFIER_DBUS, '-i', 'gtk-dialog-info', '-t', '5000', ':'.join(args[1:]), args[0]]
Futhermore it is possible to multiply the counter with an :class:`int` as
Furthermore it is possible to multiply the counter with an :class:`int` as
def __repr__(self): content = repr(self.items()) if self else '' return '%s(%s)' % (self.__class__.__name__, content)
occurence of the given `object` or entirely if it is not found.
occurrence of the given `object` or entirely if it is not found.
def remove(self, object): """ Looks for the given `object` in the list and removes the first occurrence.
Sets the given `obj` as result, set `sucess` to ``False`` if `obj`
Sets the given `obj` as result, set `success` to ``False`` if `obj`
def set(self, obj, success=True): """ Sets the given `obj` as result, set `sucess` to ``False`` if `obj` is an exception. """ self.value = obj self.success = success if self.callback and success: self.callback(obj) if self.errback and not success: self.errback(obj) with self.condition: self.ready = True self.condition....
class MultiDictTextMixin(object):
class MultiDictTestMixin(object):
def clear(self): d = self.dict_class() with Assert.raises(TypeError): d.clear()
class TestMultiDict(TestBase, MultiDictTextMixin, DictTestMixin):
class TestMultiDict(TestBase, MultiDictTestMixin, DictTestMixin):
def popitemlist(self): d = self.dict_class({'foo': 'bar'}) Assert(d.popitemlist()) == ('foo', ['bar']) with Assert.raises(KeyError): d.popitemlist() d = self.dict_class({'foo': ['bar', 'baz']}) Assert(d.popitemlist()) == ('foo', ['bar', 'baz']) with Assert.raises(KeyError): d.popitemlist()
return (self[k] for k in self)
return (dict.__getitem__(self, k) for k in self)
def itervalues(self): """ Returns an iterator over the values of all items in insertion order. """ return (self[k] for k in self)
sysconf_name = 'SC_NPROCESSORS_ONLN' if sysconf_name in os.sysconf_names: return os.sysconf('SC_NPROCESSORS_ONLN')
try: cpu_count = os.sysconf('SC_NPROCESSORS_ONLN') if cpu_count >= 1: return cpu_count except AttributeError, ValueError:
def get_cpu_count(default=None): sysconf_name = 'SC_NPROCESSORS_ONLN' if sysconf_name in os.sysconf_names: return os.sysconf('SC_NPROCESSORS_ONLN') if default is not None: return default raise NotImplementedError()
Return `r` length subsequences of elements from the `iterable` allowing
Return `r` length sub-sequences of elements from the `iterable` allowing
def combinations_with_replacement(iterable, r): """ Return `r` length subsequences of elements from the `iterable` allowing individual elements to be replaced more than once. Combinations are emitted in lexicographic sort order. So, if the input `iterable` is sorted, the combinations tuples will be produced in sorted ...
Cost in terms of lazyness of supported operators, this does not include
Cost in terms of laziness of supported operators, this does not include
def __and__(self, other): if not isinstance(other, self.__class__): return NotImplemented result = Counter() if len(self) < len(other): self, other = other, self for element in ifilter(self.__contains__, other): newcount = min(self[element], other[element]) if newcount > 0: result[element] = newcount return result
except ValueError, KeyError:
except (ValueError, KeyError):
def get_cpu_count(default=None): if sys.platform == 'win32': try: return int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError, KeyError: # value could be anything or not existing pass if sys.platform in ('bsd', 'darwin'): try: return int(os.popen('sysctl -n hw.ncpu').read()) except ValueError: # don't trust the ou...
except AttributeError, ValueError:
except (AttributeError, ValueError):
def get_cpu_count(default=None): if sys.platform == 'win32': try: return int(os.environ['NUMBER_OF_PROCESSORS']) except ValueError, KeyError: # value could be anything or not existing pass if sys.platform in ('bsd', 'darwin'): try: return int(os.popen('sysctl -n hw.ncpu').read()) except ValueError: # don't trust the ou...
def find_crosses(satellite1, start, end, satellite2='calipso', t_window=2, lon_range=None,
def find_crosses(satellite1, start, end, satellite2='calipso', time_window=20, lon_range=None,
def find_crosses(satellite1, start, end, satellite2='calipso', t_window=2, lon_range=None, lat_range=None): """Use snotimes to find satellite passes where the given *satellite* crosses CALIPSO's path within a time window *t_window*. Sort out any cross points which are outside *lon_range* and/or *lat_range*.""" import s...
import subprocess
from subprocess import Popen, PIPE import os
def find_crosses(satellite1, start, end, satellite2='calipso', t_window=2, lon_range=None, lat_range=None): """Use snotimes to find satellite passes where the given *satellite* crosses CALIPSO's path within a time window *t_window*. Sort out any cross points which are outside *lon_range* and/or *lat_range*.""" import s...
cmd = [SNO_EXECUTABLE, satellite1, satellite2, start, end, str(t_window)]
wd = os.getcwd() os.chdir(os.path.dirname(SNO_EXECUTABLE)) cmd = [SNO_EXECUTABLE, satellite1, satellite2, start, end, str(time_window)]
def find_crosses(satellite1, start, end, satellite2='calipso', t_window=2, lon_range=None, lat_range=None): """Use snotimes to find satellite passes where the given *satellite* crosses CALIPSO's path within a time window *t_window*. Sort out any cross points which are outside *lon_range* and/or *lat_range*.""" import s...
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
process = Popen(cmd, stdout=PIPE, stderr=PIPE) process.stderr.close() os.chdir(wd)
def find_crosses(satellite1, start, end, satellite2='calipso', t_window=2, lon_range=None, lat_range=None): """Use snotimes to find satellite passes where the given *satellite* crosses CALIPSO's path within a time window *t_window*. Sort out any cross points which are outside *lon_range* and/or *lat_range*.""" import s...
parser.set_usage("usage: %prog [options] satellite1 [satellite2 [...]]") parser.add_option('-t', '--time_window', type='int', default=2, help="Time window for crossing.")
parser.set_usage("usage: %prog [options] <start YYMMDD> <end YYMMDD> satellite1 [satellite2 [...]]\n" "Find times and locations where Calipso and the specified satellites cross paths.") parser.add_option('-t', '--time_window', type='int', default=20, help="Time window for crossing. Default: 20 min.")
def parse_range(range): """Parse *range*, which should look like -35.7354:25.1. Return (lower, upper).""" l = range.split(':') return (float(l[0]), float(l[1]))
for satellite in args: find_crosses(satellite, options.time_window, lon_range, lat_range)
start = args[0] end = args[1] crosses = set() for satellite in args[2:]: crosses.update(find_crosses(satellite, start, end, time_window=options.time_window, lon_range=lon_range, lat_range=lat_range)) for cross in sorted(crosses): print(cross)
def parse_range(range): """Parse *range*, which should look like -35.7354:25.1. Return (lower, upper).""" l = range.split(':') return (float(l[0]), float(l[1]))
i=a+21
i=a
def FindFiles(avhrrfile, avhrr_dir_date): #avhrr_sat = 'NOAA-18' #RESOLUTION = 5 #avhrr_dir_date = ['06','2007','06','2007'] #CL_DIR = "%s/CloudSat/5km/2007/06" %(SAT_DIR) #CAL_DIR = "%s/Calipso/5km/2007/06" %(SAT_DIR) #AVHRR_DIR = "%s/%s/5km/2007/06" %(SAT_DIR,avhrr_sat) #cloudtypefile = 'noaa18_20070622_1208_10760_s...
if len(avhrr_height) > 20:
if len(avhrr_height_work) > 20:
def CalculateStatistics(mode, clsatObj, statfile, caObj, cal_MODIS_cflag, cal_vert_feature, avhrr_ctth_csat_ok, data_ok, cal_data_ok, avhrr_ctth_cal_ok, caliop_max_height, process_calipso_ok, Resolution): import Scientific.Statistics import numpy
upplosning = len(cllon)/500
N = len(cllon)/500 + 2 upplosning = len(cllon)/N
def plotSatelliteTrajectory(cllon,cllat,calon,calat,avhrlon,avhrlat,trajectoryname): from mpl_toolkits.basemap import Basemap import pylab #import pdb #pdb.set_trace() #from setup import AREA upplosning = len(cllon)/500 print('Resolution = %i' %(upplosning)) m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\ ll...
pdb.set_trace()
def getCaliopAvhrrMatch(avhrrfile,calipsofile,ctypefile,ctthfile,surftfile,sunanglefile): import string,os import pps_io import epshdf import Numeric basename = os.path.basename(ctypefile).split(".h5")[0] base_sat = basename.split("_")[-8] base_year = basename.split("_")[-7][0:4] base_month = basename.split("_")[-7][4...
return self.price_set.all()[0]
price_set = self.price_set.all() if price_set: return price_set[0] else: return None
def current_day_price(self): return self.price_set.all()[0]
return self.price_set.all()[1]
price_set = self.price_set.all() if price_set and price_set.count() >= 2: return price_set[1] else: return None
def previous_day_price(self): return self.price_set.all()[1]
return self.price_set.all()[:15]
price_set = self.price_set.all() if price_set: return price_set[:15] else: return []
def latest_15_day_price_set(self): return self.price_set.all()[:15]
until_date = self.price_set.all()[0].date from_date = until_date - timedelta(52*7) self._last_52_week_price_set = self.price_set.filter(date__gt=from_date, date__lte=until_date)
current_day_price = self.current_day_price if current_day_price: until_date = current_day_price.date from_date = until_date - timedelta(52*7) self._last_52_week_price_set = self.price_set.filter(date__gt=from_date, date__lte=until_date) else: self._last_52_week_price_set = []
def last_52_week_price_set(self): try: self._last_52_week_price_set except AttributeError: until_date = self.price_set.all()[0].date from_date = until_date - timedelta(52*7) self._last_52_week_price_set = self.price_set.filter(date__gt=from_date, date__lte=until_date) return self._last_52_week_price_set
img -= minimum(img,T)
img -= np.minimum(img,T)
def softthreshold(img,T): ''' softthreshold(img,T) Implement a soft threshold: img[i] = max(img[i]-T,0) Processes the image inplace, return a reference to img. Use B = softthreshold(A.copy(),T) to get a copy. @see hardthreshold ''' img -= minimum(img,T) return img
def rc(img,ignore_zeros=False): """ T = rc(img, ignore_zeros=False) Calculate a threshold according to the RC method. @param ignore_zeros: Whether to ignore zero valued pixels (default: False) """ hist=fullhistogram(img) if ignore_zeros: if hist[0] == img.size: return 0 hist[0]=0 N=hist.size sum1 = cumsum(arange(N)...
def rc(img,ignore_zeros=False): """ T = rc(img, ignore_zeros=False) Calculate a threshold according to the RC method. @param ignore_zeros: Whether to ignore zero valued pixels (default: False) """ hist=fullhistogram(img) if ignore_zeros: if hist[0] == img.size: return 0 hist[0]=0 N=hist.size # Precompute most of wha...
version='0.4.9',
version='0.5.0-rc0',
def test_pyversion(): import sys maj,min,_,_,_ = sys.version_info if (maj,min) < (2,5): print "Your Python interpreter is too old for Pyslic.\nUpgrade to 2.5 or newer.\n" sys.exit(1)
author_email='murphy@mcu.edu',
author_email='murphy@cmu.edu',
def test_pyversion(): import sys maj,min,_,_,_ = sys.version_info if (maj,min) < (2,5): print "Your Python interpreter is too old for Pyslic.\nUpgrade to 2.5 or newer.\n" sys.exit(1)
weight=nu.reshape(self.weight[key,:],(nkey,self.da)))
weight=self.weight[key,:])
def __getitem__(self,key): if not isinstance(key,slice): nkey= 1 else: nkey= len(self.a[key,0]) if len(self.acov.shape) == 2: acov= self.acov[key,:] dacov= (nkey,self.da) else: acov= self.acov[key,:,:] dacov= (nkey,self.da,self.da) if hasattr(self,'weight'): out= xddata(a=nu.reshape(self.a[key,:],(nkey,self.da)), acov=...
weight=self.weight[key,:])
weight=self.weight[key])
def __getitem__(self,key): if not isinstance(key,slice): nkey= 1 else: nkey= len(self.a[key,0]) if len(self.acov.shape) == 2: acov= self.acov[key,:] dacov= (nkey,self.da) else: acov= self.acov[key,:,:] dacov= (nkey,self.da,self.da) if hasattr(self,'weight'): out= xddata(a=nu.reshape(self.a[key,:],(nkey,self.da)), acov=...
out.append(_sample_normal(self.mean[c,:],self.covar[c,:,:],
out.extend(_sample_normal(self.mean[c,:],self.covar[c,:,:],
def sample(self,nsample=1): """ NAME:
tmp_tags.pop(ii)
tmp_tags.pop(ii-popped) popped+= 1
def __init__(self,**kwargs): if kwargs.has_key('filename'): tmp_ext= re.split('\.',kwargs['filename'])[-1] if tmp_ext == 'gz': tmp_ext= re.split('\.',kwargs['filename'])[-2]+'.'+tmp_ext if tmp_ext == 'fit' or tmp_ext == 'fits' or \ tmp_ext == 'fit.gz' or tmp_ext == 'fits.gz': if kwargs.has_key('atag'): atag= kwargs['at...
tags[ii].lower() == acovtag.lower:
tags[ii].lower() == acovtag.lower():
def __init__(self,**kwargs): if kwargs.has_key('filename'): tmp_ext= re.split('\.',kwargs['filename'])[-1] if tmp_ext == 'gz': tmp_ext= re.split('\.',kwargs['filename'])[-2]+'.'+tmp_ext if tmp_ext == 'fit' or tmp_ext == 'fits' or \ tmp_ext == 'fit.gz' or tmp_ext == 'fits.gz': if kwargs.has_key('atag'): atag= kwargs['at...
self.log = logging.getLogger()
self.log = logging.getLogger( '%s.%s' % (__name__, self.__class__.__name__)) self.workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) self.build_dir = os.path.join(self.workingbranch_dir, 'build') if not os.path.isdir(self.build_dir): self.log.debug('Creating build dir: %s' % (self.b...
def __init__(self, buildversion, log=None): self.buildversion = buildversion if log is not None: self.log = log else: self.log = logging.getLogger()
workingbranch_dir = os.path.join(os.path.dirname(__file__), '..') build_dir = os.path.join(workingbranch_dir, 'build') if not os.path.isdir(build_dir): self.log.debug('Creating working dir: %s' % (build_dir,)) os.mkdir(build_dir) else: self.log.debug('Using working dir: %s' % (build_dir,))
workingbranch_dir = self.workingbranch_dir build_dir = self.build_dir
def main(self, argv): """ The main entry point for the build-apidocs command
))
), stdout=PIPE, stderr=PIPE,)
def producer(): with open(yuizip_path, 'w') as yuizip: self.log.debug('Downloading YUI Doc') download = urlopen(YUIDOC_URL) while True: bytes = download.read(1024*10) if not bytes: break else: yuizip.write(bytes) yield bytes
workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) build_dir = os.path.join(workingbranch_dir, 'build')
workingbranch_dir = self.workingbranch_dir build_dir = self.build_dir self.log.debug('Export versioned files to a build folder')
def main(self, argv): workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))
self.log.debug('Record the branch version')
def main(self, argv): workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))
self.log.debug('Generate apidocs')
def main(self, argv): workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))
self.log.debug('Generate archive')
def main(self, argv): workingbranch_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..'))
self.log.error("isURICorrect: %s" % str(e))
pass
def isURICorrect(self, uri): """ """ returned = False try: data = self.dbc.getBrowserUri() except viewpointdirect.BrowserNotPresent, e: self.log.error("isURICorrect: %s" % str(e)) else: if data: rc = simplejson.loads(data) vp_uri = rc['data'] admin_uri = self.config.get('admin_uri', None) if vp_uri.startswith(uri) o...
if vp_uri.startswith(uri) or vp_uri.startswith(admin_uri): returned = True
if admin_uri: if vp_uri.startswith(uri) or vp_uri.startswith(admin_uri): returned = True else: self.log.info("isURICorrect: allowed URI:'%s', incorrect URI:'%s'." % ((vp_uri, admin_uri), uri))
def isURICorrect(self, uri): """ """ returned = False try: data = self.dbc.getBrowserUri() except viewpointdirect.BrowserNotPresent, e: self.log.error("isURICorrect: %s" % str(e)) else: if data: rc = simplejson.loads(data) vp_uri = rc['data'] admin_uri = self.config.get('admin_uri', None) if vp_uri.startswith(uri) o...
self.log.info("isURICorrect: current URI:'%s', correct URI:'%s'." % (vp_uri, uri))
if vp_uri.startswith(uri): returned = True else: self.log.info("isURICorrect: current URI:'%s', incorrect URI:'%s'." % (vp_uri, uri))
def isURICorrect(self, uri): """ """ returned = False try: data = self.dbc.getBrowserUri() except viewpointdirect.BrowserNotPresent, e: self.log.error("isURICorrect: %s" % str(e)) else: if data: rc = simplejson.loads(data) vp_uri = rc['data'] admin_uri = self.config.get('admin_uri', None) if vp_uri.startswith(uri) o...
done_count = 0
def do_queued_updates(self, amount=-1): """ Index <amount> entries from the indexer queue.
macro.request.include_id = incl_id
macro.request.uid_generator.include_id = incl_id
def macro_TableOfContents(macro, maxdepth=int): """
<td style="border:0">
def enabled(val): return not val and u' disabled="disabled"' or u''
</td>
def enabled(val): return not val and u' disabled="disabled"' or u''
%%s
<td style="border:0"> %%s </td>
def enabled(val): return not val and u' disabled="disabled"' or u''
avv = av["Access Vector"][:1]
avv = base_metas["Access Vector"][:1]
def buildVector(base_metas): vector = "" avset = set(['Local', 'Network', 'Adjacent Network']) acset = set(['High', 'Medium', 'Low']) auset = set(['Multiple', 'Single', 'None']) avv = av["Access Vector"][:1] if avv not in avset: return None else: vector += "AV:" + avv[0] + "/" acv = ac["Access Complexity"][:1] if acv n...
acv = ac["Access Complexity"][:1]
acv = base_metas["Access Complexity"][:1]
def buildVector(base_metas): vector = "" avset = set(['Local', 'Network', 'Adjacent Network']) acset = set(['High', 'Medium', 'Low']) auset = set(['Multiple', 'Single', 'None']) avv = av["Access Vector"][:1] if avv not in avset: return None else: vector += "AV:" + avv[0] + "/" acv = ac["Access Complexity"][:1] if acv n...
auv = au["Authentication"][:1]
auv = base_metas["Authentication"][:1]
def buildVector(base_metas): vector = "" avset = set(['Local', 'Network', 'Adjacent Network']) acset = set(['High', 'Medium', 'Low']) auset = set(['Multiple', 'Single', 'None']) avv = av["Access Vector"][:1] if avv not in avset: return None else: vector += "AV:" + avv[0] + "/" acv = ac["Access Complexity"][:1] if acv n...
assert second.acquire(timeout + 0.1)
assert second.acquire(timeout + 0.2)
def testAcquireAfterTimeout(self): """ util.lock: ExclusiveLock: acquire after timeout
if vals and addpagename:
if addpagename: result += f.listitem(1, **entryfmt)
def construct_table(macro, pagelist, metakeys, legend='', checkAccess=True, styles=dict(), addpagename=False): request = macro.request request.page.formatter = request.formatter _ = request.getText row = 0 entryfmt = {'class': 'metamatrix_entry'} # Start table request.write(macro.formatter.linebreak() + u'<div class...
result += f.listitem(0)
def construct_table(macro, pagelist, metakeys, legend='', checkAccess=True, styles=dict(), addpagename=False): request = macro.request request.page.formatter = request.formatter _ = request.getText row = 0 entryfmt = {'class': 'metamatrix_entry'} # Start table request.write(macro.formatter.linebreak() + u'<div class...
t_cell(macro, "%s: MetaValueDistribution(%s)" % (error, ",".join(args)))
t_cell(macro, "%s: MetaValueDistribution(%s)" % (error, args))
def show_error(macro, args, error): request = macro.request request.write(macro.formatter.linebreak() + u'<div class="metatable">' + macro.formatter.table(1)) request.write(macro.formatter.table_row(1)) t_cell(macro, "%s: MetaValueDistribution(%s)" % (error, ",".join(args))) request.write(macro.formatter.table_row(0))...
print gout
def checking_loop(wiki): url = wiki.host while True: #Get all new history pages with pending status info('Lookig for pages') picked_pages = wiki.getMeta('CategoryHistory, overallvalue=pending') info('Found %d pages' % len(picked_pages)) if not picked_pages: info('No pages. Sleeping') time.sleep(10) continue #go thgr...
info("Test %s failed" % testname) failed = False
passed = False
def checking_loop(wiki): url = wiki.host while True: #Get all new history pages with pending status info('Lookig for pages') picked_pages = wiki.getMeta('CategoryHistory, overallvalue=pending') info('Found %d pages' % len(picked_pages)) if not picked_pages: info('No pages. Sleeping') time.sleep(10) continue #go thgr...
content_query = super(TextSearch, self).xapian_term(request, connection) title_query = TitleSearch(self._pattern, use_re=self.use_re, case=self.case).xapian_term(request, connection) return Query(OP_OR, [title_query, content_query])
if self.use_re: return Query('') else: content_query = super(TextSearch, self).xapian_term(request, connection) title_query = TitleSearch(self._pattern, use_re=self.use_re, case=self.case).xapian_term(request, connection) return Query(OP_OR, [title_query, content_query]) def xapian_need_postproc(self): return s...
def xapian_term(self, request, connection):
try: slideNumber = int(self.request.values.get('n', 1)) if not 1 <= slideNumber <= len(self.page):
slideNumber = self.request.values.get('n', 1) if slideNumber == "all": slideNumber = None else: try: slideNumber = int(slideNumber) if not 1 <= slideNumber <= len(self.page): slideNumber = 1 except ValueError:
def setSlideNumber(self): try: slideNumber = int(self.request.values.get('n', 1)) if not 1 <= slideNumber <= len(self.page): slideNumber = 1 except ValueError: slideNumber = 1 self.slideNumber = slideNumber
except ValueError: slideNumber = 1
def setSlideNumber(self): try: slideNumber = int(self.request.values.get('n', 1)) if not 1 <= slideNumber <= len(self.page): slideNumber = 1 except ValueError: slideNumber = 1 self.slideNumber = slideNumber
start = max(first, self.slideNumber - other / 2)
start = max(first, (self.slideNumber or 1) - other / 2)
def slideLinksRange(self): """ Return range of slides to display, current centered """ other = self.maxSlideLinks - 1 # other slides except current first, last = self.first_slide(), self.last_slide() start = max(first, self.slideNumber - other / 2) end = min(start + other, last) start = max(first, end - other) return r...
return min(self.slideNumber + 1, self.last_slide())
return min((self.slideNumber or 1) + 1, self.last_slide())
def next_slide(self): return min(self.slideNumber + 1, self.last_slide())
return max(self.slideNumber - 1, self.first_slide())
return max((self.slideNumber or 1) - 1, self.first_slide())
def previous_slide(self): return max(self.slideNumber - 1, self.first_slide())
def item_language_attribtues(self):
def item_language_attributes(self):
def item_language_attribtues(self): return self.languageAttributes(self.request.content_lang)
def item_slide_title(self): return wikiutil.escape(self.page.titleAt(self.slideNumber)) def item_slide_body(self): text = self.page.bodyAt(self.slideNumber)
def item_slides(self): if self.slideNumber is None: slides = [] for n in xrange(0, len(self.page)): slides.append(slide_template % { 'slide_title' : self.item_slide_title(n + 1), 'slide_body' : self.item_slide_body(n + 1) }) return ''.join(slides) else: return slide_template % self def item_slide_title(self, number=No...
def item_slide_title(self): return wikiutil.escape(self.page.titleAt(self.slideNumber))
return "%d|%d" % (self.slideNumber, self.last_slide())
if self.slideNumber is not None: return "%d|%d" % (self.slideNumber, self.last_slide()) else: return ''
def item_counter(self): return "%d|%d" % (self.slideNumber, self.last_slide())
<html%(language_attribtues)s>
<html%(language_attributes)s>
def item_counter(self): return "%d|%d" % (self.slideNumber, self.last_slide())
<h1>%(slide_title)s</h1> <div id="content"> %(slide_body)s </div>
%(slides)s
def item_counter(self): return "%d|%d" % (self.slideNumber, self.last_slide())
<ul id="date">%(date)s</ul> <ul id="author">%(author)s</ul> <ul id="counter">%(counter)s</ul>
<ul> <li id="date">%(date)s</li> <li id="author">%(author)s</li> <li id="counter">%(counter)s</li> </ul>
def item_counter(self): return "%d|%d" % (self.slideNumber, self.last_slide())
<td style="border:0; width:1%%">
<td style="border:0;">
def enabled(val): return not val and u' disabled="disabled"' or u''
<div style="text-align:left">
<div style="text-align:%s">
def enabled(val): return not val and u' disabled="disabled"' or u''
page_url, prev_oldrev, oldrev, _("Previous change"), enabled(oldrev > 1),
page_url, "left", prev_oldrev, oldrev, _("Previous change"), enabled(oldrev > 1),
def enabled(val): return not val and u' disabled="disabled"' or u''
page_url, newrev, next_newrev, _("Next change"), enabled(newrev < currentrev), )
page_url, "right", newrev, next_newrev, _("Next change"), enabled(newrev < currentrev), )
def enabled(val): return not val and u' disabled="disabled"' or u''
class FixedFilesystemSessionStore(FilesystemSessionStore): """ Fix buggy implementation of .get() in werkzeug <= 0.5: If you try to get(somesid) and the file with the contents of sid storage does not exist or is troublesome somehow, it will create a new session with a new sid in werkzeug 0.5 original implementation. ...
_fs_transaction_suffix = '.__wz_sess' class FilesystemSessionStore(SessionStore): """Simple example session store that saves sessions in the filesystem like PHP does. .. versionchanged:: 0.6 `renew_missing` was added. Previously this was considered `True`, now the default changed to `False` and it can be explicitly...
def __repr__(self): # TODO: try to get this into werkzeug codebase return '<%s %s %s%s>' % ( self.__class__.__name__, self.sid, # we want to see sid dict.__repr__(self), self.should_save and '*' or '' )
fn = self.get_session_filename(sid) f = None
def get(self, sid): if not self.is_valid_key(sid): return self.new() fn = self.get_session_filename(sid) f = None try: try: f = open(fn, 'rb') data = load(f) except (IOError, EOFError, KeyError): # XXX check completeness/correctness # Note: we do NOT generate a new sid in case of trouble with session *contents* # IOErr...
f = open(fn, 'rb') data = load(f) except (IOError, EOFError, KeyError): data = {} finally: if f:
try: data = load(f) except Exception: data = {} finally:
def get(self, sid): if not self.is_valid_key(sid): return self.new() fn = self.get_session_filename(sid) f = None try: try: f = open(fn, 'rb') data = load(f) except (IOError, EOFError, KeyError): # XXX check completeness/correctness # Note: we do NOT generate a new sid in case of trouble with session *contents* # IOErr...
fd, temp_fname = tempfile.mkstemp(suffix='.tmp', dir=self.path)
fd, temp_fname = tempfile.mkstemp(suffix=_fs_transaction_suffix, dir=self.path)
def save(self, session): fd, temp_fname = tempfile.mkstemp(suffix='.tmp', dir=self.path) f = os.fdopen(fd, 'wb') try: dump(dict(session), f, HIGHEST_PROTOCOL) finally: f.close() filesys.chmod(temp_fname, 0666 & config.umask) # relax restrictive mode from mkstemp fname = self.get_session_filename(session.sid) # this is ...
filesys.chmod(temp_fname, 0666 & config.umask)
filesys.chmod(temp_fname, self.mode)
def save(self, session): fd, temp_fname = tempfile.mkstemp(suffix='.tmp', dir=self.path) f = os.fdopen(fd, 'wb') try: dump(dict(session), f, HIGHEST_PROTOCOL) finally: f.close() filesys.chmod(temp_fname, 0666 & config.umask) # relax restrictive mode from mkstemp fname = self.get_session_filename(session.sid) # this is ...
filesys.rename(temp_fname, fname) """ Adds functionality missing in werkzeug 0.5: getting a list of all SIDs, so that purging sessions can be implemented. """ def get_all_sids(self): """ return a list of all session ids (sids) """ import re regex = re.compile(re.escape(self.filename_template).replace( r'\%s', r'([0-9a...
filesys.rename(temp_fname, fname) """ Problem: werkzeug 0.6 uses inconsistent encoding for template and filename """ def _encode_fs(self, name): if isinstance(name, unicode): name = name.encode(sys.getfilesystemencoding() or 'utf-8') return name def get_session_filename(self, sid): sid = self._encode_fs(sid) return p...
def save(self, session): fd, temp_fname = tempfile.mkstemp(suffix='.tmp', dir=self.path) f = os.fdopen(fd, 'wb') try: dump(dict(session), f, HIGHEST_PROTOCOL) finally: f.close() filesys.chmod(temp_fname, 0666 & config.umask) # relax restrictive mode from mkstemp fname = self.get_session_filename(session.sid) # this is ...
return FixedFilesystemSessionStore(path=path, filename_template='%s', session_class=MoinSession)
return FixedFilesystemSessionStore(path=path, filename_template='%s', session_class=MoinSession, mode=0666 & config.umask)
def _store_get(self, request): path = request.cfg.session_dir try: filesys.mkdir(path) except OSError: pass return FixedFilesystemSessionStore(path=path, filename_template='%s', session_class=MoinSession)
return store.get_all_sids()
return store.list()
def get_all_session_ids(self, request): store = self._store_get(request) return store.get_all_sids()
session.modified):
session.should_save):
def finalize(self, request, session): if request.user.auth_method == 'setuid': userobj = request._setuid_real_user setuid = request.user.id else: userobj = request.user setuid = None logging.debug("finalize userobj = %r, setuid = %r" % (userobj, setuid)) cfg = request.cfg # we use different cookie names for different w...
m = self.addr_re.match(target)
m = self.rules.addr_re.match(target)
def image_emit(self, node): target = node.content text = self.get_text(node) m = self.addr_re.match(target) if m: if m.group('page_name'): # inserted anchors url = wikiutil.url_unquote(target) if target.startswith('#'): return self.formatter.anchordef(url[1:]) # default to images return self.formatter.attachment_image(...
self.request.theme.add_msg(unicode(err), "error")
self.request.theme.add_msg(wikiutil.escape(unicode(err)), "error")
def execute(self): _ = self.request.getText try: self.setSlideNumber() language = self.page.pi['language'] self.request.setContentLanguage(language) self.request.write(self.template % self) except Error, err: self.request.theme.add_msg(unicode(err), "error") self.page.send_page()
'upload_label_rename': _('Page Name'),
'upload_label_rename': _('Page name'),
def get_form_html(self, buttons_html): _ = self._ return """
return orig_feed(self, re.sub(ur'[\x00-\x08\x0b-\x19]', '?', data))
return orig_feed(self, esc(data))
def monkey_feed(self, data): return orig_feed(self, re.sub(ur'[\x00-\x08\x0b-\x19]', '?', data))