rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
try: suite = create_suite() except ImportError: if not os.path.exists('testenv'): subprocess.check_call("pip install -q -E testenv nose dtopt webtest mext.test>=0.4 coverage") site.addsitedir('testenv/Lib/site-packages') suite = create_suite()
if not os.path.exists('testenv'): subprocess.check_call("pip install -q -E testenv nose dtopt webtest mext.test>=0.4 coverage") site.addsitedir('testenv/Lib/site-packages') suite = create_suite()
def create_suite(): from mext.test_suite import TestSuite suite = TestSuite('tests', coverage='html_coverage', pkg='webob') for test in ['do-it-yourself', 'file-example', 'index', 'reference']: suite.add_doctest('../docs/' + test) map(suite.add_doctest, ['test_dec', 'test_request', 'test_response', 'multidict']) for ...
' and Val is %s\n' % request.GET.get('name'),
' and Val is %s\n' % request.str_GET.get('name'),
def simpleapp(environ, start_response): status = '200 OK' response_headers = [('Content-type','text/plain')] start_response(status, response_headers) request = Request(environ) request.remote_user = 'bob' return [ 'Hello world!\n', 'The get is %r' % request.str_GET, ' and Val is %s\n' % request.GET.get('name'), 'The la...
if self._app_iter is not None: app_iter = self._app_iter else: app_iter = [self._body]
app_iter = list(self.app_iter) self.app_iter = list(app_iter)
def copy(self): """Makes a copy of the response""" if self._app_iter is not None: app_iter = self._app_iter else: app_iter = [self._body] return self.__class__( content_type=False, status=self._status, headerlist=self._headerlist, app_iter=app_iter, conditional_response=self.conditional_response)
headerlist=self._headerlist,
headerlist=self._headerlist[:],
def copy(self): """Makes a copy of the response""" if self._app_iter is not None: app_iter = self._app_iter else: app_iter = [self._body] return self.__class__( content_type=False, status=self._status, headerlist=self._headerlist, app_iter=app_iter, conditional_response=self.conditional_response)
content_type=content_type
content_type=content_type, charset=charset
def generate_response(self, environ, start_response): if self.content_length is not None: del self.content_length headerlist = list(self.headerlist) accept = environ.get('HTTP_ACCEPT', '') if accept and 'html' in accept or '*/*' in accept: content_type = 'text/html' body = self.html_body(environ) else: content_type = '...
'uid': '1234'}
'uid': '1234', 'url': 'http://mock-brain-url/'}
... def stories(self, sort_by_state=True, locked_status=False):
context = aq_inner(self.context)
def items(self): context = aq_inner(self.context) ptool = self.tools.properties() hours_per_day = ptool.xm_properties.getProperty('hours_per_day') data = [] employees = self.get_employees() for userid in employees: empldict = {} memberinfo = self.tools.membership().getMemberInfo(userid) if memberinfo and memberinfo is ...
empldict = {}
empldict = dict(id=userid)
def items(self): context = aq_inner(self.context) ptool = self.tools.properties() hours_per_day = ptool.xm_properties.getProperty('hours_per_day') data = [] employees = self.get_employees() for userid in employees: empldict = {} memberinfo = self.tools.membership().getMemberInfo(userid) if memberinfo and memberinfo is ...
portal = self.portal_state.portal()
def projectlist(self): context = aq_inner(self.context) searchpath = '/'.join(context.getPhysicalPath()) # By default search for all projects from the given path # if the context is a project it will return itself cfilter = dict(portal_type='Project', review_state='active', path={'query': searchpath, 'navtree': False})...
review_state_id = brain.review_state
def iterationbrain2dict(self, brain): """Get a dict with info from this iteration brain. """ review_state_id = brain.review_state estimate = brain.estimate actual = brain.actual_time obj = brain.getObject() history = self.workflow.getHistoryOf('eXtreme_Iteration_Workflow', obj) completion_date = None for item in histor...
history = self.workflow.getHistoryOf('eXtreme_Iteration_Workflow', obj)
wf_id = 'eXtreme_Iteration_Workflow' wfs = self.workflow.getWorkflowsFor(obj) if len(wfs): wf_id = wfs[0].id history = self.workflow.getHistoryOf(wf_id, obj)
def iterationbrain2dict(self, brain): """Get a dict with info from this iteration brain. """ review_state_id = brain.review_state estimate = brain.estimate actual = brain.actual_time obj = brain.getObject() history = self.workflow.getHistoryOf('eXtreme_Iteration_Workflow', obj) completion_date = None for item in histor...
'Products.Poi',
'Products.Poi<2.0dev',
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
title=abbreviate(story.Title() or story.getId())))
title=abbreviate(story.Title() or story.getId(), width=80)))
def stories_to_add_to(self): value = [] for story in self.get_open_stories_in_project(): story = story.getObject() if not self.can_add_tasks(story): continue value.append( dict(iterationid=story.getPhysicalPath()[-2], uid=story.UID(), title=abbreviate(story.Title() or story.getId()))) return value
results = self.get_move_value_base(game, configuration, '--GetMoveValue') move_value = self.parse_move_value(results) if move_value is None: raise TException('failed to get move value for %s %s' % \ (game, configuration)) return GetMoveResponse(status='ok', response=move_value)
try: results = self.get_move_value_base(game, configuration, '--GetMoveValue') match = re.search(self.TUPLE_PATTERN, results) if match is None: raise GameException('failed to get move value for %s %s' % \ (game, configuration)) move_value = self.parse_move_value(match.group()) return GetMoveResponse(status='ok', respon...
def getMoveValue(self, game, configuration): results = self.get_move_value_base(game, configuration, '--GetMoveValue') move_value = self.parse_move_value(results) if move_value is None: raise TException('failed to get move value for %s %s' % \ (game, configuration)) return GetMoveResponse(status='ok', response=move_val...
results = self.get_move_value_base(game, configuration, '--GetNextMoveValues') if results is None: raise TException('failed to get move values for %s %s' % \ (game, configuration)) pattern = r'\([^,]+,\s+[^,]+,\s+[^,]+\)' move_values = [] for matched in re.findall(pattern, results): move_values.append(self.parse_move_v...
try: results = self.get_move_value_base(game, configuration, '--GetNextMoveValues') move_values = [] for matched in re.findall(self.TUPLE_PATTERN, results): move_values.append(self.parse_move_value(matched.strip())) return GetNextMoveResponse(status='ok', response=move_values) except GameException as e: return GetNextM...
def getNextMoveValues(self, game, configuration): results = self.get_move_value_base(game, configuration, '--GetNextMoveValues') if results is None: raise TException('failed to get move values for %s %s' % \ (game, configuration)) pattern = r'\([^,]+,\s+[^,]+,\s+[^,]+\)' move_values = [] for matched in re.findall(patte...
raise TException(game + ' raised an error: ' + err)
raise GameException(game + ' raised an error: ' + err)
def get_move_value_base(self, game, configuration, flag): '''Securely invokes the specified game binary with the given board configuration data. This method defends against shell injections by using Popen, which doesn't go through the shell. However, an attacker may still specify a vulnerable binary; to prevent this, w...
match = re.match(r'\(([^,]+),\s+([^,]+),\s+([^,]+)\)', result)
match = re.match(r'\(([^,]*),\s+([^,]*),\s+([^,]*)\)', result)
def parse_move_value(self, result): match = re.match(r'\(([^,]+),\s+([^,]+),\s+([^,]+)\)', result) if match is None: return None board, move, value = match.group(1, 2, 3) value = self.decode_move(int(move)) return GamestateResponse(board=board, move=move, value=value)
return None
raise GameException('malformed move value: %s' % (result,))
def parse_move_value(self, result): match = re.match(r'\(([^,]+),\s+([^,]+),\s+([^,]+)\)', result) if match is None: return None board, move, value = match.group(1, 2, 3) value = self.decode_move(int(move)) return GamestateResponse(board=board, move=move, value=value)
value = self.decode_move(int(move))
value = self.decode_value(int(value)) if not move: move = None
def parse_move_value(self, result): match = re.match(r'\(([^,]+),\s+([^,]+),\s+([^,]+)\)', result) if match is None: return None board, move, value = match.group(1, 2, 3) value = self.decode_move(int(move)) return GamestateResponse(board=board, move=move, value=value)
def decode_move(self, move):
def decode_value(self, value):
def decode_move(self, move): values = ('undecided', 'win', 'lose', 'tie') if 0 <= move < len(values): return values[move] return 'undecided'
if 0 <= move < len(values): return values[move]
if 0 <= value < len(values): return values[value]
def decode_move(self, move): values = ('undecided', 'win', 'lose', 'tie') if 0 <= move < len(values): return values[move] return 'undecided'
if game not in RequestHandler.GAMES: raise TException(name + ' is not a valid game name')
if game not in self.GAMES: raise GameException(name + ' is not a valid game name')
def verify_game(self, game): if game not in RequestHandler.GAMES: raise TException(name + ' is not a valid game name')
self.assertEqual(count, 2 + len(states))
self.assertEqual(count, len(states))
def testSimple(self): m = SO3StateManifold() s1 = SO3State(m) s1.random() s2 = s1; self.assertAlmostEqual(m.distance(s1(),s2()), 0.0, 3) s2.random() si = SpaceInformation(m) si.setStateValidityChecker(isValid) si.setup() states = vectorState() count = si.getMotionStates(s1(), s2(), states, 10, True, True) self.assert...
c.execute("CREATE TABLE %s (%s)" % (planner_table,properties))
c.execute("CREATE TABLE IF NOT EXISTS %s (%s)" % (planner_table,properties))
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('PRAGMA FOREIGN_KEYS = ON') c.execute("SELECT name FROM sqlite_master WHERE type='table'") table_names = [ str(t[0]) for t in c.fetchall...
(id INTEGER PRIMARY KEY AUTOINCREMENT, totaltime REAL, timelimit REAL, memorylimit REAL, hostname TEXT, date DATE)""")
(id INTEGER PRIMARY KEY AUTOINCREMENT, totaltime REAL, timelimit REAL, memorylimit REAL, hostname VARCHAR(512), date DATE)""")
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
(id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE)""")
(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(512) UNIQUE)""")
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
print planner_name
print "Parsing data for", planner_name
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
properties = """experimentid references experiments(id) on delete cascade, plannerid references planners(id) on delete cascade"""
properties = """experimentid references experiments(id) ON DELETE CASCADE, plannerid references planners(id) ON DELETE CASCADE"""
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
properties = properties + ', \"' + logfile.readline()[:-1].replace(' ','_') +'\"'
properties = properties + ', \"' + logfile.readline()[:-1].replace(' ','_') +'\" REAL'
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
print "create table %s (%s)" % (planner_table,properties)
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
print insert_fmt_str, run
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("select name from sqlite_master where type='table'") table_names = [ str(t[0]) for t in c.fetchall...
m = re.search('CREATE TABLE "([a-z_]*)"(.*)', line)
line = re.sub(r"[\n\r\t ]+", " ", line) m = re.search('CREATE TABLE ([a-zA-Z0-9_]*)(.*)', line)
def save_as_mysql(dbname, mysqldump): # See http://stackoverflow.com/questions/1067060/perl-to-python import re conn = sqlite3.connect(dbname) mysqldump = open(mysqldump,'w') for line in conn.iterdump(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line...
m = re.search('INSERT INTO "([a-z_]*)"(.*)', line)
m = re.search('INSERT INTO "([a-zA-Z0-9_]*)"(.*)', line)
def save_as_mysql(dbname, mysqldump): # See http://stackoverflow.com/questions/1067060/perl-to-python import re conn = sqlite3.connect(dbname) mysqldump = open(mysqldump,'w') for line in conn.iterdump(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line...
replacement['setPropagationFunction'] = ('def("setPropagationFunction", &setPropagationFunctionWrapper)', """ struct PropagatePyWrapper { PropagatePyWrapper( bp::object callable ) : callable_( callable ) {} ompl::control::PropagationResult operator()(const ompl::base::State* start, const ompl::control::Control* contro...
def __init__(self): replacement = default_replacement # A C++ call like "foo.printControl(control, std::cout)" will be replaced with # something more pythonesque: "print foo.string(control)" replacement['printControl'] = ('def("string", &__printControl)', """ std::string __printControl(%s* manifold, ompl::control::Cont...
self.assertEqual(count, len(states))
self.assertEqual(count, 2 + len(states))
def testSimple(self): m = SO3StateManifold() s1 = SO3State(m) s1.random() s2 = s1; self.assertAlmostEqual(m.distance(s1(),s2()), 0.0, 3) s2.random() si = SpaceInformation(m) si.setStateValidityChecker(isValid) si.setup() states = vectorState() count = si.getMotionStates(s1(), s2(), states, 10, True, True) self.assert...
runs = max(map(lambda x : len(stats["measurements"][x]), stats["measurements"]))
runs = min(map(lambda x : len(stats["measurements"][x]), stats["measurements"]))
def save_as_sql(fname, data): sqldump = open(fname+".sql",'w') for planner, stats in data['planner'].items(): fields = ", ".join(map(lambda x: "`" + x + "` DOUBLE NULL", stats["measurements"])) table_cmd = "DROP TABLE IF EXISTS `" + planner + "`;\nCREATE TABLE `"+planner+"` (\n" + fields + ");\n" sqldump.write(table_cm...
self.std_ns.class_('vector< ompl::geometric::PRM::Milestone* >').rename('vectorPRMMileStonePtr')
self.std_ns.class_('vector< ompl::geometric::BasicPRM::Milestone* >').rename('vectorBasicPRMMileStonePtr')
def filter_declarations(self): code_generator_t.filter_declarations(self) # rename STL vectors of certain types self.std_ns.class_('vector< int >').rename('vectorInt') self.std_ns.class_('vector< double >').rename('vectorDouble') self.std_ns.class_('vector< ompl::geometric::PRM::Milestone* >').rename('vectorPRMMileSton...
self.ompl_ns.class_('PRM').member_functions('haveSolution').exclude() self.ompl_ns.class_('PRM').member_functions('growRoadmap',
self.ompl_ns.class_('BasicPRM').member_functions('haveSolution').exclude() self.ompl_ns.class_('BasicPRM').member_functions('growRoadmap',
def filter_declarations(self): code_generator_t.filter_declarations(self) # rename STL vectors of certain types self.std_ns.class_('vector< int >').rename('vectorInt') self.std_ns.class_('vector< double >').rename('vectorDouble') self.std_ns.class_('vector< ompl::geometric::PRM::Milestone* >').rename('vectorPRMMileSton...
self.m3 = ob.RealVectorStateManifold(0) self.manifold.addSubManifold(self.m3, 0.0)
def __init__(self, env): self.manifold = ob.CompoundStateManifold() self.setup = og.SimpleSetup(self.manifold) bounds = ob.RealVectorBounds(1) bounds.setLow(0) bounds.setHigh(float(env.width) - 0.000000001) self.m1 = myManifold1() self.m1.setBounds(bounds) bounds.setHigh(float(env.height) - 0.000000001) self.m2 = myMa...
parser.add_option("-b", "--boxplot", dest="boxplot", default="boxplot.pdf",
parser.add_option("-b", "--boxplot", dest="boxplot", default=None,
def save_as_mysql(dbname, mysqldump): # See http://stackoverflow.com/questions/1067060/perl-to-python import re conn = sqlite3.connect(dbname) mysqldump = open(mysqldump,'w') for line in conn.iterdump(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line...
parser.add_option("-m", "--mysql", dest="mysqldb", default="benchmark.mysql",
parser.add_option("-m", "--mysql", dest="mysqldb", default=None,
def save_as_mysql(dbname, mysqldump): # See http://stackoverflow.com/questions/1067060/perl-to-python import re conn = sqlite3.connect(dbname) mysqldump = open(mysqldump,'w') for line in conn.iterdump(): process = False for nope in ('BEGIN TRANSACTION','COMMIT', 'sqlite_sequence','CREATE UNIQUE INDEX'): if nope in line...
c.execute('SELECT typeof(%s) FROM %s' % (a, p))
c.execute('SELECT typeof(%s) FROM %s WHERE %s IS NOT NULL' % (a, p, a))
def plot_statistics(dbname, fname): """Create a PDF file with box plots for all attributes.""" print "Generating plot..." conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('PRAGMA FOREIGN_KEYS = ON') c.execute("SELECT name FROM sqlite_master WHERE type='table'") table_names = [ str(t[0]) for t in c.fetchall() ...
(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(512), settings TEXT)""")
(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(512) NOT NULL, settings TEXT)""")
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("SELECT name FROM sqlite_master WHERE type='table'") table_names = [ str(t[0]) for t in c.fetchall...
c.execute('SELECT id FROM planners WHERE name=? AND settings="?"', (planner_name, settings,))
c.execute("SELECT id FROM planners WHERE (name=? AND settings=?)", (planner_name, settings,))
def read_benchmark_log(dbname, filenames): """Parse benchmark log files and store the parsed data in a sqlite3 database.""" conn = sqlite3.connect(dbname) c = conn.cursor() c.execute('pragma foreign_keys = on') c.execute("SELECT name FROM sqlite_master WHERE type='table'") table_names = [ str(t[0]) for t in c.fetchall...
cairo_size = self.p2c_width( tk_font.config()['size'])
cairo_size = self.p2c_width(abs(tk_font.config()['size']))
def _compute_cairo_font_size( self, tk_font, text=""): if text: test_string = text else: test_string = string.ascii_letters + string.punctuation tk_length = self.p2c_width( tk_font.measure( test_string)) cairo_size = self.p2c_width( tk_font.config()['size']) self.context.set_font_size( cairo_size) for i in range(2): # ...
if valid == ERROR:
if valid == ERROR or valid == PARTIAL:
def _checkValidity(self):
credit = transactions.extra(select=extra).filtervalues('time').annotate(Sum('amount')).order_by('time')
credit = transactions.extra(select=extra).values('time').annotate(Sum('amount')).order_by('time')
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.filter(account=account,transfer=False) else: transactions = Transaction.objects.filter(account__user=user,transfer=False) # Day of the week if time == 'day': extra = {'time': ...
print keys
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.filter(account=account,transfer=False) else: transactions = Transaction.objects.filter(account__user=user,transfer=False) # Day of the week if time == 'day': extra = {'time': ...
}[timekey]
}[int(timekey)]
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.filter(account=account,transfer=False) else: transactions = Transaction.objects.filter(account__user=user,transfer=False) # Day of the week if time == 'day': extra = {'time': ...
values.append(currency(total[timekey]))
values.append(currency(total[timekey], sign=1))
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.filter(account=account,transfer=False) else: transactions = Transaction.objects.filter(account__user=user,transfer=False) # Day of the week if time == 'day': extra = {'time': ...
extra = {'time': 'CONCAT(YEAR(`date`), MONTH(`date`))'}
raise ValueError, time + ' is not a valid time value'
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.select_related().filter(account=account,transfer=False) else: transactions = Transaction.objects.select_related().filter(account__user=user,transfer=False,account__track_balanc...
credit = transactions.extra(select=extra).values('time', 'account__id').annotate(Sum('amount')).order_by('time')
credit = transactions.extra(select=extra).values('time', 'account__id').annotate(Sum('amount')).order_by('date')
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.select_related().filter(account=account,transfer=False) else: transactions = Transaction.objects.select_related().filter(account__user=user,transfer=False,account__track_balanc...
times.sort()
def net_worth_by_time(user, time=None, account=None): if type(account) is Account and account.user is user: transactions = Transaction.objects.select_related().filter(account=account,transfer=False) else: transactions = Transaction.objects.select_related().filter(account__user=user,transfer=False,account__track_balanc...
except:
except (InvalidOperation, TypeError):
def save(self, instance=None): # Check the instance we've been given (if any) if instance is None: tr = Transaction() elif isinstance(instance, Transaction): tr = instance else: raise TypeError("instance is not a Transaction")
def update_balance(self):
def update_balance(self, all=False):
def update_balance(self): """ Updates the balance of the account for all the transactions """ # Only update the balance if we're tracking the balance for this account if (self.track_balance == True): b = 0; transactions = Transaction.objects.filter(account=self,date__gt=self.balance_updated) for t in transactions: if ...
Updates the balance of the account for all the transactions
Updates the balance of the account Arguments: all -- whether to update using all transactions or just since last updated
def update_balance(self): """ Updates the balance of the account for all the transactions """ # Only update the balance if we're tracking the balance for this account if (self.track_balance == True): b = 0; transactions = Transaction.objects.filter(account=self,date__gt=self.balance_updated) for t in transactions: if ...
b = 0; transactions = Transaction.objects.filter(account=self,date__gt=self.balance_updated)
transactions = Transaction.objects.filter(account=self) if (all == False): transactions.filter(date_created__gt=self.balance_updated) b = self.balance; else: b = 0
def update_balance(self): """ Updates the balance of the account for all the transactions """ # Only update the balance if we're tracking the balance for this account if (self.track_balance == True): b = 0; transactions = Transaction.objects.filter(account=self,date__gt=self.balance_updated) for t in transactions: if ...
for t in transactions: if t.credit: b += t.amount else: b -= t.amount self.balance = b; self.balance_updated = datetime.now() self.save()
if (transactions): for t in transactions: if t.credit: b += t.amount else: b -= t.amount self.balance = b; self.balance_updated = datetime.now() self.save()
def update_balance(self): """ Updates the balance of the account for all the transactions """ # Only update the balance if we're tracking the balance for this account if (self.track_balance == True): b = 0; transactions = Transaction.objects.filter(account=self,date__gt=self.balance_updated) for t in transactions: if ...
tags = Payee.objects.filter(name__icontains=request.GET['q']).order_by('name')
ts = Payee.objects.select_related().filter(name__icontains=request.GET['q'], transaction__account__user=request.user).distinct().order_by('name')
def get_payee_suggestions(request): if not request.GET['q']: return HttpResponseBadRequest() tags = Payee.objects.filter(name__icontains=request.GET['q']).order_by('name') response = [] for t in tags: response.append((t.id, t.name)) return HttpResponse(json.dumps(response), content_type='application/javascript; char...
response = [] for t in tags: response.append((t.id, t.name))
response = [(t.id, t.name) for t in ts]
def get_payee_suggestions(request): if not request.GET['q']: return HttpResponseBadRequest() tags = Payee.objects.filter(name__icontains=request.GET['q']).order_by('name') response = [] for t in tags: response.append((t.id, t.name)) return HttpResponse(json.dumps(response), content_type='application/javascript; char...
transactions = Transaction.objects.filter(taglink__id__isnull=True).order_by('-date')
transactions = Transaction.objects.filter(taglink__id__isnull=True, account__user=request.user).order_by('-date')
def index(request): transactions = Transaction.objects.filter(taglink__id__isnull=True).order_by('-date') paginator = Paginator(transactions, 20) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: transactions = paginator.page(page) except (EmptyPage, InvalidPage): transactions = paginato...
tags = Tag.objects.filter(name__icontains=request.GET['q'], transaction__account__user=request.user).order_by('name')
tags = Tag.objects.distinct().filter(name__icontains=request.GET['q'], transaction__account__user=request.user).order_by('name')
def get_tag_suggestions(request): if 'q' not in request.GET or not request.GET['q']: return HttpResponseBadRequest() tags = Tag.objects.filter(name__icontains=request.GET['q'], transaction__account__user=request.user).order_by('name') response = [t.name for t in tags] return HttpResponse(json.dumps(response), conten...
if not user.pk in Account.USER_ACCOUNTS.keys(): Account.USER_ACCOUNTS.update({user.pk: Account.objects.filter(user=user).order_by('name')}) return Account.USER_ACCOUNTS[user.pk]
return Account.objects.filter(user=user).order_by('name') @staticmethod def invalidate_cache(**kwargs): if 'instance' in kwargs.keys() and 'sender' in kwargs.keys() and kwargs['sender'] is Account: key = 'template.cache.accounts_block.%s' % (md5_constructor(urlquote(kwargs['instance'].user.username)).hexdigest(),) cac...
def get_for_user(user): if not user.pk in Account.USER_ACCOUNTS.keys(): Account.USER_ACCOUNTS.update({user.pk: Account.objects.filter(user=user).order_by('name')}) return Account.USER_ACCOUNTS[user.pk]
kwargs['instance'].account.update_balance(False)
inst = kwargs['instance'] if 'created' in kwargs and kwargs['created']: inst.account.update_balance(False) else: inst.account.update_balance(True)
def on_save(**kwargs): if 'instance' in kwargs.keys() and 'sender' in kwargs.keys() and kwargs['sender'] is Transaction: kwargs['instance'].account.update_balance(False)
if type( what ) is str:
if not isinstance( what, list ) or isinstance( what, N.ndarray):
def removeRes( self, what ): """ Remove all atoms with a certain residue name.
if type( what ) is int: what = [ what ] if isinstance(what, list) or isinstance( what, N.ndarray):
if type( what[0] ) is int:
def removeRes( self, what ): """ Remove all atoms with a certain residue name.
if model.atoms.get( k, default=0, update=False ) in \ (0,None):
a = model.atoms.get( k, default=0, update=False ) if (a is 0) or (a is None):
def update( self, model, source, skipRes=None, updateMissing=0, force=0, headPatterns=[]): """ Update empty or missing fields of model from the source. The model will be connected to the source via model.source. Profiles that are derived from the source are labeled 'changed'=0. The same holds for coordinates (xyzChange...
r = self.fastaRecordFromId( db, i['pdb'] )
r = self.fastaRecordFromId( db, i['pdb'], i['chain'] )
def fastaFromIds( self, db, id_lst ): """ Use:: fastaFromIds( id_lst, fastaOut ) -> { str: Bio.Fasta.Record }
return N.average(rms)[0], 0.0
return N.average(rms), 0.0
def avgRmsd( self, cluster, aMask=None, threshold=0. ): """ Claculate the average pairwise rmsd (in Angstrom) for members of a cluter.
self.save()
else: item_to_modify.save()
def remove_item(self, chosen_item_id, number_removed): item_to_modify = self.cartitem_set.get(id = chosen_item_id) item_to_modify.quantity -= number_removed if item_to_modify.quantity <= 0: item_to_modify.delete() self.save()
form_initialdata.send(self.__class__, form=self, initial=initial, contact = kwargs.get('contact', None))
form_initialdata.send(ContactInfoForm, form=self, initial=initial, contact = kwargs.get('contact', None))
def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) form_initialdata.send(self.__class__, form=self, initial=initial, contact = kwargs.get('contact', None)) kwargs['initial'] = initial
log.info('Sending form_init signal: %s', self.__class__) form_init.send(self.__class__, form=self)
log.info('Sending form_init signal: %s', ContactInfoForm) form_init.send(ContactInfoForm, form=self)
def __init__(self, *args, **kwargs): initial = kwargs.get('initial', {}) form_initialdata.send(self.__class__, form=self, initial=initial, contact = kwargs.get('contact', None)) kwargs['initial'] = initial
if params[0] == 'cancel': print vars.getvalue('command') self._show_dialog = 0 @event('dialog/submit')
@event('form/submit')
def on_click(self, event, params, vars=None): if params[0] == 'add': self._editing = len(self._tasks) self._show_dialog = 1 if params[0] == 'edit': self._editing = int(params[1]) self._show_dialog = 1 if params[0] == 'del': self._tasks.pop(int(params[1])) self._error = backend.write_crontab(self._others +\ self._tasks)...
if params[0] == 'dlgEdit' and\ vars.getvalue('action', '') == 'OK': print self._tab if self._tab == 0: task_str = ' '.join((
if params[0] == 'frmAdvanced' and\ vars.getvalue('action') == 'OK': task_str = ' '.join((
def on_submit(self, event, params, vars=None): if params[0] == 'dlgEdit' and\ vars.getvalue('action', '') == 'OK': print self._tab if self._tab == 0: task_str = ' '.join(( vars.getvalue('m').replace(' ', '') or '*', vars.getvalue('h').replace(' ', '') or '*', vars.getvalue('dom').replace(' ', '') or '*', vars.getvalue(...
task_str += '\t' + vars.getvalue('command') try: new_task = backend.Task(task_str) except: self._error = "Error: Wrong options." self._editing = -1 return 1 if self._editing < len(self._tasks): self._tasks[self._editing] = new_task else: self._tasks.append(new_task) self._error = backend.write_crontab(self._others +\ s...
task_str += '\t' + vars.getvalue('command') try: new_task = backend.Task(task_str) except: self._error = "Error: Wrong options." self._editing = -1 return 1 if self._editing < len(self._tasks): self._tasks[self._editing] = new_task else: self._tasks.append(new_task) self._error = backend.write_crontab(self._others +\ s...
def on_submit(self, event, params, vars=None): if params[0] == 'dlgEdit' and\ vars.getvalue('action', '') == 'OK': print self._tab if self._tab == 0: task_str = ' '.join(( vars.getvalue('m').replace(' ', '') or '*', vars.getvalue('h').replace(' ', '') or '*', vars.getvalue('dom').replace(' ', '') or '*', vars.getvalue(...
self._tab = 0
def on_submit(self, event, params, vars=None): if params[0] == 'dlgEdit' and\ vars.getvalue('action', '') == 'OK': print self._tab if self._tab == 0: task_str = ' '.join(( vars.getvalue('m').replace(' ', '') or '*', vars.getvalue('h').replace(' ', '') or '*', vars.getvalue('dom').replace(' ', '') or '*', vars.getvalue(...
UI.MiniButton(text='Select',onclick="form", action='OK', form='frmUsers')
UI.MiniButton(text='Select',onclick='form', action='OK', form='frmUsers')
def get_default_ui(self): user_sel = [UI.SelectOption(text = x, value = x, selected = True if x == self._user else False) for x in backend.get_all_users()] topbox = UI.FormBox(UI.HContainer(UI.Label(text='User: '), UI.Select(*user_sel, name='users'), UI.MiniButton(text='Select',onclick="form", action='OK', form='frmUse...
self.config.get('server').shutdown()
self.config.get('server').stop()
def stop(self): self.config.get('server').shutdown()
colspan=3 ) ), UI.LayoutTableRow(
width = '60%' ),
def get_ui_temp_minutes(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='minutes'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='minutes'), colspan=2 ) ), UI.LayoutTableRow( UI.Layout...
colspan=1
width = '20%'
def get_ui_temp_minutes(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='minutes'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='minutes'), colspan=2 ) ), UI.LayoutTableRow( UI.Layout...
colspan=2
width = '20%'
def get_ui_temp_minutes(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='minutes'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='minutes'), colspan=2 ) ), UI.LayoutTableRow( UI.Layout...
colspan=3 ) ), UI.LayoutTableRow(
width = '60%' ),
def get_ui_temp_hours(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='hours'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='hours'), colspan=2 ) ), UI.LayoutTableRow( UI.LayoutTableC...
colspan=1
width = '20%'
def get_ui_temp_hours(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='hours'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='hours'), colspan=2 ) ), UI.LayoutTableRow( UI.LayoutTableC...
colspan=2
width = '20%'
def get_ui_temp_hours(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='hours'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='hours'), colspan=2 ) ), UI.LayoutTableRow( UI.LayoutTableC...
colspan=1
def get_ui_temp_hours(self): temp_table = UI.LayoutTable( UI.LayoutTableRow( UI.LayoutTableCell( UI.Label(text='Start task every'), colspan=3 ) ), UI.LayoutTableRow( UI.LayoutTableCell( UI.TextInput(name='hours'), colspan=1 ), UI.LayoutTableCell( UI.Label(text='hours'), colspan=2 ) ), UI.LayoutTableRow( UI.LayoutTableC...
ss = os.listdir('plugins')
def load_all(): global plugins ss = os.listdir('plugins') sys.path.insert(0, 'plugins') ss.sort() for s in ss: if '.py' in s: __import__(os.path.splitext(s)[0], None, None, ['']) log.info('Plugins', 'Found plugin ' + s) for plugin in PluginMaster.__subclasses__(): p = plugin() plugins.append(p) p._on_load() for a i...
if '.py' in s: __import__(os.path.splitext(s)[0], None, None, ['']) log.info('Plugins', 'Found plugin ' + s)
__import__(os.path.splitext(s)[0], None, None, ['']) log.info('Plugins', 'Found plugin ' + s)
def load_all(): global plugins ss = os.listdir('plugins') sys.path.insert(0, 'plugins') ss.sort() for s in ss: if '.py' in s: __import__(os.path.splitext(s)[0], None, None, ['']) log.info('Plugins', 'Found plugin ' + s) for plugin in PluginMaster.__subclasses__(): p = plugin() plugins.append(p) p._on_load() for a i...
UI.ProgressBar(value=ru, max=rt, width=100) if rt != '0' else None,
UI.ProgressBar(value=ru, max=rt, width=100) if int(rt) != 0 else None,
def get_ui(self): ru, rt = self.get_swap() w = UI.Widget( UI.HContainer( UI.Image(file='/dl/loadavg/widget_swap.png'), UI.Label(text='Swap:', bold=True), UI.ProgressBar(value=ru, max=rt, width=100) if rt != '0' else None, UI.Label(text="%sM / %sM"%(ru,rt)) ) ) return w
f.write(Jobs[j].CronLine() + '\n')
if j.Time != '': f.write(Jobs[j].CronLine() + '\n')
def Commit(): global Jobs Init() f = open('/etc/cron.d/ajenti-backup', 'w') f.write('SHELL=/bin/sh\n') for j in Jobs: f.write(Jobs[j].CronLine() + '\n') f.close() return 'Done'
utils.shell_bg('yum repolist', output='/tmp/ajenti-yum-output', deleteout=True)
utils.shell_bg('yum check-update', output='/tmp/ajenti-yum-output', deleteout=True)
def get_lists(self): utils.shell_bg('yum repolist', output='/tmp/ajenti-yum-output', deleteout=True)
if s[0].startwith('===='):
if s[0].startswith('===='):
def search(self, q, st): ss = utils.shell('yum -q -C search %s' % q).splitlines() a = st.full r = {} for s in ss: s = s.split() if s[0].startwith('===='): continue else: r[s[0]] = apis.pkgman.Package() r[s[0]].name = s[0] r[s[0]].description = ' '.join(s[2:]) r[s[0]].state = 'removed' if a.has_key(s[0]) and a[s[0]].sta...
tabbar.add("Advanced", self.get_ui_advanced(t))
def get_ui_edit(self, t): tabbar = UI.TabControl(active=self._tab) #tabbar.add("Advanced", self.get_ui_advanced(t)) tabbar.add("Special", self.get_ui_special(t)) dlg = UI.DialogBox( tabbar, title='Edit task', id='dlgEdit', hideok=True, hidecancel=True ) return dlg
), UI.LayoutTableRow( UI.Button(text='Ok', id='ok_advanced'), UI.Button(text='Cancel', id='cancel'),
def get_ui_advanced(self, t): adv_table = UI.LayoutTable( UI.LayoutTableRow( UI.Label(text='Minutes'), UI.TextInput(name='m', value=t.m) ), UI.LayoutTableRow( UI.Label(text='Hours'), UI.TextInput(name='h', value=t.h) ), UI.LayoutTableRow( UI.Label(text='Days of month'), UI.TextInput(name='dom', value=t.dom) ), UI.Layou...
spc_table = UI.LayoutTable(UI.LayoutTableRow( UI.Radio(value="reboot", text="reboot", name="special", checked=True), UI.Radio(value="hourly", text="hourly", name="special")), UI.LayoutTableRow( UI.Radio(value="daily", text="daily", name="special"), UI.Radio(value="weekly", text="weekly", name="special")), UI.LayoutTabl...
spc_table = UI.LayoutTable( UI.LayoutTableRow( UI.Radio(value="reboot", text="reboot", name="special", checked=True), UI.Radio(value="hourly", text="hourly", name="special")), UI.LayoutTableRow( UI.Radio(value="daily", text="daily", name="special"), UI.Radio(value="weekly", text="weekly", name="special")), UI.LayoutTab...
def get_ui_special(self, t): spc_table = UI.LayoutTable(UI.LayoutTableRow( UI.Radio(value="reboot", text="reboot", name="special", checked=True), UI.Radio(value="hourly", text="hourly", name="special")), UI.LayoutTableRow( UI.Radio(value="daily", text="daily", name="special"), UI.Radio(value="weekly", text="weekly", na...
dist = open('/etc/issue').read().strip('\n\t ').split()[0]
dist = 'Arch' if 'Arch' in open('/etc/issue').read() else 'unknown'
def detect_platform(): if platform.system() != 'Linux': return platform.system().lower() dist = '' (maj, min, patch) = platform.python_version_tuple() if (maj * 10 + min) >= 26: dist = platform.linux_distribution()[0] else: dist = platform.dist()[0] if dist == '': try: dist = open('/etc/issue').read().strip('\n\t ')....
self.set('ajenti', 'platform', pl)
def save(self): with open(self.filename, 'w') as f: self.write(f) self.set('ajenti', 'platform', pl)
lt = UI.LayoutTable( UI.LayoutTableRow(frm, UI.Spacer(width=40), frmr), UI.LayoutTableRow( UI.Button(text='Run', form='frmRun', onclick='form'), UI.Spacer(width=40), UI.Button(text='Repeat', form='frmRecent', onclick='form')
lt = UI.HContainer( frm, UI.Button(text='Run', form='frmRun', onclick='form'), UI.VContainer( UI.Label(text='Repeat:'), frmr
def get_default_ui(self): recent = [UI.SelectOption(text=x, value=x) for x in self._recent] log = UI.CustomHTML(enquote(self._process.output + self._process.errors))
for base in [base for base in bases if hasattr(base, '_implements')]:
for base in [base for base in new_class.mro()[1:] if hasattr(base, '_implements')]:
def maybe_init(self, plugin_manager, init=init, cls=new_class): if plugin_manager.instance_get(cls) is None: # Plugin is just created if init: try: init(self) except: raise plugin_manager.instance_set(cls, self)
ajentid = AjentiDaemon()
ajentid = AjentiDaemon('/tmp/ajenti.pid')
def usage(): print """
img = 'none'
img = '0'
def get_ui(self): panel = UI.PluginPanel(UI.Label(text=('Uptime: ' + get_uptime())), title='Power Management', icon='/dl/power/icon.png')