rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
name = name.replace("'", "'\\''") name = "'" + name + "'"
def move(f, t, name): com = "mv " + f + "/" + name + " " + t + "/" if os.path.exists(f + "/" + name + ".cfg"): com = "mv " + f + "/" + name + ".cfg " + t + "/" shell(com)
self.tempdir = None
def __init__(self, parser, message): self.line = parser.parser_line self.wml_line = parser.last_wml_line self.message = message self.preprocessed = parser.preprocessed self.tempdir = None
if self.tempdir: output = self.tempdir
if self.temp_dir: output = self.temp_dir
def preprocess(self, defines): """ Call wesnoth --preprocess to get preprocessed WML which we can subsequently parse.
if options.keep_temp: p.tempdir = options.keep_temp
if options.keep_temp: p.temp_dir = options.keep_temp
def test(input, expected, note): test2(input, expected, note, lambda p: p.root.debug())
def __init__(self, wesnoth_exe):
def __init__(self, wesnoth_exe, userdir, datadir):
def __init__(self, wesnoth_exe): self.images = {} self.paths_per_campaign = {} self.ipaths = {} self.notfound = {} self.id = 0 self.verbose = 0 self.datadir = get_datadir(wesnoth_exe) self.userdir = get_userdir(wesnoth_exe)
self.datadir = get_datadir(wesnoth_exe) self.userdir = get_userdir(wesnoth_exe)
self.datadir = datadir self.userdir = userdir if not self.datadir: self.datadir = get_datadir(wesnoth_exe) if not self.userdir: self.userdir = get_userdir(wesnoth_exe)
def __init__(self, wesnoth_exe): self.images = {} self.paths_per_campaign = {} self.ipaths = {} self.notfound = {} self.id = 0 self.verbose = 0 self.datadir = get_datadir(wesnoth_exe) self.userdir = get_userdir(wesnoth_exe)
if self.verbose:
if 1:
def copy_and_color_images(self, target_path): for iid in self.images.keys(): opath = os.path.join(target_path, "pics", iid) try: os.makedirs(os.path.dirname(opath)) except OSError: pass
Popen([os.path.join(am_dir, "../unit_tree/TeamColorizer"), src, path + "/" + imgurl])
def w(x): f.write(x + "\n")
for i in range(len(res)): for j in range(len(res[i])): sys.stderr.write("Line " + str(i) + " match " + str(j) + " : " + res[i][j] + "\n")
for i, val in res: for j, sub_val in val: sys.stderr.write("Line %s match %s: %s\n" % (i, j, sub_val))
def debug_dump(data, res): """Show the data the regex retrieved from a match.
for i in range(len(res)):
for i in res:
def create_config_table(data): """Creates a table for data in a config table.
result += "| " + res[i][0] + "\n" result += "| [[GUIVariable if not res[i][2]:
result += "| " + i[0] + "\n" result += "| [[GUIVariable if not i[2]:
def create_config_table(data): """Creates a table for data in a config table.
result += "| " + res[i][2] + "\n" result += "| " + format(res[i][3]) + "\n"
result += "| " + i[2] + "\n" result += "| " + format(i[3]) + "\n"
def create_config_table(data): """Creates a table for data in a config table.
for i in range(len(res)):
for i in res:
def create_formula_table(data): """Creates a table for data in a formula table.
result += "| " + res[i][0] + "\n" result += "| " + res[i][1] + "\n" result += "| " + format(res[i][2]) + "\n"
result += "| " + i[0] + "\n" result += "| " + i[1] + "\n" result += "| " + format(i[2]) + "\n"
def create_formula_table(data): """Creates a table for data in a formula table.
for i in range(len(res)):
for i in res:
def create_variable_types_table(data): """Creates a table for the variable types."""
result += '| <span id="' + res[i][0] + '">' + res[i][0] + '</span>\n' result += "| " + format(res[i][1]) + "\n"
result += '| <span id="' + i[0] + '">' + i[0] + '</span>\n' result += "| " + format(i[1]) + "\n"
def create_variable_types_table(data): """Creates a table for the variable types."""
for i in range(len(res)):
for i in res:
def create_widget_overview_table(data): """Creates a table for all available widgets.""" #matches a line like # Button A push button. variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += "| " + '<span id="' + res[i][0].lower() + "\">" result += re.sub(r'_', ' ', res[i][0])
result += "| " + '<span id="' + i[0].lower() + "\">" result += re.sub(r'_', ' ', i[0])
def create_widget_overview_table(data): """Creates a table for all available widgets.""" #matches a line like # Button A push button. variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += res[i][0]
result += i[0]
def create_widget_overview_table(data): """Creates a table for all available widgets.""" #matches a line like # Button A push button. variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += "| " + format(res[i][1]) + "\n"
result += "| " + format(i[1]) + "\n"
def create_widget_overview_table(data): """Creates a table for all available widgets.""" #matches a line like # Button A push button. variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
for i in range(len(res)):
for i in res:
def create_window_overview_table(data): """Creates a table for all available windows.""" #matches a line like # Addon_connect The dialog to connect to the addon server variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += "| " + re.sub(r'_', ' ', res[i][0])
result += "| " + re.sub(r'_', ' ', i[0])
def create_window_overview_table(data): """Creates a table for all available windows.""" #matches a line like # Addon_connect The dialog to connect to the addon server variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += res[i][0]
result += i[0]
def create_window_overview_table(data): """Creates a table for all available windows.""" #matches a line like # Addon_connect The dialog to connect to the addon server variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
result += "| " + format(res[i][1]) + "\n"
result += "| " + format(i[1]) + "\n"
def create_window_overview_table(data): """Creates a table for all available windows.""" #matches a line like # Addon_connect The dialog to connect to the addon server variable = "(?:[a-z]|[A-Z])(?:[a-z]|[A-Z]|[0-9]|_)*" regex = re.compile(" *(" + variable + ") +(.*)\n") res = regex.findall(data)
for i in range(len(res)):
for i in res:
def create_container_table(data): """Creates a table for a container.""" print "The container table is deprecated, use the grid instead.\n"
if not res[i][1]:
if not i[1]:
def create_container_table(data): """Creates a table for a container.""" print "The container table is deprecated, use the grid instead.\n"
result += "| " + res[i][1] + " " if not res[i][3]:
result += "| " + i[1] + " " if not i[3]:
def create_container_table(data): """Creates a table for a container.""" print "The container table is deprecated, use the grid instead.\n"
result += "(" + res[i][3] + ")\n" result += "| " + res[i][2] + "\n" if not res[i][0]:
result += "(" + i[3] + ")\n" result += "| " + i[2] + "\n" if not i[0]:
def create_container_table(data): """Creates a table for a container.""" print "The container table is deprecated, use the grid instead.\n"
result += "| " + re.sub(r'@\*', "\n*", res[i][4]) + "\n"
result += "| " + re.sub(r'@\*', "\n*", i[4]) + "\n"
def create_container_table(data): """Creates a table for a container.""" print "The container table is deprecated, use the grid instead.\n"
for i in range(len(res)): result += "|-\n| " + "&nbsp;" * len(res[i][0]) * 8 if not res[i][1]:
for i in res: result += "|-\n| " + "&nbsp;" * len(i[0]) * 8 if not i[1]:
def create_dialog_widgets_table(data): """Creates a table for the widgets in a dialog."""
result += res[i][1] if not res[i][2]:
result += i[1] if not i[2]:
def create_dialog_widgets_table(data): """Creates a table for the widgets in a dialog."""
result += " (" + res[i][2] + ")\n" result += "| " + "[[GUIToolkitWML if res[i][4] == "m":
result += " (" + i[2] + ")\n" result += "| " + "[[GUIToolkitWML if i[4] == "m":
def create_dialog_widgets_table(data): """Creates a table for the widgets in a dialog."""
result += "| " + format(res[i][5]) + "\n"
result += "| " + format(i[5]) + "\n"
def create_dialog_widgets_table(data): """Creates a table for the widgets in a dialog."""
fd = open(output_directory + file, "w") for i in range(len(data_list)): fd.write(data_list[i][1]) fd.close()
with open(output_directory + file, "w") as fd: for i in data_list: fd.write(i[1])
def create_output(): """Generates the output"""
file = open(name, "r") data = file.read() file.close()
with open(name, "r") as file: data = file.read()
def process_file(name): """Processes all wiki blocks (if any) of a file."""
for i in range(len(res)):
for i in res:
def process_file(name): """Processes all wiki blocks (if any) of a file."""
current_block = res[i][0] section = reindent(res[i][1])
current_block = i[0] section = reindent(i[1])
def process_file(name): """Processes all wiki blocks (if any) of a file."""
file = open(name, "r") data = file.read() file.close()
with open(name, "r") as file: data = file.read()
def process_file_macros(name): """Processes all wiki macro blocks (if any) of a file."""
for i in range(len(res)):
for i in res:
def process_file_macros(name): """Processes all wiki macro blocks (if any) of a file."""
current_block = res[i][0] section = reindent(res[i][1])
current_block = i[0] section = reindent(i[1])
def process_file_macros(name): """Processes all wiki macro blocks (if any) of a file."""
"0: failer::MyException thrown at tests/Failer.cc:7 " +
"0: failer::MyException thrown at tests/Failer.cc:29 " +
def testValue(self): """Check that the exception value is a proper SWIGged C++ exception with appropriate message.""" try: self.x.fail() except Exception, e: self.assert_(e is not None) self.assertEqual(len(e.args), 1) self.assert_(isinstance(e, Exception)) self.assert_(isinstance(e, lsst.pex.exceptions.LsstException))...
self.assertEqual(t[0]._line, 7)
self.assertEqual(t[0]._line, 29)
def testTraceback(self): """Check that the traceback is accessible and correct.""" try: self.x.fail() except lsst.pex.exceptions.LsstCppException, e: t = e.args[0].getTraceback() self.assert_(len(t), 1) self.assert_(isinstance(t[0], lsst.pex.exceptions.Tracepoint)) self.assertEqual(t[0]._file, "tests/Failer.cc") self.a...
out = os.path.join(destpath, os.path.basename(path))
out = os.path.join(destpath, "ui_strings-%s.js" % os.path.basename(path)[:-3])
def _process_dir(dirpath, destpath): files = _find_pofiles(dirpath) for path in files: out = os.path.join(destpath, os.path.basename(path)) outfd = codecs.open(out, "w", encoding="utf_8_sig") process_file(path, outfd) outfd.close()
process_file(path, outfd)
_process_file(path, outfd)
def _process_dir(dirpath, destpath): files = _find_pofiles(dirpath) for path in files: out = os.path.join(destpath, os.path.basename(path)) outfd = codecs.open(out, "w", encoding="utf_8_sig") process_file(path, outfd) outfd.close()
elif resource.startswidth("../"): while resource.startswith("../"): pos = resource.find("/", 3) if pos > -1: resource = resource[pos:] else: resource = ""
def get_resources(os_path, web_path, file_name): resources = [] with open(os.path.join(os_path, file_name), 'r') as f: content = f.read() for match in _re_resource.finditer(content): resource = filter(bool, match.groups())[0] if resource.startswith("/"): pass elif resource.startswith("./"): resource = web_path + resour...
def process_file(inpath, outfd):
def _process_file(inpath, outfd):
def process_file(inpath, outfd): lines = [p["msgstr"] for p in dfstrings.get_po_strings(inpath) if "scope" in p and "dragonfly" in p["scope"] ] bad_escaped = dfstrings.get_strings_with_bad_escaping(lines) if bad_escaped: print "error: %s contains strings with bad escaping: %s" % (inpath, bad_escaped) return 1 bad_for...
line = line.strip().lower()
line_tc = line.strip() line = line_tc.lower()
def main(): if (len(sys.argv) < 3 or sys.argv[1] == "-h"): usage() sgml = codecs.open(sys.argv[1], "r", "utf-8") prefix = sys.argv[2] doc_pattern = re.compile('.* docid="([^"]*).*"') seg_pattern = re.compile('.* id="([^"]*)".*') ref_sets = [] cur_ref_set = [] cur_doc = "" cur_seg = "" cur_txt = "" for line in sgml...
cur_txt = re.sub("<[^>]*>", "", line)
cur_txt = re.sub("<[^>]*>", "", line_tc)
def main(): if (len(sys.argv) < 3 or sys.argv[1] == "-h"): usage() sgml = codecs.open(sys.argv[1], "r", "utf-8") prefix = sys.argv[2] doc_pattern = re.compile('.* docid="([^"]*).*"') seg_pattern = re.compile('.* id="([^"]*)".*') ref_sets = [] cur_ref_set = [] cur_doc = "" cur_seg = "" cur_txt = "" for line in sgml...
localcontext['company'] = user.company.id
localcontext['company'] = user.company
def parse(self, report, objects, datas, localcontext=None): user = self.pool.get('res.user').browse(Transaction().user) if localcontext is None: localcontext = {} localcontext['company'] = user.company.id return super(CompanyReport, self).parse(report, objects, datas, localcontext=localcontext)
self.assertRaises(Exception, test_view('company'))
test_view('company')
def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('company'))
r = self.renderer(assignment=classic.Assignment(template='base_view', macro='main'))
r = self.renderer(assignment=classic.Assignment(template='base_view', macro='content-core'))
def testRenderClassicPortlet(self): r = self.renderer(assignment=classic.Assignment(template='base_view', macro='main')) r.render()
self.context.restrictedTraverse(addview)
self.context.restrictedTraverse(str(addview))
def check_permission(p): addview = p.addview if not addview: return False
if d.bozo == 1 and not isinstance(d.get('bozo_exception'),
if getattr(d, 'bozo', 0) == 1 and not isinstance(d.get('bozo_exception'),
def _retrieveFeed(self): """do the actual work and try to retrieve the feed""" url = self.url if url!='': self._last_update_time_in_minutes = time.time()/60 self._last_update_time = DateTime() d = feedparser.parse(url) if d.bozo == 1 and not isinstance(d.get('bozo_exception'), ACCEPTED_FEEDPARSER_EXCEPTIONS): self._loa...
def _error_formatter(self, error):
def _error_formatter(error):
def _error_formatter(self, error): #TODO move to basecontroller ? """ FormEncode error formating.""" return """<div id="error-message"><img src="/images/exclamation.png"/> %s</div>""" % ( htmlfill.html_quote(error))
test_v_member = VoluntaryMemberData.john_smith()
test_v_member = VoluntaryMemberData.JohnSmith()
def test_inherinting(self): """ Test that `VoluntaryMember` model inherit from `Person` model.""" test_v_member = VoluntaryMemberData.john_smith() person = meta.Session.query(model.Person).filter_by(last_name=test_v_member.last_name).one() v_member = meta.Session.query(model.VoluntaryMember).filter_by(last_name=test_v_...
def denial_handler():
def denial_handler(reason):
def denial_handler(): """ Auth & Auth denial handler. When this handler is called, response.status has two possible values: 401 or 403. """ if response.status_int == 401: message = _("Forbiden access: Authentification required") message_type = 'error' else: credentials = request.environ.get('repoze.what.credentials') ...
self.headers = { "User-Agent": "Mozilla/5.0" }
self.headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "text/xml", "Accept": "text/xml"}
def __init__(self, url, proxy = None): """ Connects to the server, as defined in the url. Parameters: * url: A fully qualified url: `scheme://user:pass@hostname:port` * proxy: A string defining a proxy server: `hostname:port` """ self.url = urlparse.urlparse(url)
return self.request(url, "PROPFIND", props, {'depth': depth})
return self.request(url, "PROPFIND", props, {'depth': str(depth)})
def propfind(self, url, props="", depth=0): """ Send a propfind request.
{'depth': depth, "Content-Type":
{'depth': str(depth), "Content-Type":
def report(self, url, query="", depth=0): """ Send a report request.
raise error.ReportError(r.raw)
raise error.ReportError(report.raw)
def date_search(client, calendar, start, end = None): """ Perform a time-interval search in the `calendar`. """ rc = [] # build the request expand = cdav.Expand(start, end) data = cdav.CalendarData() + expand prop = dav.Prop() + data range = cdav.TimeRange(start, end) vevent = cdav.CompFilter("VEVENT") + range vcal =...
properties, that don't have comples types.
properties, that don't have complex types.
def get_properties(self, props = [], depth = 0): """ Get properties (PROPFIND) for this object. Works only for properties, that don't have comples types.
* start = "20100528T124500Z", a vCal-formatted string describing a date-time. * end = "20100528T124500Z", same as above.
* start = datetime.now(). * end = same as above.
def date_search(self, start, end = None): """ Search events by date in the calendar. Recurring events are expanded if they have an occurence during the specified time frame.
DAVObject.__init__(self, client, url, parent, id)
DAVObject.__init__(self, client=client, url=url, parent=parent, id=id)
def __init__(self, client, url = None, data = None, parent = None, id = None): """ Event has an additional parameter for its constructor: * data = "...", vCal data for the event """ DAVObject.__init__(self, client, url, parent, id) if data is not None: self.data = data
nickname = mmp_packet.getBodyAttr('nickname') self.myname = utils.win2str(nickname)
try: nickname = mmp_packet.getBodyAttr('nickname') self.myname = utils.win2str(nickname) except KeyError: self.myname = self._login
def _process_packet(self, mmp_packet):
currency = models.ForeignKey(Currencies,db_column ="currency",max_length=9,blank=True,verbose_name='Currency')
currency = models.CharField(max_length=180,null=True, blank=True,)
def __unicode__(self): return u"%s" % (self.gmtzone)
add_summary( "Found: %s controllers" % ( len(controllers) ) )
add_summary( "Found %s controllers" % ( len(controllers) ) )
def check_controllers(): global controllers status = -1 controllers = run_hpacucli() if len(controllers) == 0: add_summary("No Disk Controllers Found. Exiting...") global nagios_state nagios_state = unknown end() add_summary( "Found: %s controllers" % ( len(controllers) ) ) for i in controllers: controller_status = che...
for i in environ['PATH'].split(':'): print i
def main(): parse_arguments() set_path('') check_controllers() check_logicaldisks() check_physicaldisks() for i in environ['PATH'].split(':'): print i end()
debug = False if debug:
global debugging if debugging:
def debug( debugtext ): debug = False if debug: print debugtext
if key in subitems.values(): object['master'][key] = []
def run_sssu(system=None, command="ls system full"): commands = [] continue_on_error="set option on_error=continue" login="select manager %s USERNAME=%s PASSWORD=%s"%(hostname,username,password) commands.append(continue_on_error) commands.append(login) if system != None: commands.append("select SYSTEM %s" % system) c...
totalstoragespacegb=i['totalstoragespacegb'] usedstoragespacegb=i['usedstoragespacegb'] warninggb= float(totalstoragespacegb) * float( i['occupancyalarmlevel'] ) / 100
totalstoragespacegb= float( i['totalstoragespacegb'] ) usedstoragespacegb= float ( i['usedstoragespacegb'] ) occupancyalarmlvel = float( i['occupancyalarmlevel'] ) warninggb= totalstoragespacegb * occupancyalarmlvel / 100
def check_generic(command="ls disk full",namefield="objectname", perfdata_fields=[], longserviceoutputfields=[], detailedsummary=False): summary="" perfdata="" nagios_state = ok systems = run_sssu() objects = [] for i in systems: result = run_sssu(system=i['objectname'], command=command) for x in result: x['systemname'...
long("- %s - diskgroup usage is over threshold!\n" % state[warning])
long("- %s - diskgroup usage is over %s%% threshold !\n" % (state[warning], occupancyalarmlvel) )
def check_generic(command="ls disk full",namefield="objectname", perfdata_fields=[], longserviceoutputfields=[], detailedsummary=False): summary="" perfdata="" nagios_state = ok systems = run_sssu() objects = [] for i in systems: result = run_sssu(system=i['objectname'], command=command) for x in result: x['systemname'...
stat = check_operationalstate( sensor,print_failed_objects=True, namefield='name', valid_states=['good','notavailable','unsupported'])
stat = check_operationalstate( sensor,print_failed_objects=True, namefield='name', valid_states=['good','notavailable','unsupported','notinstalled'])
def check_generic(command="ls disk full",namefield="objectname", perfdata_fields=[], longserviceoutputfields=[], detailedsummary=False): summary="" perfdata="" nagios_state = ok systems = run_sssu() objects = [] for i in systems: result = run_sssu(system=i['objectname'], command=command) for x in result: x['systemname'...
for fan in i['fans']: fanstate = max(fanstate,ok) if fan.has_key('status'): status = fan['status'] elif fan.has_key('installstatus'): status = fan['installstatus'] if status != 'normal' and status != 'yes': fanstate = max(warning,fanstate) long("Fan %s status = %s\n" % (fan['fanname'],status)) for source in i['powerso...
if i.has_key('fans'): for fan in i['fans']: fanstate = max(fanstate,ok) if fan.has_key('status'): status = fan['status'] elif fan.has_key('installstatus'): status = fan['installstatus'] if status != 'normal' and status != 'yes': fanstate = max(warning,fanstate) long("Fan %s status = %s\n" % (fan['fanname'],status)) if...
def check_controllers(): summary="" perfdata="" #longserviceoutput="\n" nagios_state = ok systems = run_sssu() controllers =[] for i in systems: result = run_sssu(system=i['objectname'], command="ls controller full") for controller in result: controller['systemname'] = i['objectname'] controllers.append( controller ) f...
except IOError as (errno, strerror):
except IOError, (errno, strerror):
def readbond( interface ): intfile = "/proc/net/bonding/%s" % interface # Read interface info try: bondfh = open (intfile, 'r') except IOError as (errno, strerror): print "Unable to open bond %s: %s" % (intfile, strerror) sys.exit(3) except: print "Unexpected error:", sys.exc_info()[0] sys.exit(3) # Initialize bond ...
print "Ble"
print "Usage: %s -i bond0" % sys.argv[0]
def usage(): print "Ble"
check_wbem()
def main(): parse_arguments() set_path('') #check_wbem() end()
message = "%s - %s" % ( state[nagios_state], summary)
message = "%s - %s" % ( state[nagios_status], summary)
def end(): global summary global longserviceoutput global perfdata global nagios_status global show_longserviceoutput global show_perfdata message = "%s - %s" % ( state[nagios_state], summary) if show_perfdata: message = "%s | %s" % ( message, perfdata) if show_longserviceoutput: message = "%s\n%s" % ( message, longser...
debug("results: %s" % (stdout.strip() )
debug("results: %s" % (stdout.strip() ) )
def runCommand(command): proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stderr=subprocess.PIPE,) stdout, stderr = proc.communicate('through stdin to stdout') if proc.returncode > 0: print "Error %s: %s\n command was: '%s'" % (proc.returncode,stderr.strip(),command) debug("results: %s" % (stdout.str...
return 'Copyright (c) %s Andrew Ramos' % now.year
return 'Copyright &copy; %s Andrew Ramos' % now.year
def feed_copyright(self): now = datetime.datetime.now() return 'Copyright (c) %s Andrew Ramos' % now.year
projects = Project.objects.filter(status='p').select_related()
projects = Project.objects.filter(status='p').select_related().order_by("-pk")
def portfolio_home(request): projects = Project.objects.filter(status='p').select_related() return {'projects':projects}
articles = Article.objects.all().order_by("-date_published") case_studies = CaseStudy.objects.all().order_by("-date_published") short_posts = ShortPost.objects.all().order_by("-date_published") quotes = Quote.objects.all().order_by("-date_published")
articles = Article.objects.filter(status='p').all().order_by("-date_published") case_studies = CaseStudy.objects.filter(status='p').all().order_by("-date_published") short_posts = ShortPost.objects.filter(status='p').all().order_by("-date_published") quotes = Quote.objects.filter(status='p').all().order_by("-date_publi...
def items(self): articles = Article.objects.all().order_by("-date_published") case_studies = CaseStudy.objects.all().order_by("-date_published") short_posts = ShortPost.objects.all().order_by("-date_published") quotes = Quote.objects.all().order_by("-date_published")
class CaseStudyIndex(SearchIndex):
class CaseStudyIndex(RealTimeSearchIndex):
def get_queryset(self): """Used when the entire index for model is updated.""" return Article.objects.filter(status='p',date_published__lte=datetime.datetime.now())
class ShortPostIndex(SearchIndex):
class ShortPostIndex(RealTimeSearchIndex):
def get_queryset(self): """Used when the entire index for model is updated.""" return CaseStudy.objects.filter(status='p',date_published__lte=datetime.datetime.now())
class QuoteIndex(SearchIndex):
class QuoteIndex(RealTimeSearchIndex):
def get_queryset(self): """Used when the entire index for model is updated.""" return ShortPost.objects.filter(status='p',date_published__lte=datetime.datetime.now())
content.append('<img src="%s">' % image) print dir(content)
content.append('<img src="%s%s">' % (settings.MEDIA_URL, image.image)) print '<img src="%s%s">' % (settings.MEDIA_URL, image.image)
def item_description(self, item): content = [] if item._meta.verbose_name == "article": for image in item.images.all(): content.append('<img src="%s">' % image) print dir(content) content.append(smartypants.smartyPants(item.content)) return "".join(content) elif item._meta.verbose_name == "short post": if item.link: re...
print "hello world"
pass
def say(self): print "hello world"
Expression.Context = _PyV8.AstExpressionContext
def convert(obj): if type(obj) == _PyV8.JSArray: return [convert(v) for v in obj] if type(obj) == _PyV8.JSObject: return dict([[str(k), convert(obj.__getattr__(str(k)))] for k in obj.__members__]) return obj
FunctionBoilerplate = _PyV8.AstFunctionBoilerplateLiteral
SharedFunction = _PyV8.AstSharedFunctionInfoLiteral
def convert(obj): if type(obj) == _PyV8.JSArray: return [convert(v) for v in obj] if type(obj) == _PyV8.JSObject: return dict([[str(k), convert(obj.__getattr__(str(k)))] for k in obj.__members__]) return obj
st = JSStackTrace.GetCurrentStackTrace(4, JSStackTrace.Options.Detailed) self.assertEqual(1, len(st))
def testErrorInfo(self): with JSContext() as ctxt: with JSEngine() as engine: try: engine.compile(""" function hello() { throw Error("hello world"); } hello();""", "test", 10, 10).run() self.fail() except JSError, e: self.assert_(str(e).startswith('JSError: Error: hello world ( test @ 14 : 34 ) ->')) self.assertEqual...
return self.tag.name
return self.tag.name.upper()
def tagName(self): return self.tag.name
body = xpath_property("/html/body[1]", readonly=True)
body = xpath_property("/html/body[1]")
def URL(self): raise NotImplementedError()
self.assertEquals("html", html.nodeName)
self.assertEquals("HTML", html.nodeName)
def testNode(self): self.assertEquals(Node.DOCUMENT_NODE, self.doc.nodeType) self.assertEquals("#document", self.doc.nodeName) self.failIf(self.doc.nodeValue) html = self.doc.documentElement self.assert_(html) self.assertEquals(Node.ELEMENT_NODE, html.nodeType) self.assertEquals("html", html.nodeName) self.failIf(htm...
self.assertEquals("body", body.tagName)
self.assertEquals("BODY", body.tagName)
def testDocument(self): nodes = self.doc.getElementsByTagName("body") body = nodes.item(0) self.assertEquals("body", body.tagName)
self.assertEquals("html", html.tagName)
self.assertEquals("HTML", html.tagName)
def testElement(self): html = self.doc.documentElement self.assertEquals("html", html.tagName) self.assertEquals("http://www.w3.org/1999/xhtml", html.getAttribute("xmlns")) self.assert_(html.getAttributeNode("xmlns")) nodes = html.getElementsByTagName("body") self.assertEquals(1, nodes.length) body = nodes.item(0) ...
self.assertEquals("body", body.tagName)
self.assertEquals("BODY", body.tagName)
def testElement(self): html = self.doc.documentElement self.assertEquals("html", html.tagName) self.assertEquals("http://www.w3.org/1999/xhtml", html.getAttribute("xmlns")) self.assert_(html.getAttributeNode("xmlns")) nodes = html.getElementsByTagName("body") self.assertEquals(1, nodes.length) body = nodes.item(0) ...
source = self._makeOne(directory='transmogrify.filesystem.tests:empty')
source = self._makeOne(directory='transmogrify.filesystem.tests:empty', ignored='re:.*\.svn.*\nre:.*\.DS_Store\n')
def test_empty_directory(self): source = self._makeOne(directory='transmogrify.filesystem.tests:empty') self.assertEquals([], list(source))
self.main_widget().error_box)
self.main_widget().show_error)
def activate(self): if self.config()["run_sync_server"]: # Restart the thread to have the new settings take effect. self.deactivate() try: self.thread = ServerThread(self.component_manager) except socket.error, (errno, e): if errno == 98: self.main_widget().show_error(\ _("Unable to start sync server.") + " " + \
import sys; sys.stderr.write("rollback")
def terminate(self):
for key, value in fact.data.iteritems(): fact.data[key] = value.replace(match.group(1), filename) self.con.execute("""update data_for_fact set value=? where _fact_id=? and key=?""", (fact.data[key], fact._id, key))
else: filename = filename.replace("\\", "/") for key, value in fact.data.iteritems(): fact.data[key] = value.replace(match.group(1), filename) self.con.execute("""update data_for_fact set value=? where _fact_id=? and key=?""", (fact.data[key], fact._id, key))
def _process_media(self, fact, timestamp):
self.main_widget().information_box)
self.main_widget().show_information)
def accept(self): QtGui.QDialog.accept(self) # Store input for later use. server = unicode(self.server.text()) port = self.port.value() username = unicode(self.username.text()) password = unicode(self.password.text()) self.config()["server_for_sync_as_client"] = server self.config()["port_for_sync_as_client"] = port se...