rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
print top.date_usage + top.STOP_TIMEOUT print now + week print now + week > top.date_usage + top.STOP_TIMEOUT | def _check_timeout(top, res): """ Checks for near timeouts (within 1 week) or already happened timeouts. @param top: Topology to check @type top: topology.Topology @param res: Analysis result object @type res: Result @rtype: None """ import datetime, generic now = datetime.datetime.now() week = datetime.timedelta(week... | |
if self.connector_set.filter(name=con.name).exclude(id=dev.id).count() > 0: | if self.connector_set.filter(name=con.name).exclude(id=con.id).count() > 0: | def connectors_add(self, con): if self.connector_set.filter(name=con.name).exclude(id=dev.id).count() > 0: raise fault.new(fault.DUPLICATE_CONNECTOR_ID, "Duplicate connector id: %s" % con.name) self.connector_set.add(con) |
if pipe_config: start_fd.write("ipfw pipe %d config %s\n" % ( pipe_id, pipe_config ) ) | start_fd.write("ipfw pipe %d config %s\n" % ( pipe_id, pipe_config ) ) | def write_control_scripts(self): """ Write the control scrips for this object and its child objects """ host = self.device.host start_fd=open(self.connector.topology.get_control_script(host.name,"start"), "a") start_fd.write("brctl addbr %s\n" % self.bridge_name ) start_fd.write("ip link set %s up\n" % self.bridge_name... |
logger.lograw(self.output.getValue()) | logger.lograw(self.output.getvalue()) | def check_delete(self): if time.time() - self.started > 3600: if not os.path.exists(config.log_dir + "/tasks"): os.makedirs(config.log_dir + "/tasks") logger = log.Logger(config.log_dir + "/tasks/%s"%self.id) logger.lograw(self.output.getValue()) logger.close() del TaskStatus.tasks[self.id] |
self.host.execute("vzctl start %s --wait" % self.openvz_id, task) | self.host.execute("timeout 60 vzctl start %s --wait" % self.openvz_id, task) | def start_run(self, task): generic.Device.start_run(self, task) for iface in self.interfaces_all(): bridge = self.bridge_name(iface) self.host.bridge_create(bridge) self.host.execute("ip link set %s up" % bridge, task) self.host.execute("vzctl start %s --wait" % self.openvz_id, task) for iface in self.interfaces_all():... |
memory = int(self.host.get_result("[ -s /var/run/qemu-server/%s.pid ] && PROC=`cat /var/run/qemu-server/%s.pid` && [ -e /proc/$PROC/stat ] && cat /proc/$PROC/stat | awk '{print ($24 * 4096)}' || echo 0" % (self.kvm_id, self.kvm_id))) | try: memory = int(self.host.get_result("[ -s /var/run/qemu-server/%s.pid ] && PROC=`cat /var/run/qemu-server/%s.pid` && [ -e /proc/$PROC/stat ] && cat /proc/$PROC/stat | awk '{print ($24 * 4096)}' || echo 0" % (self.kvm_id, self.kvm_id))) except: memory = 0 | def get_resource_usage(self): if self.state == generic.State.CREATED: disk = 0 else: disk = int(self.host.get_result("[ -s /var/lib/vz/images/%s/disk.qcow2 ] && stat -c %%s /var/lib/vz/images/%s/disk.qcow2 || echo 0" % (self.kvm_id, self.kvm_id))) if self.state == generic.State.STARTED: memory = int(self.host.get_resul... |
host.execute("wget -nv %s -O %s" % (self.download_url, dst), task) | if self.download_url: host.execute("wget -nv %s -O %s" % (self.download_url, dst), task) | def upload_to_host(self, host, task): dst = self.get_filename() host.execute("wget -nv %s -O %s" % (self.download_url, dst), task) |
self.host.execute("vzctl set %s --hostname %s_%s --save" % ( self.openvz_id, self.topology.name, self.name ), task) | self.host.execute("vzctl set %s --hostname %s-%s --save" % ( self.openvz_id, self.topology.name.replace("_","-"), self.name ), task) | def prepare_run(self, task): generic.Device.prepare_run(self, task) self.host.execute("vzctl create %s --ostemplate %s" % ( self.openvz_id, self.template ), task) self.host.execute("vzctl set %s --devices c:10:200:rw --capability net_admin:on --save" % self.openvz_id, task) if self.root_password: self.host.execute("vz... |
cmd = [Host.SSH_COMMAND, "root@%s" % self.name, command] | cmd = Host.SSH_COMMAND + ["root@%s" % self.name, command] | def execute(self, command, task=None): cmd = [Host.SSH_COMMAND, "root@%s" % self.name, command] str = self.name + ": " + command + "\n" if task: fd = task.output else: fd = sys.stdout fd.write(str) res = self._exec(cmd) fd.write(res) return res |
cmd = [Host.RSYNC_COMMAND, local_file, "root@%s:%s" % (self.name, remote_file)] | cmd = Host.RSYNC_COMMAND + [local_file, "root@%s:%s" % (self.name, remote_file)] | def upload(self, local_file, remote_file, task=None): cmd = [Host.RSYNC_COMMAND, local_file, "root@%s:%s" % (self.name, remote_file)] str = self.name + ": " + local_file + " -> " + remote_file + "\n" self.execute("mkdir -p $(dirname %s)" % remote_file, task) if task: fd = task.output else: fd = sys.stdout fd.write(str... |
cmd = [Host.RSYNC_COMMAND, "root@%s:%s" % (self.name, remote_file), local_file] | cmd = Host.RSYNC_COMMAND + ["root@%s:%s" % (self.name, remote_file), local_file] | def download(self, remote_file, local_file, task=None): cmd = [Host.RSYNC_COMMAND, "root@%s:%s" % (self.name, remote_file), local_file] str = self.name + ": " + local_file + " <- " + remote_file + "\n" if task: fd = task.output else: fd = sys.stdout fd.write(str) res = self._exec(cmd) fd.write(res) return res |
return self._exec([Host.SSH_COMMAND, "root@%s" % self.name, command]) | return self._exec(Host.SSH_COMMAND+["root@%s" % self.name, command]) | def get_result(self, command): return self._exec([Host.SSH_COMMAND, "root@%s" % self.name, command]) |
print "Checking topology timeouts" | def cleanup(): print "Checking topology timeouts" for top in all(): top.check_timeout() | |
if self.device_set.filter(name=dev.name).count() > 0: | if self.device_set.filter(name=dev.name).exclude(id=dev.id).count() > 0: | def devices_add(self, dev): if self.device_set.filter(name=dev.name).count() > 0: raise fault.new(fault.DUPLICATE_DEVICE_ID, "Duplicate device id: %s" % dev.name) self.device_set.add(dev) |
if self.connector_set.filter(name=con.name).count() > 0: | if self.connector_set.filter(name=con.name).exclude(id=dev.id).count() > 0: | def connectors_add(self, con): if self.connector_set.filter(name=con.name).count() > 0: raise fault.new(fault.DUPLICATE_CONNECTOR_ID, "Duplicate connector id: %s" % con.name) self.connector_set.add(con) |
return self.dhcpdevice.upcast() | return self.dhcpddevice.upcast() | def upcast(self): if self.is_dhcpd(): return self.dhcpdevice.upcast() if self.is_kvm(): return self.kvmdevice.upcast() if self.is_openvz(): return self.openvzdevice.upcast() return self |
for iface in device.interfaces_all(): | for iface in device.interface_set_all(): | def get_best_host(group, device=None): all_hosts = Host.objects.filter(enabled=True) # pylint: disable-msg=E1101 if group: all_hosts = all_hosts.filter(group=group) if device: for iface in device.interfaces_all(): if iface.is_connected(): sf = iface.connection.connector.upcast() if sf.is_special(): if sf.feature_group:... |
tincname = self.tincname(con) | def prepare_run(self, task): generic.Connector.prepare_run(self, task) for con in self.connections_all(): host = con.interface.device.host tincname = self.tincname(con) tincport = self.tincport(con) path = self.topology.get_control_dir(host.name) + "/" + tincname if not os.path.exists(path+"/hosts"): os.makedirs(path+"... | |
return not self.subtasks_done == self.subtasks_total | return self.subtasks_done < self.subtasks_total | def is_active(self): return not self.subtasks_done == self.subtasks_total |
return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "done": self.subtasks_done==self.subtasks_total, "started": self.started} | return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "done": self.subtasks_done>=self.subtasks_total, "started": self.started} | def dict(self): return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "done": self.subtasks_done==self.subtasks_total, "started": self.started} |
return index(api, request) | return index(request) | def remove(api, request, top_id): api.top_remove(int(top_id)) return index(api, request) |
HostStore.add(argv[0]) | HostStore.add(Host(argv[0])) | def host_add(argv): if not len(argv) == 1: usage(None) return HostStore.add(argv[0]) |
con = self.interface.connection raise fault.new(fault.DUPLICATE_INTERFACE_CONNECTION, "Interface %s is connected to %s and %s" % (self.interface, self.interface.connection, self) ) | if not self.interface.connection == self: raise fault.new(fault.DUPLICATE_INTERFACE_CONNECTION, "Interface %s is connected to %s and %s" % (self.interface, self.interface.connection, self) ) | def decode_xml(self, dom): try: device_name = dom.getAttribute("device") device = self.connector.topology.devices_get(device_name) iface_name = dom.getAttribute("interface") self.interface = device.interfaces_get(iface_name) try: con = self.interface.connection raise fault.new(fault.DUPLICATE_INTERFACE_CONNECTION, "Int... |
return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "status": self.status, "done": self.status==TaskStatus.DONE, "started": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(self.started))} | return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "status": self.status, "active": self.status == TaskStatus.ACTIVE, "failed": self.status == TaskStatus.FAILED, "done": self.status==TaskStatus.DONE, "started": time.strftime("%Y-%m-%d %H:... | def dict(self): return {"id": self.id, "output": self.output.getvalue(), "subtasks_done": self.subtasks_done, "subtasks_total": self.subtasks_total, "status": self.status, "done": self.status==TaskStatus.DONE, "started": time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(self.started))} |
self.output.write(exc) | self.output.write('%s:%s' % (exc.__class__.__name__, exc)) | def _run(self): try: self.func(*self.args, task=self, **self.kwargs) self.done() except Exception, exc: fault.errors_add('%s:%s' % (exc.__class__.__name__, exc), traceback.format_exc()) self.output.write(exc) self.failed() |
dev.type = type | dev.type = dtype | def run(self, top, task): #print "applying %s" % self if self.type == "topology-rename": top.name = self.properties["name"] top.save() elif self.type == "device-create": dtype = self.properties["type"] import kvm, openvz if dtype == "kvm": dev = kvm.KVMDevice() elif dtype == "openvz": dev = openvz.OpenVZDevice() else: ... |
con.type = type | con.type = ctype | def run(self, top, task): #print "applying %s" % self if self.type == "topology-rename": top.name = self.properties["name"] top.save() elif self.type == "device-create": dtype = self.properties["type"] import kvm, openvz if dtype == "kvm": dev = kvm.KVMDevice() elif dtype == "openvz": dev = openvz.OpenVZDevice() else: ... |
result["ifconfig"] = self.get_result("ifconfig -a") | def debug_info(self): result={} result["OpenVZ"] = self.get_result("vzlist -a") result["KVM"] = self.get_result("qm list") result["Bridges"] = self.get_result("brctl show") result["iptables router"] = self.get_result("iptables -t mangle -v -L PREROUTING") result["ipfw rules"] = self.get_result("ipfw show") result["ipfw... | |
disk = int(self.host.get_result("du -sb /var/lib/vz/private/%s | awk '{print $1}'" % self.openvz_id)) | try: disk = int(self.host.get_result("du -sb /var/lib/vz/private/%s | awk '{print $1}'" % self.openvz_id)) except: disk = 0 | def get_resource_usage(self): if self.state == generic.State.CREATED: disk = 0 elif self.state == generic.State.STARTED: disk = int(self.host.get_result("grep -h -A 1 -E '^%s:' /proc/vz/vzquota | tail -n 1 | awk '{print $2}'" % self.openvz_id))*1024 else: disk = int(self.host.get_result("du -sb /var/lib/vz/private/%s |... |
con = TincConnection() con.init(self, connection) self.connection_set.add ( con ) | self.add_connection(connection) def add_connection(self, dom): con = TincConnection() con.init (self, dom) con.bridge_special_name = con.interface.device.host.public_bridge self.connection_set.add ( con ) self.save() return con | def init(self, topology, dom): self.topology = topology self.decode_xml(dom) self.save() for connection in dom.getElementsByTagName ( "connection" ): con = TincConnection() con.init(self, connection) self.connection_set.add ( con ) |
function(args, user=user) | return function(*args, user=user) | def execute(self, function, args, user): |
defer.maybeDeferred(self.execute, function, *args, user=user).addErrback(self._ebRender).addCallback(self._cbRender,request) | defer.maybeDeferred(self.execute, function, args, user).addErrback(self._ebRender).addCallback(self._cbRender,request) | def render(self, request): username = request.getUser() passwd = request.getPassword() user = self.authenticate(username, passwd) if not user.is_valid: request.setResponseCode(http.UNAUTHORIZED) if username=='' and passwd=='': return 'Authorization required!' else: return 'Authorization Failed!' request.content.seek(0,... |
if self.interfaces_get(iface.name): raise fault.new(fault.DUPLICATE_INTERFACE_NAME, "Duplicate interface id: %s" % iface ) | def interfaces_add(self, iface): if self.interfaces_get(iface.name): raise fault.new(fault.DUPLICATE_INTERFACE_NAME, "Duplicate interface id: %s" % iface ) return self.interface_set.add(iface) | |
host.execute("rm -r %s %s.pid" % (dir, dir), task ) | if host: host.execute("rm -r %s %s.pid" % (dir, dir), task ) | def destroy_run(self, task): generic.Connection.destroy_run(self, task) host = self.interface.device.host dir = self._capture_dir() host.execute("rm -r %s %s.pid" % (dir, dir), task ) |
del users[user.name] | del users[user.user.name] | def cleanup(): for user in users.values(): if time.time() - user.cachetime > 3600: del users[user.name] |
name=request.REQUEST["name"] type=request.REQUEST["type"] api.template_add(name, type) return index(request) | if request.REQUEST.has_key("name"): name=request.REQUEST["name"] type=request.REQUEST["type"] api.template_add(name, type) return index(request) else: return render_to_response("admin/template_add.html") | def add(api, request): name=request.REQUEST["name"] type=request.REQUEST["type"] api.template_add(name, type) return index(request) |
if self.gateway: | if self.gateway and self.connector.type == "router": | def encode_xml(self, dom, doc, internal): dummynet.EmulatedConnection.encode_xml(self, dom, doc, internal) if self.gateway: dom.setAttribute("gateway", self.gateway) if internal: if self.tinc_port: dom.setAttribute("tinc_port", str(self.tinc_port)) |
self.gateway = util.get_attr(dom, "gateway", default="10.1.1.254/24") if not len(self.gateway.split("/")) == 2: self.gateway = self.gateway + "/24" | self.gateway = util.get_attr(dom, "gateway", default=None) if self.connector.type == "router": if not self.gateway: self.gateway = "10.1.1.254/24" if not len(self.gateway.split("/")) == 2: self.gateway = self.gateway + "/24" | def decode_xml(self, dom): dummynet.EmulatedConnection.decode_xml(self, dom) self.gateway = util.get_attr(dom, "gateway", default="10.1.1.254/24") if not len(self.gateway.split("/")) == 2: self.gateway = self.gateway + "/24" |
stop_fd=open(self.topology.get_deploy_script(host.name,"stop"), "a") | stop_fd=open(self.connector.topology.get_deploy_script(host.name,"stop"), "a") | def write_deploy_script(self): start_fd=open(self.connector.topology.get_deploy_script(host.name,"start"), "a") start_fd.write("brctl addbr %s\n" % self.bridge_name ) start_fd.write("ip link set %s up\n" % self.bridge_name ) if self.bridge_id: pipe_id = self.bridge_id * 10 pipe_config="" start_fd.write("modprobe ipfw_m... |
return Template.objects.get(type=type, name=name) | return Template.objects.get(type=type, name=name).name | def get_template(type, name): try: return Template.objects.get(type=type, name=name) except Exception, exc: return get_default_template(type) |
iface.upcast.start_run(iface, task) | iface.upcast().start_run(iface, task) | def start_run(self, task): generic.Device.start_run(self, task) for iface in self.interfaces_all(): bridge = self.bridge_name(iface) self.host.execute("brctl addbr %s" % bridge, task) self.host.execute("ip link set %s up" % bridge, task) self.host.execute("vzctl start %s --wait" % self.openvz_id, task) for iface in sel... |
properties += _xml_attrs_to_dict(pr.attributes) | properties.update(_xml_attrs_to_dict(pr.attributes)) | def read_from_dom(dom): modlist = [] for mod in dom.getElementsByTagName("modification"): type = mod.getAttribute("type") element = util.get_attr(mod, "element", None) subelement = util.get_attr(mod, "subelement", None) properties = {} for pr in mod.getElementsByTagName("properties"): properties += _xml_attrs_to_dict(p... |
return {"disk": res.disk, "memory": res.memory, "ports": res.ports, "public_ips": res.public_ips} | return {"disk": str(res.disk), "memory": str(res.memory), "ports": res.ports, "public_ips": res.public_ips} | def _resources_info(res): return {"disk": res.disk, "memory": res.memory, "ports": res.ports, "public_ips": res.public_ips} |
self.delay_Stddev = ( 1.0 - self.sliding_factor ) * self.delay_stddev + self.sliding_factor * delay_stddev | self.delay_stddev = ( 1.0 - self.sliding_factor ) * self.delay_stddev + self.sliding_factor * delay_stddev | def adapt(self, loss, delay_avg, delay_stddev): self.loss = ( 1.0 - self.sliding_factor ) * self.loss + self.sliding_factor * loss self.delay_avg = ( 1.0 - self.sliding_factor ) * self.delay_avg + self.sliding_factor * delay_avg self.delay_Stddev = ( 1.0 - self.sliding_factor ) * self.delay_stddev + self.sliding_factor... |
dict[r.type] = r.value | dict[r.type] = str(r.value) | def encode(self): dict = {} for r in self.resourceentry_set.all(): dict[r.type] = r.value return dict |
res[k] = res[k] + v | res[k] = str(int(res[k]) + int(v)) | def add_encoded_resources(r1, r2): res = {} for k, v in r1.items(): if k in res: res[k] = res[k] + v else: res[k] = v for k, v in r2.items(): if k in res: res[k] = res[k] + v else: res[k] = v return res |
if self.host_name: fd.write("vzctl set %s --hostname %s --save\n" % ( self.openvz_id, self.host_name ) ) else: fd.write("vzctl set %s --hostname %s --save\n" % ( self.openvz_id, self.id ) ) | fd.write("vzctl set %s --hostname %s --save\n" % ( self.openvz_id, self.id ) ) | def write_control_script(self, host, script, fd): """ Write the control script for this object and its child objects """ if script == "prepare": fd.write("vzctl create %s --ostemplate %s\n" % ( self.openvz_id, self.template ) ) fd.write("vzctl set %s --devices c:10:200:rw --capability net_admin:on --save\n" % self.ope... |
fd.write("( while true; do vncterm -rfbport %s -passwd %s -c vzctl enter %s ; done ) & echo $! > vnc-%s.pid" % ( self.vnc_port, self.vnc_password(), self.openvz_id, self.id ) ) | fd.write("( while true; do vncterm -rfbport %s -passwd %s -c vzctl enter %s ; done ) >/dev/null 2>&1 & echo $! > vnc-%s.pid" % ( self.vnc_port, self.vnc_password(), self.openvz_id, self.id ) ) | def write_control_script(self, host, script, fd): """ Write the control script for this object and its child objects """ if script == "prepare": fd.write("vzctl create %s --ostemplate %s\n" % ( self.openvz_id, self.template ) ) fd.write("vzctl set %s --devices c:10:200:rw --capability net_admin:on --save\n" % self.ope... |
return self.device.interface_device(self) | return self.device.upcast().interface_device(self) | def interface_name(self): return self.device.interface_device(self) |
os.rename(temp, full) | shutil.move(temp, full) | def closeTempFile(self, temp, full): """ Perform final cache set as atomic FS operation. """ logger.debug("Created image cache file:" + full) os.rename(temp, full) |
if is_mobile(context, request): | if need_reset(context, request): | def set_mobile_html_content_type(object, event): """ Post publication hook which sets HTML content type so that the page is understood as a mobile page. NOTE: This should be done for Googlebot and other mobile aware search bots only! Various *real* mobile handsets blow up if you try to feed them anything else beside t... |
request = site.REQUEST if is_mobile(site, request): return get_mobile_skin_name(site, request) else: return self.default_skin | request = getattr(site, "REQUEST", None) if request: if is_mobile(site, request): return get_mobile_skin_name(site, request) return self.default_skin | def getDefaultSkin(self): """ Get the default skin name. """ site = self request = site.REQUEST if is_mobile(site, request): return get_mobile_skin_name(site, request) else: return self.default_skin |
return properties.mobile_domain_prefixes[0] + "." + domain | if properties.mobile_domain_prefixes: return properties.mobile_domain_prefixes[0] + "." + domain else: logger.warn('No mobile_domain_prefixes found.') | def prefixDomain(self, domain, mode): """ Add subdomain discriminator to domain host name |
return properties.preview_domain_prefixes[0] + "." + domain else: return domain | if properties.preview_domain_prefixes: return properties.preview_domain_prefixes[0] + "." + domain else: logger.warn('No preview_domain_prefixes found.') return domain | def prefixDomain(self, domain, mode): """ Add subdomain discriminator to domain host name |
elif url.startswith("++resource"): | elif "++resource" in url: | def mapURL(self, url): """ Make image URL relative to site root. If possible, make URI relative to site root so that we can safely pass it around from a page to another. If URL is absolute, don't touch it. @param url: Image URL or URI as a string """ # Make sure we are traversing the context chain without view obj... |
physicalPath = imageObject.getPhysicalPath() assert len(physicalPath) > 2 virtualPath = physicalPath[2:] virtualPath = self.removeScale(virtualPath) url = "/".join(virtualPath) | if ("FileResource" in imageObject.__class__.__name__): return url elif hasattr(imageObject, "getPhysicalPath"): physicalPath = imageObject.getPhysicalPath() virtualPath = self.request.physicalPathToVirtualPath(physicalPath) assert len(physicalPath) > 2 virtualPath = physicalPath[2:] virtualPath = self.removeSc... | def mapURL(self, url): """ Make image URL relative to site root. If possible, make URI relative to site root so that we can safely pass it around from a page to another. If URL is absolute, don't touch it. @param url: Image URL or URI as a string """ # Make sure we are traversing the context chain without view obj... |
self.location_manager = getUtility(IMobileSiteLocationManager) | self.location_manager = getMultiAdapter((self.context, self.request), IMobileSiteLocationManager) | def __init__(self, context, request): self.context = context self.request = request self.discriminator = getUtility(IMobileRequestDiscriminator) self.location_manager = getUtility(IMobileSiteLocationManager) self.request_flags = self.discriminator.discriminate(self.context, self.request) |
return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.MOBILE) | return self.location_manager.rewriteURL(self.context.absolute_url(), MobileRequestType.MOBILE) | def getMobileSiteURL(self): """ Return the mobile version of this context""" return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.MOBILE) |
return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.PREVIEW) | return self.location_manager.rewriteURL(self.context.absolute_url(), MobileRequestType.PREVIEW) | def getMobilePreviewURL(self): """ Return URL used in phone simualtor. """ return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.PREVIEW) |
return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.WEB) | return self.location_manager.rewriteURL(self.context.absolute_url(), MobileRequestType.WEB) | def getWebSiteURL(self): """ Return the web version URL of this of context """ return self.location_manager.rewriteURL(self.request, self.context.absolute_url(), MobileRequestType.WEB) |
print self.browser.contents | def test_mobile_sitemap(self): """ Check that accuracy of UA match is delivered to us correctly. """ url = self.portal.absolute_url() + "/@@mobile_sitemap?mode=mobile&language=en&uncompressed" self.browser.open(url) print self.browser.contents self.assertTrue('xmlns:mobile="http://www.google.com/schemas/sitemap-mobil... | |
try: location_manager = getMultiAdapter((context, self.request), IMobileSiteLocationManager) except: return | location_manager = getMultiAdapter((context, self.request), IMobileSiteLocationManager) | def redirect_url(self, url, query_string, media_type=MobileRequestType.MOBILE): """ HTTP redirect to a mobile site matching certain URL. @param url: Base URL to rewrite @param query_string: Incoming query string on the orignal request (for analytics preservation etc.) @param media_type: Target media type. "www" or "... |
raise RuntimeError("Current selected mobile theme " + skin_name + " is not installed on the site. Please install a mobile theme add-on using Add On installer in site setup.") | raise RuntimeError( "Current selected mobile theme %s is not installed on the " "site. Please install a mobile theme add-on using Add On " "installer in site setup." % skin_name) | def get_mobile_skin_name(site, request): """ @return: Mobile theme name for a Plone site object """ properties = site.portal_properties if hasattr(properties, "mobile_properties"): # Plone Mobile quickinstaller has been run # and we have mobile theme specifc files registeed mobile_properties = properties.mobile_prop... |
from Products.PluggableAuthService.plugins.CookieAuthHelper import CookieAuthHelper | from Products.PluggableAuthService.plugins.CookieAuthHelper import \ CookieAuthHelper | def getDefaultSkin(self): """ Get the default skin name. """ site = self request = getattr(site, "REQUEST", None) if request: if is_mobile(site, request): return get_mobile_skin_name(site, request) return self.default_skin |
logger.warn("Mobilized Plone site must be configured to be accessed using subdomains.") | logger.warn("Mobilized Plone site must be configured to be accessed " "using subdomains.") | def getCookieDomain(request): """ Get a parent domain name to be used in the cookie One cookie covers all *.yoursite.com domains. """ if "SERVER_URL" in request.environ: # WSGI based servers server_url = request.environ["SERVER_URL"] else: # Zope's Medusa server_url = request.other["SERVER_URL"] parts = urlparse.url... |
logger.warn("..and access site site using fake domain name web.site.foo.") logger.warn("Also DO NOT do Zope HTTP Basic Auth, since it is not subdomain aware - use only Plone interface for login") | logger.warn("..and access site site using fake domain name " "web.site.foo.") logger.warn("Also DO NOT do Zope HTTP Basic Auth, since it is not " "subdomain aware - use only Plone interface for login") | def getCookieDomain(request): """ Get a parent domain name to be used in the cookie One cookie covers all *.yoursite.com domains. """ if "SERVER_URL" in request.environ: # WSGI based servers server_url = request.environ["SERVER_URL"] else: # Zope's Medusa server_url = request.other["SERVER_URL"] parts = urlparse.url... |
raise RuntimeError("You need to use subdomain to access the site. E.g. web.localhost instead of localhost") | raise RuntimeError("You need to use subdomain to access the site. " "E.g. web.localhost instead of localhost") | def getCookieDomain(request): """ Get a parent domain name to be used in the cookie One cookie covers all *.yoursite.com domains. """ if "SERVER_URL" in request.environ: # WSGI based servers server_url = request.environ["SERVER_URL"] else: # Zope's Medusa server_url = request.other["SERVER_URL"] parts = urlparse.url... |
@return: True or False | def isPreviewRequest(self, site, request, prefixes): """ Determine should this request be rendered in mobile mode. | |
return not site.portal_membership.isAnonymousUser() | return not getToolByName(site, 'portal_membership').isAnonymousUser() | def isAdminRequest(self, site, request): """ By default, assume all logged in users are admins. """ return not site.portal_membership.isAnonymousUser() |
properties = context.portal_properties.mobile_properties | portal_properties = getToolByName(context, "portal_properties") properties = portal_properties.mobile_properties | def discriminate(self, context, request): |
logger.warn("Cannot access mobile properties") | logger.info("Cannot access mobile properties, having context:" + context_desc) | def discriminate(self, context, request): |
print "Active template id:" + template | def constructListing(self): | |
imageObject = context.unrestrictedTraverse(url) | site = getSite() try: imageObject = context.unrestrictedTraverse(url) except Unauthorized: parent_path = '/'.join(url.split('/')[:-1]) image_path = url.split('/')[-1] parent = site.unrestrictedTraverse(parent_path) imageObject = parent.restrictedTraverse(image_path) | def mapURL(self, url): """ Make image URL relative to site root. If possible, make URI relative to site root so that we can safely pass it around from a page to another. If URL is absolute, don't touch it. @param url: Image URL or URI as a string """ # Make sure we are traversing the context chain without view obj... |
mobileFolderListing = FieldPropertyDelegate(IMobileBehavior["mobileFolderListing"]) | mobileFolderListing = FieldProperty(IMobileBehavior["mobileFolderListing"]) | def __getattr__(self, name): return getattr(self.__field, name) |
appearInFolderListing = FieldPropertyDelegate(IMobileBehavior["appearInFolderListing"]) | appearInFolderListing = FieldProperty(IMobileBehavior["appearInFolderListing"]) | def __getattr__(self, name): return getattr(self.__field, name) |
logger.warn("See twinapex.plone.mobile.monkeypatch for more info") | logger.warn("See gomobile.mobile.monkeypatch for more info") | def getCookieDomain(request): """ Get a parent domain name to be used in the cookie One cookie covers all *.yoursite.com domains. """ if "SERVER_URL" in request.environ: # WSGI based servers server_url = request.environ["SERVER_URL"] else: # Zope's Medusa server_url = request.other["SERVER_URL"] parts = urlparse.url... |
debug = mobile_properties.tracker_debug | debug = getattr(mobile_properties, "tracker_debug", None) | def update(self, trackingId=None): """ Look up tracker and make it generate tracking HTML snippet """ mobile_properties = getCachedMobileProperties(self.context, self.request) |
print "Got TC:" + self.trackingCode | def render(self): """ Render the HTML snippet """ print "Got TC:" + self.trackingCode return self.trackingCode | |
location_manager = getMultiAdapter((context, self.request), IMobileSiteLocationManager) | try: location_manager = getMultiAdapter((context, self.request), IMobileSiteLocationManager) except: return | def redirect_url(self, url, query_string, media_type=MobileRequestType.MOBILE): """ HTTP redirect to a mobile site matching certain URL. @param url: Base URL to rewrite @param query_string: Incoming query string on the orignal request (for analytics preservation etc.) @param media_type: Target media type. "www" or "... |
elif "HTTP_HOST" in request.environ: | elif "REMOTE_ADDR" in request.environ: | def get_ip(request): """ Extract the client IP address from the HTTP request in proxy compatible way. @return: IP address as a string or None if not available """ if "HTTP_X_FORWARDED_FOR" in request.environ: # Virtual host ip = request.environ["HTTP_X_FORWARDED_FOR"] elif "HTTP_HOST" in request.environ: # Non-virtua... |
return detect_mobile_browser(ua) | if ua: return detect_mobile_browser(ua) else: return False | def isMobileBrowser(self): ua = get_user_agent(self.request) return detect_mobile_browser(ua) |
if item["exclude_from_nav"]: | if item.getExcludeFromNav(): | def show(item): """ @param item: Brain |
return "." + domain_rot | return "." + domain_root | def getCookieDomain(request): """ Get a parent domain name to be used in the cookie One cookie covers all *.yoursite.com domains. """ if "SERVER_URL" in request.environ: # WSGI based servers server_url = request.environ["SERVER_URL"] else: # Zope's Medusa server_url = request.other["SERVER_URL"] parts = urlparse.url... |
""" | @param url: Image URL or URI as a string """ context = self.context.aq_inner | def mapURL(self, url): """ Make image URL relative to site root. If possible, make URI relative to site root so that we can safely pass it around from a page to another. If URL is absolute, don't touch it. """ if url.startswith("http://"): # external URL url = url elif url.startswith("++resource"): # Zope 3 resources... |
imageObject = self.context.unrestrictedTraverse(url) | imageObject = context.unrestrictedTraverse(url) | def mapURL(self, url): """ Make image URL relative to site root. If possible, make URI relative to site root so that we can safely pass it around from a page to another. If URL is absolute, don't touch it. """ if url.startswith("http://"): # external URL url = url elif url.startswith("++resource"): # Zope 3 resources... |
print "Active template id:" + template | def constructListing(self): | |
print "Performing mobile folder listing" | def constructListing(self): | |
print 'generating traverse functions for class', c.name() | print 'generating builder functions for class', c.name() | def make_builder_inc_file(filename, class_text, expression_class): result = [] classes = parse_classes(class_text) for c in classes: if c.qualifier() != '': # skip classes residing in a different name space continue print 'generating traverse functions for class', c.name() f = c.constructor parameters = [] for p in f.p... |
if extract_type(p.type()) != expression_class: | if extract_type(p.type()) not in [expression_class, expression_class + '_list']: | def make_builder_inc_file(filename, class_text, expression_class): result = [] classes = parse_classes(class_text) for c in classes: if c.qualifier() != '': # skip classes residing in a different name space continue print 'generating traverse functions for class', c.name() f = c.constructor parameters = [] for p in f.p... |
def make_classes(filename, class_text, superclass = None, namespace = 'core', add_constructor_overloads = False, superclass_aterm = None): | def make_classes(filename, class_text, superclass = None, namespace = 'core', add_constructor_overloads = False, superclass_aterm = None, generate_is_functions = False): | def make_classes(filename, class_text, superclass = None, namespace = 'core', add_constructor_overloads = False, superclass_aterm = None): classes = parse_classes(class_text, superclass, use_base_class_name = True) # skip the classes with a namespace qualifier (they are defined elsewhere) classes = [c for c in classes... |
make_classes( '../../lps/include/mcrl2/modal_formula/state_formula.h', STATE_FORMULA_CLASSES, 'state_formula') make_is_functions('../../lps/include/mcrl2/modal_formula/state_formula.h', STATE_FORMULA_CLASSES, 'state_formula') make_classes( '../../lps/include/mcrl2/modal_formula/regular_formula.h', REGULAR_FORM... | make_classes('../../bes/include/mcrl2/bes/boolean_expression.h', BOOLEAN_EXPRESSION_CLASSES, 'boolean_expression', generate_is_functions = True, superclass_aterm = 'BooleanExpression') make_classes('../../data/include/mcrl2/data/assignment.h', ASSIGNMENT_EXPRESSION_CLASSES, 'assignment_expression', add_constructor_over... | def make_is_functions(filename, class_text, classname, namespace = 'core'): TERM_TRAITS_TEXT = r''' /// \\brief Test for a %s expression /// \\param t A term /// \\return True if it is a %s expression inline bool is_%s(const %s& t) { return %s::detail::gsIs%s(t); } |
make_classes('../../data/include/mcrl2/data/', DATA_EXPRESSION_CLASSES, 'data_expression', add_constructor_overloads = True) make_is_functions('../../data/include/mcrl2/data/data_expression.h', DATA_EXPRESSION_CLASSES, 'data_expression') make_classes('../../data/include/mcrl2/data/assignment.h', ASSIGNMENT_EXPRESSION_C... | make_classes('../../process/include/mcrl2/process/process_expression.h', PROCESS_EXPRESSION_CLASSES, 'process_expression', generate_is_functions = True, superclass_aterm = 'ProcExpr') make_classes('../../data/include/mcrl2/data/data_expression.h', DATA_EXPRESSION_CLASSES, 'data_expression', add_constructor_overloads ... | def make_is_functions(filename, class_text, classname, namespace = 'core'): TERM_TRAITS_TEXT = r''' /// \\brief Test for a %s expression /// \\param t A term /// \\return True if it is a %s expression inline bool is_%s(const %s& t) { return %s::detail::gsIs%s(t); } |
DERIVED_CLASS_CONSTRUCTOR = r''' /// \\brief Constructor. | DERIVED_CLASS_CONSTRUCTOR = r''' /// \\\\brief Constructor. | def class_member_functions(self): result = [] index = 1 for p in self.parameters(): result.append(member_function(str(p), index)) index = index + 1 return result |
/// \\brief Constructor. | /// \\\\brief Constructor. | def class_member_functions(self): result = [] index = 1 for p in self.parameters(): result.append(member_function(str(p), index)) index = index + 1 return result |
mtext = '\n\n' + mtext | mtext = '\n' + mtext | def class_definition(self, superclass = None, namespace = 'core', use_base_class_name = True, add_container_typedefs = True): f = self.constructor if use_base_class_name: classname = self.base_classname constructor = str(self.base_class_constructor) else: classname = self.classname constructor = str(self.constructor) |
ctext = Class(superclass_aterm, '%s()' % superclass, 'class %s' % superclass, superclass = None, use_base_class_name = False).class_inline_definition(namespace, True, add_constructor_overloads) + ctext | text = Class(superclass_aterm, '%s()' % superclass, 'class %s' % superclass, superclass = None, use_base_class_name = False).class_inline_definition(namespace, True, add_constructor_overloads) text = re.sub('check_term', 'check_rule', text) ctext = text + ctext | def make_class_declarations(filename, class_text, superclass = None, namespace = 'core', add_constructor_overloads = False, superclass_aterm = None): classes = parse_classes(class_text, superclass, use_base_class_name = True) # skip the classes with a namespace qualifier (they are defined elsewhere) classes = [c for c... |
def type(self, include_modifiers = True, include_namespace = False): | def type(self, include_modifiers = True, include_namespace = False, remove_templates = False): | def type(self, include_modifiers = True, include_namespace = False): type1 = self.type_ if include_namespace and extract_namespace(type1) == None: type1 = '%s::%s' % (self.namespace(), type1) if include_modifiers: if 'const' in self.modifiers_: prefix = 'const ' else: prefix = '' if '*' in self.modifiers_: postfix = '*... |
text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x) | text = r'''<RETURN_TYPE> operator()(<CONST><CLASS_NAME>& x) | def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x) |
static_cast<Derived&>(*this).enter(x);VISIT_TEXT static_cast<Derived&>(*this).leave(x);RETURN_STATEMENT | static_cast<Derived&>(*this).enter(x);<VISIT_TEXT> static_cast<Derived&>(*this).leave(x);<RETURN_STATEMENT> | def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x) |
if modifiability_map[classname]: | if is_modifiable_type(classname, modifiability_map): | def builder_function(self, all_classes, dependencies, modifiability_map): text = r'''RETURN_TYPE operator()(<CONST>CLASS_NAME& x) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.