rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
m.Create(job.output_file) | m.Create(os.path.normpath(job.output_file)) | def __execute_job(self, job): if job.command == "generate": print "Command \"generate\" found. Generating map file." if job.output_file == None: print "No output file set. Aborting." self.__delete_job(job.file_job) return |
self.Inside(other.bottom, other.top) or | self.Inside(other.bottom, other.left) or | def Intersects(self, other): if (self.Inside(other.top, other.left) or self.Inside(other.top, other.right) or self.Inside(other.bottom, other.top) or self.Inside(other.bottom, other.right)): return True if (other.Inside(self.top, self.left) or other.Inside(self.top, self.right) or other.Inside(self.bottom, self.top) o... |
other.Inside(self.bottom, self.top) or | other.Inside(self.bottom, self.left) or | def Intersects(self, other): if (self.Inside(other.top, other.left) or self.Inside(other.top, other.right) or self.Inside(other.bottom, other.top) or self.Inside(other.bottom, other.right)): return True if (other.Inside(self.top, self.left) or other.Inside(self.top, self.right) or other.Inside(self.bottom, self.top) o... |
z = ZipFile(filename, "w") | z = ZipFile(filename, "w", ZIP_DEFLATED) | def Create(self, filename): ''' Creates the map at the given location @param filename: Location of the map file that should be created ''' print "Creating map file ..." # Open the zip file z = ZipFile(filename, "w") for file in self.__files: # Make sure we have a list if not isinstance(file, list): # ... or at least a ... |
z.write(file[0], None, ZIP_STORED) | z.write(file[0], os.path.basename(file[0]), ZIP_STORED) | def Create(self, filename): ''' Creates the map at the given location @param filename: Location of the map file that should be created ''' print "Creating map file ..." # Open the zip file z = ZipFile(filename, "w") for file in self.__files: # Make sure we have a list if not isinstance(file, list): # ... or at least a ... |
z.write(file[0], None, ZIP_DEFLATED) z.close() | z.write(file[0], os.path.basename(file[0]), ZIP_DEFLATED) z.close() | def Create(self, filename): ''' Creates the map at the given location @param filename: Location of the map file that should be created ''' print "Creating map file ..." # Open the zip file z = ZipFile(filename, "w") for file in self.__files: # Make sure we have a list if not isinstance(file, list): # ... or at least a ... |
raise cherrypy.HTTPRedirect('/status?uuid=' + job.uuid) | raise cherrypy.HTTPRedirect(cherrypy.url('/status?uuid=' + job.uuid)) | def generate(self, name, mail, waypoint_file, latmin, latmax, lonmin, lonmax): name = name.strip() if name == "": return view.render(error='No map name given!') | HTMLFormFiller(data=dict(name=name, mail=mail)) |
self.__delete_job(dir_job) | self.__delete_job(file_job) | def __check_jobs(self): for file in os.listdir(self.__dir_jobs): dir_job = os.path.join(self.__dir_jobs, file) if not os.path.isdir(dir_job): continue |
print "Downloading tile " + url + ".zip ..." | print "Downloading tile " + url + ' ...' | def __download_tile(path_tile_zip, filename): url = __server_path + filename + '.zip' print "Downloading tile " + url + ".zip ..." socket.setdefaulttimeout(10) try: urllib.urlretrieve(url, path_tile_zip) except IOError: print "Download of tile " + url + " failed!" |
globals()).__of__(self.context) | package_path).__of__(self.context) | def export(self, export_context, subdir, root=False): """ See IFilesystemExporter. """ template = PageTemplateResource('xml/%s' % self._FILENAME, globals()).__of__(self.context) info = self._getExportInfo() export_context.writeDataFile('%s.xml' % self.context.getId(), template(info=info), 'text/xml', subdir, ) |
return creds | return {} | def extractCredentials(self, request): """ Extract credentials from cookie or 'request'. """ creds = {} cookie = request.get(self.cookie_name, '') # Look in the request.form for the names coming from the login form login = request.form.get('__ac_name', '') |
return None | raise RuntimeError("Output of bench program indicated error.") | def parse_data(self, data): result = [] for line in data.split("\n"): #print "DEBUG OUT:" + line if self.check_for_error(line): return None m = self.re_barrierSec1.match(line) if not m: m = self.re_sec2.match(line) if not m: m = self.re_sec3.match(line) |
return None | raise RuntimeError("Output of bench program did not contain a total value") | def parse_data(self, data): result = [] for line in data.split("\n"): #print "DEBUG OUT:" + line if self.check_for_error(line): return None m = self.re_barrierSec1.match(line) if not m: m = self.re_sec2.match(line) if not m: m = self.re_sec3.match(line) |
self.config = Configurator(args[0], cli_options, args[1:]) | self.config = Configurator(args[0], cli_options, *args[1:]) | def run(self, argv = None): if argv is None: argv = sys.argv cli_options, args = self.shell_options().parse_args(argv[1:]) if len(args) < 1: logging.error("<config> is a mandatory parameter and was not given. See --help for more information.") sys.exit(-1) |
logging.warning("Run runId.cfg.vm['name'], runId.cfg.name)) | logging.warning("Run runId.cfg.vm['name'], runId.cfg.name, p.returncode, output)) | def _generate_data_point(self, cmdline, error, perf_reader, runId): p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) (output, _) = p.communicate() if p.returncode != 0: (consequent_erroneous_runs, erroneous_runs) = error consequent_erroneous_runs += 1 erroneous_runs += 1 log... |
def _configuration_details(self, runId, statistics): | def _configuration_details(self, runId, statistics = None): | def _configuration_details(self, runId, statistics): result = [] criteria = (runId.cfg, ) + runId.variables + (runId.criterion, ) for criterion in criteria: result.append(" %s" % criterion) result.append(" = ") self._output_stats(result, statistics) return result |
result += self._configuration_details(runId, {}) | result += self._configuration_details(runId) | def runFailed(self, runId): result = [] result.append("[%s] Run failed: " % datetime.now()) |
self._addAdditionalXAxisValueLabels(len(data), ax1) | self._addAdditionalXAxisValueLabels(len(bp['boxes']), ax1) | def _createDiagram(self, character, groups): assert type(character) is tuple assert type(groups) is dict fileName = self._configurator.visualization.get('fileName', "%s-%s.pdf") % character fig, ax1 = self._createFigure() data, titles = self._prepareData(groups) bp = self._plotBoxes(data) self._brushUpBoxes(bp, data... |
self._top = 900 bottom = 600 ax1.set_ylim(bottom, self._top) | ax1.set_ylim(self._bottom, self._top) | def _addDataLabels(self, ax1, titles, numBoxes): # Set the axes ranges and axes labels ax1.set_xlim(0.5, numBoxes+0.5) self._top = 900 bottom = 600 ax1.set_ylim(bottom, self._top) xtickNames = plt.setp(ax1, xticklabels=titles) plt.setp(xtickNames, rotation=45, fontsize=8) |
numBoxes = len(data) | numBoxes = len(bp['boxes']) if numBoxes != len(bp['boxes']): foo assert numBoxes == len(bp['boxes']) | def _brushUpBoxes(self, bp, data, ax1): # Now fill the boxes with desired colors self._boxColors = ['darkkhaki','royalblue'] numBoxes = len(data) self._medians = range(numBoxes) for i in range(numBoxes): box = bp['boxes'][i] boxX = [] boxY = [] for j in range(5): boxX.append(box.get_xdata()[j]) boxY.append(box.get_ydat... |
data = self._sortAndName(data) | data = self._sort(data) | def jobCompleted(self, configurations, dataAggregator): data = self._unfoldConfig(dataAggregator.getData()) data = self._filter_by_criterion(data) data = self._separate(data) data = self._group(data) data = self._sortAndName(data) for characteristics, groups in data.iteritems(): self._createDiagram(characteristics, g... |
assert type(character) is tuple | assert type(character) is tuple, "character was expected to be a tuple but is " + str(type(character)) + ":" + str(character) | def _createDiagram(self, character, groups): assert type(character) is tuple assert type(groups) is dict fileName = self._configurator.visualization.get('fileName', "%s-%s.pdf") % character fig, ax1 = self._createFigure() data, titles = self._prepareData(groups) self._estimanteInterval(data) bp = self._plotBoxes(da... |
fileName = self._configurator.visualization.get('fileName', "%s-%s.pdf") % character | try: fileName = self._configurator.visualization.get('fileName', "%s-%s.pdf") % character except TypeError: raise ValueError("fileName template given in configuration does not match the given arguments. Tpl: " + self._configurator.visualization.get('fileName', "%s-%s.pdf") + " args: " + character.__str__()) | def _createDiagram(self, character, groups): assert type(character) is tuple assert type(groups) is dict fileName = self._configurator.visualization.get('fileName', "%s-%s.pdf") % character fig, ax1 = self._createFigure() data, titles = self._prepareData(groups) self._estimanteInterval(data) bp = self._plotBoxes(da... |
plt.setp(xtickNames, rotation=45, fontsize=8) | plt.setp(xtickNames, rotation=90, fontsize=8) | def _addDataLabels(self, ax1, titles, numBoxes): # Set the axes ranges and axes labels ax1.set_xlim(0.5, numBoxes+0.5) ax1.set_ylim(self._bottom, self._top) xtickNames = plt.setp(ax1, xticklabels=titles) plt.setp(xtickNames, rotation=45, fontsize=8) |
tmpTiles, tmpVals = zip(*values) | tmpTitles, tmpVals = zip(*values) def name(tuple): if columnName: return columnName.format(*tuple) else: return str(tuple) | def _prepareData(self, groups): #hm, ignore grouping for now, we will incooperate that later if necessary data = [] titles = [] for group, values in groups.iteritems(): tmpTiles, tmpVals = zip(*values) data += tmpVals titles += [group[0] + " " + title for title in tmpTiles] return data, titles |
titles += [group[0] + " " + title for title in tmpTiles] | for title in tmpTitles: if type(group) is str: titles.append(name((group,) + title)) else: titles.append(name(group + title)) | def _prepareData(self, groups): #hm, ignore grouping for now, we will incooperate that later if necessary data = [] titles = [] for group, values in groups.iteritems(): tmpTiles, tmpVals = zip(*values) data += tmpVals titles += [group[0] + " " + title for title in tmpTiles] return data, titles |
def _sortAndName(self, data): if 'columnName' in self._configurator.visualization: columnName = self._configurator.visualization['columnName'] else: columnName = None | def _sort(self, data): | def _sortAndName(self, data): if 'columnName' in self._configurator.visualization: columnName = self._configurator.visualization['columnName'] else: columnName = None if 'sortBy' in self._configurator.visualization: sortBy = self._configurator.visualization['sortBy'].copy() #copy since we use popitem() to access the o... |
return cmp(statX.__dict__[val], statY.__dict__[val]) def name(tuple): if columnName: return columnName.format(*tuple) else: return str(tuple) | return cmp(statY.__dict__[val], statX.__dict__[val]) | def myCmp(x, y): if len(x[1]) == 0 or len(y[1]) == 0: return cmp(x[1], y[1]) statX = StatisticProperties(x[1], self._configurator.statistics['confidence_level']) statY = StatisticProperties(y[1], self._configurator.statistics['confidence_level']) return cmp(statX.__dict__[val], statY.__dict__[val]) |
assert type(group) is tuple | assert type(group) is tuple or type(group) is str, "Group is not a tuple or string: " + str(type(group)) + " " + str(group) | def name(tuple): if columnName: return columnName.format(*tuple) else: return str(tuple) |
list = [(name(key), points) for key, points in groupData.iteritems()] list.sort(cmp=myCmp) | list = [(key, points) for key, points in groupData.iteritems()] list = sorted(list, cmp=myCmp) | def name(tuple): if columnName: return columnName.format(*tuple) else: return str(tuple) |
runsCompleted = runsCompleted + 1 | runsCompleted += 1 runsRemaining -= 1 | def execute(self): startTime = None runsCompleted = 0 (actions, benchConfigs) = self._configurator.getBenchmarkConfigurations() configs = self._generate_all_configs(benchConfigs) runsRemaining = len(configs) for action in actions: with activelayers(layer(action)): for runId in configs: logging.info("Configurations le... |
for var_val in cfg.suite['variable_values']: configurations.append(RunId(cfg, (cores, input_size, var_val))) | if len(cfg.suite['variable_values']): for var_val in cfg.suite['variable_values']: configurations.append(RunId(cfg, (cores, input_size, var_val))) else: configurations.append(RunId(cfg, (cores, input_size, None))) | def _generate_all_configs(self, benchConfigs): configurations = [] for cfg in benchConfigs: for cores in cfg.vm['cores']: for input_size in cfg.suite['input_sizes']: for var_val in cfg.suite['variable_values']: configurations.append(RunId(cfg, (cores, input_size, var_val))) return configurations |
def default_fifo_quantity_out(self): | def default_fifo_quantity(self): | def default_fifo_quantity_out(self): return 0.0 |
def default_fifo_quantity_out(self, cursor, user, context=None): | def default_fifo_quantity(self, cursor, user, context=None): | def default_fifo_quantity_out(self, cursor, user, context=None): return 0.0 |
def default_fifo_quantity_out(self): return 0.0 | def default_fifo_quantity(self): return Decimal('0.0') | def default_fifo_quantity_out(self): return 0.0 |
from supybot.questions import expect, something, yn | from supybot.questions import expect, something, yn, output | def configure(advanced): from supybot.questions import expect, something, yn def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) conf.registerPlugin('Bugtracker', True) |
conf.registerPlugin('Bugtracker', True) | Bugtracker = conf.registerPlugin('Bugtracker', True) def getRepeatdelay(): output("How many seconds should the bot wait before repeating bug information?") repeatdelay = something("Enter a number greater or equal to 0", default=Bugtracker.repeatdelay._default) try: repeatdelay = int(repeatdelay) if repeatdelay < 0: r... | def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) |
conf.registerChannelValue(conf.supybot.plugins.Bugtracker, 'bugReporter', | conf.registerChannelValue(Bugtracker, 'bugReporter', | def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) |
registry.String('', """Determines the bugtracker to query when the | registry.String('lp', """Determines the bugtracker to query when the | def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default) |
if boost_fnd and not found or (found and len(boost_lib_suffix) > len(boost_fnd.group(1))): if boost_fnd.group(1): boost_lib_suffix = boost_fnd.group(1) else: boost_lib_suffix = "" found = True break | if boost_fnd: if not found or (found and (not boost_fnd.group(1) or len(boost_lib_suffix) > len(boost_fnd.group(1)))): if boost_fnd.group(1): boost_lib_suffix = boost_fnd.group(1) else: boost_lib_suffix = "" found = True | def suffix_check(env): libpath = ["/lib", "/usr/lib"] if os.getenv("LD_LIBRARY_PATH"): libpath.append(os.getenv("LD_LIBRARY_PATH")) if env.has_key("LIBPATH"): libpath.extend(env["LIBPATH"]) |
else | else: | def compiler_check(param): #Configure.CheckCXX() gcc_int_ver = 40100 |
def compiler_check(): | def compiler_check(param): | def compiler_check(): #Configure.CheckCXX() gcc_int_ver = 40300 |
gcc_int_ver = 40300 | gcc_int_ver = 40100 | def compiler_check(): #Configure.CheckCXX() gcc_int_ver = 40300 |
ac_prog = "g++" | if not param: ac_prog = "g++" else ac_prog = param | def compiler_check(): #Configure.CheckCXX() gcc_int_ver = 40300 |
testRunner = xmlrunner.XMLTestRunner(output='test-results') | testrunner = xmlrunner.XMLTestRunner(output='test-results') | def suite(): suite = unittest.TestSuite() suite.addTest(PidmanRestClientTest("test_search_pids")) suite.addTest(PidmanRestClientTest("test_constructor")) suite.addTest(PidmanRestClientTest("test_list_domains")) suite.addTest(PidmanRestClientTest("test_create_domain")) suite.addTest(PidmanRestClientTest("test_request_do... |
logging.debug('Request: %s %s %s <![BODY[%s]]>' % (method, url, headers, body)) | logger.debug('Request: %s %s %s <![BODY[%s]]>' % (method, url, headers, body)) | def _make_request(self, url, method='GET', body=None, expected_response=[200], requires_auth=False, accept="application/json"): ''' Make an API request. Common functionality for making http requests and simple error handling. Defaults are set so that simple access requests can specify very few parameters. |
my_structures.append(self.get_license(vars)) | license_structure = self.get_license(vars) if license_structure: my_structures.append(license_structure) | def get_structures(self, vars): my_structures = [] for structure in self.required_structures: my_structures.append(self.load_structure(structure)) # append the chosen license structure, if applicable my_structures.append(self.get_license(vars)) return my_structures |
def test_gpl_structure(self): """ verify that the gpl2 license writes correctly, given appropriate values the base template requires no structures, so the only one we should get below is the license structure | def test_license_structure(self): """ verify that all license structures are well formed | def test_gpl_structure(self): """ verify that the gpl2 license writes correctly, given appropriate values the base template requires no structures, so the only one we should get below is the license structure """ this_year = datetime.date.today().year try: my_license = self.template.get_structures(self.license_vars)[0... |
try: my_license = self.template.get_structures(self.license_vars)[0] except IndexError: self.fail('unable to find GPL license structure') | for this_license in LICENSE_EXPECTATIONS.keys(): self.license_vars['license_name'] = this_license try: my_license = self.template.get_structures(self.license_vars)[0] except IndexError: self.fail('unable to find %s license structure' % this_license) | def test_gpl_structure(self): """ verify that the gpl2 license writes correctly, given appropriate values the base template requires no structures, so the only one we should get below is the license structure """ this_year = datetime.date.today().year try: my_license = self.template.get_structures(self.license_vars)[0... |
my_license().write_files(self.command, self.tempdir, self.license_vars); import pdb; pdb.set_trace( ) | my_license().write_files(self.command, self.tempdir, self.license_vars); | def test_gpl_structure(self): """ verify that the gpl2 license writes correctly, given appropriate values the base template requires no structures, so the only one we should get below is the license structure """ this_year = datetime.date.today().year try: my_license = self.template.get_structures(self.license_vars)[0... |
top = os.listdir(self.tempdir) self.failUnless('docs' in top, 'failed to write the docs directory') docs = os.listdir(os.path.join(self.tempdir, 'docs')) self.failUnless('LICENSE.GPL' in docs, 'GPL License failed to write') self.failUnless('LICENSE.txt' in docs, 'license boilerplate failed to write') bp = open(os.pat... | top = os.listdir(self.tempdir) self.failUnless('docs' in top, 'failed to write the docs directory') expected = LICENSE_EXPECTATIONS[this_license] docs = os.listdir(os.path.join(self.tempdir, 'docs')) for filename in expected: self.failUnless(filename in docs, '%s not found in docs dir' % filename) bpfh = open(os.path.... | def test_gpl_structure(self): """ verify that the gpl2 license writes correctly, given appropriate values the base template requires no structures, so the only one we should get below is the license structure """ this_year = datetime.date.today().year try: my_license = self.template.get_structures(self.license_vars)[0... |
preserved, min_area = set(), tolerance ** 2 | min_area = tolerance ** 2 | def simplify(shape, tolerance, cross_check): """ """ if shape.type != 'LineString': return shape coords = list(shape.coords) if len(coords) <= 2: # don't shorten the too-short return shape # For each coordinate that forms the apex of a three-coordinate # triangle, find the area of that triangle and put it into a lis... |
coords[index] = None | coords[index], popped = None, True | def simplify(shape, tolerance, cross_check): """ """ if shape.type != 'LineString': return shape coords = list(shape.coords) if len(coords) <= 2: # don't shorten the too-short return shape # For each coordinate that forms the apex of a three-coordinate # triangle, find the area of that triangle and put it into a lis... |
if getattr(form, extractData, None): | if getattr(form, "extractData", None): | def validate_input(self, formname, fieldname, fieldset=None, value=None): """Given a form (view) name, a field name and the submitted value, validate the given field. """ |
curl = subprocess.call(['/usr/bin/curl', '-4', '-I', '-m', '5', test], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if (t==IP and curl==28) or (t==TLS and curl==35) or (t==URL and curl==56): pass elif t==IP and curl==56: print line, '\t', test, '=>', '\033[31mexpecting %d, got %d\033[0m' % (expect[t], curl) | val1 = subprocess.call(['/usr/bin/curl', '-4', '-I', '-m', '5', test], stdout=subprocess.PIPE, stderr=subprocess.PIPE) val2 = subprocess.call(['/usr/bin/curl', '-4', '-I', '-m', '5', test], stdout=subprocess.PIPE, stderr=subprocess.PIPE) if (t==IP and val1==28 and val2==28) or (t==TLS and val1==35 or val2==35) or (t==U... | def main(): fin = open('list.txt', 'r') ferr = open('list.err', 'w') line = 0 if len(sys.argv) > 1: startfrom = int(sys.argv[1]) else: startfrom = 0 for rule in fin: line += 1 rule = rule.strip() if line < startfrom: continue if not rule: continue if rule.startswith('[AutoProxy'): continue if rule.startswith('!'): cont... |
print line, '\t', test, '=>', '\033[1;31mexpecting %d, got %d\033[0m' % (expect[t], curl) ferr.write(str(line) + ': "' + rule + '", expecting %d, got %d' % (expect[t], curl) + '\n') | print line, '\t', test, '=>', '\033[1;31mexpecting %d, got %d %d\033[0m' % (expect[t], val1, val2) ferr.write(str(line) + ': "' + rule + '", expecting %d, got %d %d' % (expect[t], val1, val2) + '\n') | def main(): fin = open('list.txt', 'r') ferr = open('list.err', 'w') line = 0 if len(sys.argv) > 1: startfrom = int(sys.argv[1]) else: startfrom = 0 for rule in fin: line += 1 rule = rule.strip() if line < startfrom: continue if not rule: continue if rule.startswith('[AutoProxy'): continue if rule.startswith('!'): cont... |
'footer': ('django.db.models.fields.TextField', [], {}), | 'footer': ('django.db.models.fields.TextField', [], {'null': 'True'}), | def backwards(self, orm): # Deleting field 'ScheduledUpdate.footer' db.delete_column('accounts_scheduledupdate', 'footer') |
if ready_by: | if ready_by and method_display: | def clean(self): cleaned_data = super(OrderForm, self).clean() method = self.cleaned_data.get('method') if method == Order.METHOD_DELIVERY: address_fields = ['street', 'city', 'state', 'zip'] if not all(cleaned_data.get(field) for field in address_fields): msg = 'You must enter an address for delivery.' raise forms.Val... |
organization = models.CharField() | organization = models.CharField(max_length=255) | def save(self, *args, **kwargs): self.total = self.price * self.qty super(LineItem, self).save(*args, **kwargs) |
if 'instance' in kwargs: | if kwargs.get('instance'): | def __init__(self, data=None, files=None, *args, **kwargs): super(SubscriberForm, self).__init__(data, files, *args, **kwargs) if 'instance' in kwargs: user = kwargs['instance'].user self.initial.update({ 'first_name': user.first_name, 'last_name': user.last_name, 'email': user.email }) |
msg = 'Section "%s" created successfully. Now you can <a href="%s">add a menu item now</a> or configure section options below.' % (obj.name, reverse('dashboard_add_menu', args=['item']) + '?q=%d' % (obj.id),) | msg = 'Section "%s" created successfully. Now you can <a href="%s">add a menu item now</a> or configure section options below.' % (obj.name, reverse('dashboard_add_menu', args=['item']) + '?pk=%d' % (obj.id),) | def add_edit_menu(request, object_type, object_id=None): model = get_model('core', object_type) form_dict = { 'section': SectionForm, 'item': get_item_form(request.site) } instance = None form_class = form_dict[object_type] if object_id is not None: instance = get_object_or_404(model, id=object_id) if instance and inst... |
t, meridian = value.split() h, m = [int(v) for v in t.split(':')] | try: t, meridian = value.split() h, m = [int(v) for v in t.split(':')] except ValueError: return None | def clean(self, value): if value: t, meridian = value.split() h, m = [int(v) for v in t.split(':')] if meridian == 'PM' and h != 12: h += 12 elif meridian == 'AM' and h == 12: h = 0 return time(h, m) return None |
setattr(new_class, k, v) | m = key_re.match(k) if not m: raise KeyChainError('Invalid keychain key %s' % k) name = m.group(1).lower() setattr(new_class, name, CacheProxy(v)) | def __new__(cls, name, bases, dct): """Sets cache key templates declared in settings as class attributes. """ new_class = super(KeyChainMetaclass, cls).__new__(cls, name, bases, dct) cache_keys = getattr(settings, 'KEYCHAIN_CACHE_KEYS', {}) for k, v in cache_keys.items(): setattr(new_class, k, v) return new_class |
def __getattr__(cls, name): try: key_template = getattr(cls, 'KEY_%s' % name.upper()) except AttributeError: raise AttributeError('No key template defined for %s' % name) return CacheProxy(key_template) | def __getattr__(cls, name): try: key_template = getattr(cls, 'KEY_%s' % name.upper()) except AttributeError: raise AttributeError('No key template defined for %s' % name) return CacheProxy(key_template) | |
self.slug = slugify(self.title) | self.slug = slugify(self.title)[:50] | def save(self, *args, **kwargs): self.body_html = markdown(self.body) if not self.id: self.slug = slugify(self.title) self.time_sent = datetime.now() super(Release, self).save(*args, **kwargs) |
ip_address=request.META.get('REMOTE_ADDR'), | ip_address=ip_address, | def record_hit(self, site, location, session_id, response_code, request): """Records a single hit to the site, creating a session container where necessary and otherwise grabbing the appropriate session to add the hits to. |
total_pages = Fax.objects.filter(site=site).aggregate(Max('page_count'))['page_count__max'] | total_pages = Fax.objects.filter(site=site).aggregate(Sum('page_count'))['page_count__sum'] | def home(request): site = request.site updates = site.scheduledupdate_set.all() email_subscribers = Subscriber.via_email.filter(site=site) fax_subscribers = Subscriber.via_fax.filter(site=site) total_pages = Fax.objects.filter(site=site).aggregate(Max('page_count'))['page_count__max'] this_month = datetime(datetime.now... |
site=site, timestamp__gt=this_month).aggregate(Max('page_count'))['page_count__max'] | site=site, completion_time__gte=this_month).aggregate(Sum('page_count'))['page_count__sum'] | def home(request): site = request.site updates = site.scheduledupdate_set.all() email_subscribers = Subscriber.via_email.filter(site=site) fax_subscribers = Subscriber.via_fax.filter(site=site) total_pages = Fax.objects.filter(site=site).aggregate(Max('page_count'))['page_count__max'] this_month = datetime(datetime.now... |
if site.account.user != request.user: raise Http404() | def delete_site_object(request, model, object_id, reverse_on): site = request.site if site.account.user != request.user: raise Http404() instance = model.objects.get(id=object_id) if instance.site != site: raise Http404() instance.delete() return HttpResponseRedirect(reverse(reverse_on)) | |
def add_edit_menu(request, object_type, object_id): | def add_edit_menu(request, object_type, object_id=None): | def add_edit_menu(request, object_type, object_id): model = get_model('core', object_type) form_dict = { 'section': SectionForm, 'item': get_item_form(request.site) } instance = None form_class = form_dict['object_type'] if object_id is not None: instance = get_object_or_404(model, id=object_id) if instance and instanc... |
form_class = form_dict['object_type'] | form_class = form_dict[object_type] | def add_edit_menu(request, object_type, object_id): model = get_model('core', object_type) form_dict = { 'section': SectionForm, 'item': get_item_form(request.site) } instance = None form_class = form_dict['object_type'] if object_id is not None: instance = get_object_or_404(model, id=object_id) if instance and instanc... |
value = value.strftime('%I:%M %p') | value = '' if value: value = value.strftime('%I:%M %p') | def render(self, name, value, attrs=None): value = value.strftime('%I:%M %p') return super(AmPmTimeWidget, self).render(name, value, attrs) |
for k, v in times.items(): | time_list = times.items() time_list.sort(key=lambda obj: obj[1][0]) for k, v in time_list: | def hours(self): """Returns a nicely formatted string representing availability based on the site's associated ``TimeSlot`` objects. """ # this implementation is a little naive, but let's just assume our customers # don't keep ridiculous hours timeslots = self.timeslot_set.order_by('dow') times = {} for timeslot in tim... |
exclude = ('name', 'image', 'color',) | exclude = ('site', 'name', 'image', 'color',) | def __init__(self, *args, **kwargs): """Ensures that the list of available images objects is not cached, as ``forms.ChoiceField`` deliberately does. """ super(BackgroundForm, self).__init__(*args, **kwargs) self.fields['bg'].queryset = Background.objects.all() |
return Site.objects.get(domain=domain, tld=tld) | return Site.objects.get(domain=domain) | def get_site_from_domain(subdomain=None, domain=None, tld=None): if domain == 'takeouttiger': if subdomain == 'www': raise Site.DoesNotExist domain = subdomain return Site.objects.get(domain=domain, tld=tld) |
return '%s at %s' % (self.get_weekday_display(), self.start_time.strftime('%x')) | return '%s at %s' % (self.get_weekday_display(), self.start_time.strftime('%X')) | def __unicode__(self): return '%s at %s' % (self.get_weekday_display(), self.start_time.strftime('%x')) |
def remove_twitter(request) | def remove_twitter(request): | def remove_twitter(request) social = request.site.social social.twitter_token = None social.twitter_secret = None social.twitter_screen_name = None social.save() return HttpResponseRedirect(reverse('integration_settings')) |
def remove_facebook(request) | def remove_facebook(request): | def remove_facebook(request) social = request.site.social social.facebook_id = None social.facebook_url = None social.facebook_auto_items = None social.save() return HttpResponseRedirect(reverse('integration_settings')) |
template_name='dashboard/restaurant/location_form.html', post_save_redirect='/dashboard/location/') | template_name='dashboard/restaurant/location_form.html', post_save_redirect='/dashboard/restaurant/location/') | def location(request): return update_object(request, form_class=LocationForm, object_id=request.site.id, template_name='dashboard/restaurant/location_form.html', post_save_redirect='/dashboard/location/') |
return HttpResponse(bg.as_css()) | if bg.staged_image: css = bg.as_css(staged=True) else: css = bg.as_css() return HttpResponse(css) | def get_custom_bg_css(request): form = CustomBackgroundForm(request.POST, instance=request.site.background) form.full_clean() bg = form.save(commit=False) return HttpResponse(bg.as_css()) |
'obj': obj | 'obj': obj, 'MEDIA_URL': settings.MEDIA_URL | def add_related(request, object_type, object_id, form_class): if not request.is_ajax() or request.method != 'POST': raise Http404 model = get_model('core', object_type) instance = get_object_or_404(model, id=object_id) form = form_class(request.POST) if form.is_valid(): obj = form.save(commit=False) setattr(obj, object... |
result['row'] = render_to_string('dashboard/menu/includes/group_row.html', { 'group': group | result['new_row'] = render_to_string('dashboard/menu/includes/group_row.html', { 'group': group, 'MEDIA_URL': settings.MEDIA_URL | def add_sidegroup(request, object_type, object_id): if not request.is_ajax() or request.method != 'POST': raise Http404 result = {} try: model = get_model('core', object_type) instance = get_object_or_404(model, id=object_id) group = SideDishGroup() setattr(group, object_type, instance) group.save() result['success'] =... |
'obj': obj | 'obj': obj, 'MEDIA_URL': settings.MEDIA_URL | def add_side(request, object_id, instance=None): if not request.is_ajax() or request.method != 'POST': raise Http404 instance = get_object_or_404(SideDishGroup, id=object_id) form = SideDishForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.group = instance obj.save() row = render_to_string('dashb... |
method_display = dict(Order.METHOD_CHOICES)[method] | def clean(self): cleaned_data = super(OrderForm, self).clean() method = self.cleaned_data.get('method') if method == Order.METHOD_DELIVERY: address_fields = ['street', 'city', 'state', 'zip'] if not all(cleaned_data.get(field) for field in address_fields): msg = 'You must enter an address for delivery.' raise forms.Val... | |
return HttpResponseRedirect(str(social.site) + reverse('dashboard_marketing_home')) | return HttpResponseRedirect(str(social.site) + reverse('dashboard_marketing')) | def twitter_return(request): auth_dict = get_access_token(request, TWITTER_CONSUMER, TWITTER_CONNECTION, TWITTER_ACCESS_TOKEN_URL, 'twitter') social = Social.objects.get(twitter_screen_name=auth_dict['screen_name']) social.twitter_token = auth_dict['oauth_token'] social.twitter_secret = auth_dict['oauth_token_secret'] ... |
attrs['side_%d' % sidegroup.id] = forms.ModelChoiceField( queryset=sidegroup.sidedish_set.all(), widget=forms.RadioSelect, empty_label=None ) | if sidegroup.sidedish_set.count(): attrs['side_%d' % sidegroup.id] = forms.ModelChoiceField( queryset=sidegroup.sidedish_set.all(), widget=forms.RadioSelect, empty_label=None ) | def get_order_form(instance): """For a given ``instance`` of ``core.models.Item``, returns a form appropriate for completing an order, with a quantity field for all forms, radio select for variant (if applicable), and checkboxes for substitutions/ upgrades (if applicable). """ variants = instance.variant_set.all() upgr... |
self.client.get('/') | self.client.get('/', HTTP_REFERER=self.site.__unicode__() + '/') | def test_current_session(self): self.client.get('/') self.client.get('/') session = Session.objects.order_by('-id')[0] self.assertEquals(2, session.hit_set.count()) |
self.status = status | def notify_restaurant(self, status): """Sends a message to the restaurant with the information about the order and flags the order as either sent or paid. """ content = self.get_pdf_invoice() if self.site.ordersettings.receive_via == OrderSettings.RECEIPT_EMAIL: email = EmailMessage('Takeout Tiger Order #%d' % self.id,... | |
lon, lat = float(site.lon), float(site.lat) | try: lon, lat = float(site.lon), float(site.lat) except TypeError: raise GeocodeError | def __init__(self, data=None, site=None, *args, **kwargs): lon, lat = float(site.lon), float(site.lat) super(OrderSettingsForm, self).__init__(data, *args, **kwargs) self.fields['delivery_area'].widget = EditableMap(options={ 'geometry': 'polygon', 'isCollection': True, 'layers': ['google.streets'], 'default_lat': lat,... |
return HttpResponse('<a href="%s">Redeem</a>' % ( coupon.add_coupon_url(), unicode(coupon))) | return HttpResponse('<a href="%s%s">Redeem now!</a>' % ( unicode(coupon.site), coupon.add_coupon_url())) | def share_coupon(request, coupon_id): try: coupon = Coupon.objects.get_by_coupon_id(coupon_id) except Coupon.DoesNotExist: raise Http404 if request.method == 'POST': shared_via = request.POST.get('via') if shared_via == 'twitter': coupon.twitter_share_count += 1 elif shared_via == 'facebook': coupon.fb_share_count += 1... |
cleaned_data = self.cleaned_data | def save(self): instance = super(SignupForm, self).save(commit=False) if cleaned_data.get('promo'): referrer = SalesRep.objects.get(code=cleaned_data['promo']) else: referrer = None instance.subscription_id = self.subscription['id'] instance.customer_id = self.subscription['customer']['id'] instance.card_type = self.su... | |
value = '' | def render(self, name, value, attrs=None): value = '' if value: value = value.strftime('%I:%M %p') return super(AmPmTimeWidget, self).render(name, value, attrs) | |
CouponUse.objects.create(order=order, coupon=coupon) | CouponUse.objects.create(order=order, coupon=self) | def log_use(self, order): if self.max_clicks: self.click_count += 1 self.save() CouponUse.objects.create(order=order, coupon=coupon) |
return HttpResponseRedirect(str(social.site) + reverse('dashboard')) | return HttpResponseRedirect(str(social.site) + reverse('dashboard_marketing_home')) | def twitter_return(request): auth_dict = get_access_token(request, TWITTER_CONSUMER, TWITTER_CONNECTION, TWITTER_ACCESS_TOKEN_URL, 'twitter') social = Social.objects.get(twitter_screen_name=auth_dict['screen_name']) social.twitter_token = auth_dict['oauth_token'] social.twitter_secret = auth_dict['oauth_token_secret'] ... |
def __init__(self, data=None, site=None, *args, **kwargs): | def __init__(self, data=None, files=None, site=None, *args, **kwargs): | def __init__(self, data=None, site=None, *args, **kwargs): super(LocationForm, self).__init__(data=data, *args, **kwargs) self.fields['schedule'].queryset = site.schedule_set.all() |
upgrades = 0 | upgrades, sides = 0, 0 | def tally(self, item): qty = item['quantity'] base_price = item['variant'].price upgrades = 0 if item.has_key('upgrades'): upgrades = sum(upgrade.price for upgrade in item['upgrades']) if len(item['sides']): sides = sum(side.price for side in item['sides']) return (base_price + upgrades + sides) * qty |
if session_is_stale or (created and not referrer.startswith(unicode(site))): | if session_is_stale or (not created and not referrer.startswith(unicode(site))): | def record_hit(self, site, location, session_id, response_code, request): """Records a single hit to the site, creating a session container where necessary and otherwise grabbing the appropriate session to add the hits to. |
domain = '.'.join(['www', self.domain, self.tld]) | return 'http://' + self.domain | def __unicode__(self): if self.custom_domain: domain = '.'.join(['www', self.domain, self.tld]) else: return self.tiger_domain() return 'http://' + domain |
return 'http://' + domain | def __unicode__(self): if self.custom_domain: domain = '.'.join(['www', self.domain, self.tld]) else: return self.tiger_domain() return 'http://' + domain | |
return os.path.join(settings.CUSTOM_MEDIA_URL, '.'.join([self.domain, self.tld])) | return os.path.join(settings.CUSTOM_MEDIA_URL, self.tiger_domain().lstrip('http://')) | def custom_media_url(self): """Returns a path where site-specific static files can be accessed. """ return os.path.join(settings.CUSTOM_MEDIA_URL, '.'.join([self.domain, self.tld])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.